用Blazor和DeepSeek API创建聊天应用

B站影视 2025-02-06 09:22 2

摘要:本文将指导您如何使用Blazor框架和DeepSeek API构建一个简单的聊天应用。Blazor是一个用于构建交互式Web UI的框架,它允许开发者使用C#编写前端代码。DeepSeek API则提供强大的自然语言处理能力,使得应用程序能够理解和生成人类语言

本文将指导您如何使用Blazor框架和DeepSeek API构建一个简单的聊天应用。Blazor是一个用于构建交互式Web UI的框架,它允许开发者使用C#编写前端代码。DeepSeek API则提供强大的自然语言处理能力,使得应用程序能够理解和生成人类语言。

首先,创建一个新的Blazor Server项目:

dotnet new blazorserver -o BlazorDeepSeekChat// 添加HttpClient服务
builder.Services.AddScoped(sp => new HttpClient);
//设置HttpClient授权
// 添加配置
builder.Services.Configure(
builder.Configuration.GetSection("DeepSeek"));

// 注册授权HttpClient
builder.Services.AddHttpClient("DeepSeek", (sp, client) => {
var settings = sp.GetRequiredService>.Value;
client.BaseAddress = new Uri(settings.ApiUrl);
client.DefaultrequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.ApiKey);
});
@page "/"
@inject HttpClient Http

DeepSeek Chat





@foreach (var message in messages)
{

@message.Content

}





@if (isSending) {
发送中...
} else {
发送
}





.chat-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}

.message-list {
height: 500px;
overflow-y: auto;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}

.message {
margin: 10px 0;
padding: 8px 12px;
border-radius: 15px;
max-width: 70%;
}

.user {
background: #007bff;
color: white;
margin-left: auto;
}

.assistant {
background: #e9ecef;
margin-right: auto;
}

.input-area {
display: flex;
gap: 10px;
}

textarea {
flex: 1;
height: 80px;
padding: 10px;
}
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Runtime;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;

namespaceBlazorDeepSeekChat.Pages;

publicpartialclassIndex
{
privatereadonly List messages = new;
privatestringinputText =string.Empty;
privateboolisSending =false;
private HttpClient _httpClient;
private IConfiguration _configuration;

// 使用 @inject 注入 HttpClient 和 IConfiguration
[Inject]
private HttpClient HttpClient { get; set; }

[Inject]
private IConfiguration Configuration { get; set; }

protected override voidOnInitialized
{
_httpClient = HttpClient;
_configuration = Configuration;

// 设置 API 地址
_httpClient.BaseAddress = new Uri(_configuration["DeepSeek:ApiUrl"]);

// 添加认证头
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_configuration["DeepSeek:ApiKey"]}");

}

private async TaskSendMessage
{
if (string.IsOrWhiteSpace(inputText) || isSending) return;

try
{
var payload = new
{
model = "deepseek-chat",
messages = new { new { role = "user", content = inputText } },
temperature = "0.7",
max_tokens =1000
};

try
{
// 创建请求内容
var requestContent = new StringContent(inputText, Encoding.UTF8, "application/json");

// 发送 POST 请求
//var response = await _httpClient.PostAsync(_configuration["DeepSeek:ApiUrl"], requestContent);

var response = await _httpClient.PostAsJsonAsync(_configuration["DeepSeek:ApiUrl"], payload);
response.EnsureSuccessStatusCode;

var result = await response.Content.ReadFromJsonAsync;
var assistantMessage = new ChatMessage("assistant", result?.Choices[0].Message.Content ?? "");

messages.Add(assistantMessage);
//return result?.Choices[0].Message.Content ?? string.Empty;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP Error: {ex.StatusCode}");
Console.WriteLine($"Response: {ex.Message}");
thrownew Exception("API 请求失败,请检查配置和网络连接。");
}

}
catch (Exception ex)
{
messages.Add(new ChatMessage("error", $"错误: {ex.Message}"));
}
finally
{
isSending =false;
}
}

private recordChatMessage(stringRole,stringContent)
{
publicstringClass => Role switch
{
"user" => "user",
"assistant" => "assistant",
_ => "error"
};
}

privateclassDeepSeekResponse
{
public List Choices { get; set; } = new;

publicclassChoice
{
public Message Message { get; set; } = new;
}

publicclassMessage
{
publicstringContent { get; set; } =string.Empty;
}
}
}

5. 配置API访问(需在wwwroot/appsettings.json添加)

{
"DeepSeek": {
"ApiKey": "api_key",
"ApiUrl": "https://api.deepseek.com/v1/chat/completions"
}
}

DeepSeekSettings 实体

public class DeepSeekSettings
{
///
/// DeepSeek API 的基础地址
///
public string ApiUrl { get; set; } = string.Empty;

///
/// DeepSeek API 的访问密钥
///
public string ApiKey { get; set; } = string.Empty;

///
/// 默认使用的模型名称
///
public string DefaultModel { get; set; } = "deepseek-chat";

///
/// API 请求的温度参数(控制生成文本的随机性)
///
public double Temperature { get; set; } =0.7;

///
/// API 请求的最大令牌数(控制生成文本的长度)
///
public int MaxTokens { get; set; } =1000;
}

来源:opendotnet

相关推荐