部署DeepSeek模型,进群交流最in玩法!
立即加群
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >用Blazor和DeepSeek API创建聊天应用

用Blazor和DeepSeek API创建聊天应用

作者头像
郑子铭
发布2025-03-21 13:14:47
发布2025-03-21 13:14:47
9800
代码可运行
举报
运行总次数:0
代码可运行

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

1. 创建项目

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

代码语言:javascript
代码运行次数:0
运行
复制
dotnet new blazorserver -o BlazorDeepSeekChat

2. 添加必要服务(Program.cs)

代码语言:javascript
代码运行次数:0
运行
复制
// 添加HttpClient服务
builder.Services.AddScoped(sp => new HttpClient());
//设置HttpClient授权
// 添加配置
builder.Services.Configure<DeepSeekSettings>(
    builder.Configuration.GetSection("DeepSeek"));

// 注册授权HttpClient
builder.Services.AddHttpClient("DeepSeek", (sp, client) => {
    var settings = sp.GetRequiredService<IOptions<DeepSeekSettings>>().Value;
    client.BaseAddress = new Uri(settings.ApiUrl);
    client.DefaultRequestHeaders.Authorization = 
        new AuthenticationHeaderValue("Bearer", settings.ApiKey);
});

3. 创建聊天界面(Pages/Index.razor)

代码语言:javascript
代码运行次数:0
运行
复制
@page "/"
@inject HttpClient Http

<h3>DeepSeek Chat</h3>

<div class="chat-container">
    <div class="message-list">
        @foreach (var message in messages)
        {
            <div class="message @message.Class">
                <div class="message-content">@message.Content</div>
            </div>
        }
    </div>
    
    <div class="input-area">
        <textarea @bind="inputText" placeholder="输入消息..." />
        <button @onclick="SendMessage" :disabled="isSending">
            @if (isSending) {
                <span>发送中...</span>
            } else {
                <span>发送</span>
            }
        </button>
    </div>
</div>

<style>
    .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;
    }
</style>

4. 添加代码逻辑(Pages/Index.razor.cs)

代码语言:javascript
代码运行次数:0
运行
复制
 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<ChatMessage> messages = new();
    privatestring inputText = string.Empty;
    privatebool isSending = false;
    private HttpClient _httpClient;
    private IConfiguration _configuration;

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

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

    protected override void OnInitialized()
    {
        _httpClient = HttpClient;
        _configuration = Configuration;

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

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

    private async Task SendMessage()
    {
        if (string.IsNullOrWhiteSpace(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<DeepSeekResponse>();
                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 record ChatMessage(string Role, string Content)
    {
        publicstring Class => Role switch
        {
            "user" => "user",
            "assistant" => "assistant",
            _ => "error"
        };
    }

    privateclassDeepSeekResponse
    {
        public List<Choice> Choices { get; set; } = new();

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

        publicclassMessage
        {
            publicstring Content { get; set; } = string.Empty;
        }
    }
}

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

代码语言:javascript
代码运行次数:0
运行
复制
{
  "DeepSeek": {
    "ApiKey": "api_key",
    "ApiUrl": "https://api.deepseek.com/v1/chat/completions"
  }
}

DeepSeekSettings 实体

代码语言:javascript
代码运行次数:0
运行
复制
public class DeepSeekSettings
{
    /// <summary>
    /// DeepSeek API 的基础地址
    /// </summary>
    public string ApiUrl { get; set; } = string.Empty;

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

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

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

    /// <summary>
    /// API 请求的最大令牌数(控制生成文本的长度)
    /// </summary>
    public int MaxTokens { get; set; } = 1000;
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-03-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 创建项目
  • 2. 添加必要服务(Program.cs)
  • 3. 创建聊天界面(Pages/Index.razor)
  • 4. 添加代码逻辑(Pages/Index.razor.cs)
  • 5. 配置API访问(需在wwwroot/appsettings.json添加)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档