欢迎光临
我们一直在努力

C#接入AI操作步骤详解(deepseek接入)

在C#中接入AI有多种方式,下面我将为你详细介绍几种主流的方法和操作步骤:

1. 使用Azure AI服务(推荐新手)

准备工作

csharp

// 安装NuGet包
Install-Package Azure.AI.TextAnalytics
Install-Package Azure.AI.OpenAI

文本分析示例

csharp

using Azure;
using Azure.AI.TextAnalytics;

class Program
{
static async Task Main(string[] args)
{
// Azure认知服务配置
string endpoint = "你的终结点";
string apiKey = "你的API密钥";

var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

// 情感分析
string document = "这个产品非常好用,我非常喜欢!";
DocumentSentiment documentSentiment = client.AnalyzeSentiment(document);

Console.WriteLine($"情感: {documentSentiment.Sentiment}");
Console.WriteLine($"正面评分: {documentSentiment.ConfidenceScores.Positive:P2}");
}
}

2. 使用OpenAI API

安装OpenAI包

csharp

Install-Package OpenAI

调用GPT模型示例

csharp

using OpenAI_API;
using OpenAI_API.Chat;

class OpenAIService
{
private readonly OpenAIAPI _api;

public OpenAIService(string apiKey)
{
_api = new OpenAIAPI(apiKey);
}

public async Task<string> GetChatResponse(string prompt)
{
var chat = _api.Chat.CreateConversation();
chat.AppendUserInput(prompt);

string response = await chat.GetResponseFromChatbotAsync();
return response;
}
}

// 使用示例
class Program
{
static async Task Main(string[] args)
{
var openAIService = new OpenAIService("你的OpenAI-API密钥");
string response = await openAIService.GetChatResponse("请解释一下人工智能");
Console.WriteLine(response);
}
}

3. 使用ML.NET进行本地AI开发

安装ML.NET

csharp

Install-Package Microsoft.ML

情感分析模型示例

csharp

using Microsoft.ML;
using Microsoft.ML.Data;

// 定义数据模型
public class SentimentData
{
[LoadColumn(0)] public string SentimentText;
[LoadColumn(1), ColumnName("Label")] public bool Sentiment;
}

public class SentimentPrediction
{
[ColumnName("PredictedLabel")] public bool Prediction { get; set; }
public float Probability { get; set; }
public float Score { get; set; }
}

class MLNetDemo
{
static void Main()
{
var mlContext = new MLContext();

// 加载数据
IDataView dataView = mlContext.Data.LoadFromTextFile<SentimentData>(
"sentiment-data.csv",
hasHeader: true,
separatorChar: ',');

// 数据预处理管道
var dataProcessPipeline = mlContext.Transforms.Text.FeaturizeText(
"Features",
nameof(SentimentData.SentimentText));

// 选择算法
var trainer = mlContext.BinaryClassification.Trainers.SdcaLogisticRegression();
var trainingPipeline = dataProcessPipeline.Append(trainer);

// 训练模型
var model = trainingPipeline.Fit(dataView);

// 预测
var predictionEngine = mlContext.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(model);

var sample = new SentimentData { SentimentText = "这是一个很棒的产品" };
var result = predictionEngine.Predict(sample);

Console.WriteLine($"预测结果: {(result.Prediction ? "正面" : "负面")}");
Console.WriteLine($"置信度: {result.Probability:P2}");
}
}

4. 集成TensorFlow.NET

安装TensorFlow.NET

csharp

Install-Package TensorFlow.NET
Install-Package SciSharp.TensorFlow.Redist

图像分类示例

csharp

using Tensorflow;
using static Tensorflow.Binding;

class TensorFlowDemo
{
public void Run()
{
// 加载预训练模型
var graph = new Graph();
var session = new Session(graph);

// 这里加载你的TensorFlow模型
// var model = graph.Import(); // 导入.pb文件

// 进行预测
// var results = session.Run(…);
}
}

5. 完整的AI服务封装示例

csharp

public interface IAIService
{
Task<string> AnalyzeTextAsync(string text);
Task<string> GenerateImageAsync(string prompt);
Task<object> ClassifyImageAsync(byte[] imageData);
}

public class AzureAIService : IAIService
{
private readonly TextAnalyticsClient _textClient;
private readonly OpenAIService _openAIService;

public AzureAIService(string textEndpoint, string textKey, string openAIKey)
{
_textClient = new TextAnalyticsClient(new Uri(textEndpoint), new AzureKeyCredential(textKey));
_openAIService = new OpenAIService(openAIKey);
}

public async Task<string> AnalyzeTextAsync(string text)
{
try
{
// 情感分析
var sentiment = await _textClient.AnalyzeSentimentAsync(text);

// 关键短语提取
var keyPhrases = await _textClient.ExtractKeyPhrasesAsync(text);

return $"情感: {sentiment.Value.Sentiment}, " +
$"关键短语: {string.Join(", ", keyPhrases.Value)}";
}
catch (Exception ex)
{
return $"分析失败: {ex.Message}";
}
}

public async Task<string> GenerateImageAsync(string prompt)
{
// 使用DALL-E生成图像
return await _openAIService.GenerateImage(prompt);
}

public Task<object> ClassifyImageAsync(byte[] imageData)
{
// 图像分类逻辑
throw new NotImplementedException();
}
}

6. 配置和最佳实践

appsettings.json配置

json

{
"AzureAI": {
"Endpoint": "https://your-resource.cognitiveservices.azure.com/",
"Key": "your-key"
},
"OpenAI": {
"ApiKey": "your-openai-key"
}
}

依赖注入配置

csharp

// Startup.cs或Program.cs
services.AddSingleton<IAIService>(provider =>
{
var config = provider.GetRequiredService<IConfiguration>();
return new AzureAIService(
config["AzureAI:Endpoint"],
config["AzureAI:Key"],
config["OpenAI:ApiKey"]
);
});

操作步骤总结

  • 选择AI服务提供商

    • Azure Cognitive Services

    • OpenAI API

    • Google Cloud AI

    • 本地ML.NET

  • 获取API密钥和终结点

    • 注册相应平台账号

    • 创建资源获取密钥

  • 安装对应NuGet包

  • 实现服务封装

    • 创建服务类

    • 处理异常

    • 添加日志记录

  • 测试和优化

    • 编写单元测试

    • 性能优化

    • 错误处理

  • 注意事项

    • 妥善保管API密钥,不要硬编码在代码中

    • 添加适当的错误处理和重试机制

    • 考虑API调用频率限制

    • 对于生产环境,使用配置管理工具管理密钥

    • 监控API使用情况和成本

    选择哪种方式取决于你的具体需求:云服务适合快速集成,本地ML.NET适合数据隐私要求高的场景,TensorFlow.NET适合已有TensorFlow模型的场景。

    ML.NET 是完全免费和开源的。

    下面为您详细解释一下它的免费模式以及可能涉及的潜在成本:

    1. ML.NET 框架本身

    • 许可证:它使用非常宽松的 MIT 许可证。这意味着您可以在个人项目、商业项目、开源或闭源项目中自由使用、修改和分发它,而无需支付任何授权费用。

    • 开源:代码完全公开在 GitHub 上,由微软官方维护。

    • 无运行时费用:一旦您的模型训练完成并集成到应用程序中,使用模型进行预测(推理)不会产生任何按调用次数计费的费用。这与调用云AI API(如OpenAI或Azure Cognitive Services)按调用量付费的模式有本质区别。

    2. 潜在的间接成本

    虽然框架免费,但在开发和使用过程中,可能会产生一些间接成本:

    • 开发工具:

      • 免费:您可以使用完全免费的 Visual Studio Code 或 Visual Studio Community Edition 进行开发。

      • 付费:如果您选择使用付费版的 Visual Studio Professional 或 Enterprise,这会产生费用,但这与ML.NET本身无关,是开发工具的成本。

    • 计算资源:

      • 训练模型:如果您的数据集非常庞大,训练一个复杂的模型(如图像分类、推荐系统)可能会消耗大量的CPU/GPU资源和时间。如果您在本地进行训练,成本就是电费和硬件折旧。如果您在云服务器(如Azure VM)上进行训练,则需要支付云服务器的费用。

      • 部署和运行:您的应用程序需要运行在某个服务器或计算机上。无论是本地服务器、Azure App Service、AWS EC2还是您用户的桌面电脑,这些环境都有其固有的硬件或托管成本。但模型的推理过程本身不产生额外许可费。

    • 数据存储与准备:如果您的训练数据存储在云数据库或数据湖中,这些存储服务会产生费用。

    ML.NET vs. 云AI服务的成本对比

    为了更清晰,我们可以做一个对比:

    特性ML.NET云AI服务 (如 Azure OpenAI)
    许可/使用费 完全免费 (MIT License) 按使用量付费 (每千次调用/每token收费)
    开发成本 较高,需要数据科学和工程技能 较低,主要通过API调用,集成简单
    数据隐私 极高,数据和模型完全在您掌控的环境中 数据需要发送到云端,可能存在隐私顾虑
    自定义性 极强,可以用自己的数据训练完全定制化的模型 有限,通常基于通用大模型,定制有门槛和成本
    基础设施成本 需要自行提供训练和部署的计算资源 由云服务商管理,包含在调用费中
    适用场景 对数据隐私要求高、需要高度定制、长期使用量大 快速原型开发、不需要定制、使用量不大或不想管理基础设施

    ML.NET 是一个真正免费的框架,非常适合以下情况:

  • 对数据隐私和安全性要求极高,不希望将数据送出公司网络。

  • 需要构建高度定制化的AI模型,而通用云服务无法满足需求。

  • 应用规模很大,长期来看,自己训练和部署模型比按调用付费更经济。

  • 希望将AI功能与您的.NET应用程序无缝集成,并作为一个独立的离线应用程序分发。

  • 简单来说,ML.NET 让您用 前期开发成本和基础设施成本 换取了 零运行时许可费和绝对的数据控制权。对于预算有限、注重数据隐私的.NET开发者来说,它是一个极其强大的免费武器。

    C# 接入 DeepSeek API 完整指南

    下面详细介绍如何在 C# 中接入 DeepSeek API,包括控制台应用、Web API 和桌面应用的实现。

    1. 准备工作

    获取 API 密钥

  • 访问 DeepSeek 开放平台

  • 注册账号并登录

  • 在控制台中创建 API 密钥

  • 安装必要的 NuGet 包

    bash

    Install-Package Newtonsoft.Json
    Install-Package System.Net.Http

    2. 基础实现 – 控制台应用

    创建 API 请求模型

    csharp

    using Newtonsoft.Json;

    public class DeepSeekRequest
    {
    [JsonProperty("model")]
    public string Model { get; set; } = "deepseek-chat";

    [JsonProperty("messages")]
    public List<ChatMessage> Messages { get; set; } = new List<ChatMessage>();

    [JsonProperty("max_tokens")]
    public int MaxTokens { get; set; } = 2048;

    [JsonProperty("temperature")]
    public double Temperature { get; set; } = 0.7;

    [JsonProperty("stream")]
    public bool Stream { get; set; } = false;
    }

    public class ChatMessage
    {
    [JsonProperty("role")]
    public string Role { get; set; } // "system", "user", "assistant"

    [JsonProperty("content")]
    public string Content { get; set; }
    }

    创建 API 响应模型

    csharp

    public class DeepSeekResponse
    {
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("object")]
    public string Object { get; set; }

    [JsonProperty("created")]
    public long Created { get; set; }

    [JsonProperty("model")]
    public string Model { get; set; }

    [JsonProperty("choices")]
    public List<Choice> Choices { get; set; }

    [JsonProperty("usage")]
    public UsageInfo Usage { get; set; }
    }

    public class Choice
    {
    [JsonProperty("index")]
    public int Index { get; set; }

    [JsonProperty("message")]
    public ChatMessage Message { get; set; }

    [JsonProperty("finish_reason")]
    public string FinishReason { get; set; }
    }

    public class UsageInfo
    {
    [JsonProperty("prompt_tokens")]
    public int PromptTokens { get; set; }

    [JsonProperty("completion_tokens")]
    public int CompletionTokens { get; set; }

    [JsonProperty("total_tokens")]
    public int TotalTokens { get; set; }
    }

    实现 DeepSeek 服务类

    csharp

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using Newtonsoft.Json;

    public class DeepSeekService
    {
    private readonly string _apiKey;
    private readonly string _apiUrl = "https://api.deepseek.com/v1/chat/completions";
    private readonly HttpClient _httpClient;

    public DeepSeekService(string apiKey)
    {
    _apiKey = apiKey;
    _httpClient = new HttpClient();
    _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
    }

    public async Task<string> SendMessageAsync(string userMessage, string systemMessage = null)
    {
    var request = new DeepSeekRequest
    {
    Messages = new List<ChatMessage>()
    };

    // 添加系统消息(如果有)
    if (!string.IsNullOrEmpty(systemMessage))
    {
    request.Messages.Add(new ChatMessage
    {
    Role = "system",
    Content = systemMessage
    });
    }

    // 添加用户消息
    request.Messages.Add(new ChatMessage
    {
    Role = "user",
    Content = userMessage
    });

    try
    {
    var jsonContent = JsonConvert.SerializeObject(request);
    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

    var response = await _httpClient.PostAsync(_apiUrl, content);
    response.EnsureSuccessStatusCode();

    var responseContent = await response.Content.ReadAsStringAsync();
    var deepSeekResponse = JsonConvert.DeserializeObject<DeepSeekResponse>(responseContent);

    return deepSeekResponse.Choices[0].Message.Content;
    }
    catch (Exception ex)
    {
    return $"错误: {ex.Message}";
    }
    }

    public async Task<string> SendMessageWithHistoryAsync(List<ChatMessage> messageHistory)
    {
    var request = new DeepSeekRequest
    {
    Messages = messageHistory
    };

    try
    {
    var jsonContent = JsonConvert.SerializeObject(request);
    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

    var response = await _httpClient.PostAsync(_apiUrl, content);
    response.EnsureSuccessStatusCode();

    var responseContent = await response.Content.ReadAsStringAsync();
    var deepSeekResponse = JsonConvert.DeserializeObject<DeepSeekResponse>(responseContent);

    return deepSeekResponse.Choices[0].Message.Content;
    }
    catch (Exception ex)
    {
    return $"错误: {ex.Message}";
    }
    }

    public void Dispose()
    {
    _httpClient?.Dispose();
    }
    }

    控制台应用示例

    csharp

    class Program
    {
    static async Task Main(string[] args)
    {
    // 替换为你的实际 API 密钥
    string apiKey = "你的DeepSeek-API密钥";

    using var deepSeekService = new DeepSeekService(apiKey);

    Console.WriteLine("DeepSeek AI 聊天助手 (输入 '退出' 结束对话)");
    Console.WriteLine("===========================================");

    var conversationHistory = new List<ChatMessage>();

    while (true)
    {
    Console.Write("你: ");
    var userInput = Console.ReadLine();

    if (userInput?.ToLower() == "退出" || userInput?.ToLower() == "exit")
    break;

    if (string.IsNullOrWhiteSpace(userInput))
    continue;

    // 添加用户消息到历史
    conversationHistory.Add(new ChatMessage
    {
    Role = "user",
    Content = userInput
    });

    Console.Write("AI: ");
    var response = await deepSeekService.SendMessageWithHistoryAsync(conversationHistory);
    Console.WriteLine(response);

    // 添加AI回复到历史
    conversationHistory.Add(new ChatMessage
    {
    Role = "assistant",
    Content = response
    });

    Console.WriteLine();
    }
    }
    }

    3. Web API 集成

    创建 ASP.NET Core Web API 控制器

    csharp

    [ApiController]
    [Route("api/[controller]")]
    public class AIController : ControllerBase
    {
    private readonly DeepSeekService _deepSeekService;

    public AIController(IConfiguration configuration)
    {
    var apiKey = configuration["DeepSeek:ApiKey"];
    _deepSeekService = new DeepSeekService(apiKey);
    }

    [HttpPost("chat")]
    public async Task<ActionResult<ChatResponse>> Chat([FromBody] ChatRequest request)
    {
    try
    {
    var response = await _deepSeekService.SendMessageAsync(request.Message, request.SystemMessage);

    return Ok(new ChatResponse
    {
    Success = true,
    Message = response,
    Timestamp = DateTime.UtcNow
    });
    }
    catch (Exception ex)
    {
    return BadRequest(new ChatResponse
    {
    Success = false,
    Message = $"请求失败: {ex.Message}",
    Timestamp = DateTime.UtcNow
    });
    }
    }

    [HttpPost("chat-with-history")]
    public async Task<ActionResult<ChatResponse>> ChatWithHistory([FromBody] ChatHistoryRequest request)
    {
    try
    {
    var messages = request.Messages.Select(m => new ChatMessage
    {
    Role = m.Role,
    Content = m.Content
    }).ToList();

    var response = await _deepSeekService.SendMessageWithHistoryAsync(messages);

    return Ok(new ChatResponse
    {
    Success = true,
    Message = response,
    Timestamp = DateTime.UtcNow
    });
    }
    catch (Exception ex)
    {
    return BadRequest(new ChatResponse
    {
    Success = false,
    Message = $"请求失败: {ex.Message}",
    Timestamp = DateTime.UtcNow
    });
    }
    }
    }

    // DTO 类
    public class ChatRequest
    {
    public string Message { get; set; }
    public string SystemMessage { get; set; }
    }

    public class ChatHistoryRequest
    {
    public List<MessageDto> Messages { get; set; }
    }

    public class MessageDto
    {
    public string Role { get; set; }
    public string Content { get; set; }
    }

    public class ChatResponse
    {
    public bool Success { get; set; }
    public string Message { get; set; }
    public DateTime Timestamp { get; set; }
    }

    appsettings.json 配置

    json

    {
    "DeepSeek": {
    "ApiKey": "你的DeepSeek-API密钥",
    "ApiUrl": "https://api.deepseek.com/v1/chat/completions"
    },
    "Logging": {
    "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore": "Warning"
    }
    },
    "AllowedHosts": "*"
    }

    4. WPF 桌面应用集成

    MainWindow.xaml

    xml

    <Window x:Class="DeepSeekChat.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DeepSeek AI 聊天助手" Height="600" Width="800">
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto">
    <ItemsControl x:Name="MessagesItemsControl">
    <ItemsControl.ItemTemplate>
    <DataTemplate>
    <Border Margin="5" Padding="10"
    Background="{Binding BackgroundColor}"
    CornerRadius="10">
    <TextBlock Text="{Binding Content}"
    TextWrapping="Wrap"
    Foreground="{Binding TextColor}"/>
    </Border>
    </DataTemplate>
    </ItemsControl.ItemTemplate>
    </ItemsControl>
    </ScrollViewer>

    <Grid Grid.Row="1" Margin="10">
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <TextBox x:Name="MessageTextBox"
    Grid.Column="0"
    Height="60"
    TextWrapping="Wrap"
    VerticalScrollBarVisibility="Auto"
    KeyDown="MessageTextBox_KeyDown"/>

    <Button x:Name="SendButton"
    Grid.Column="1"
    Content="发送"
    Width="60"
    Height="60"
    Margin="10,0,0,0"
    Click="SendButton_Click"/>
    </Grid>
    </Grid>
    </Window>

    MainWindow.xaml.cs

    csharp

    using System;
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;

    namespace DeepSeekChat
    {
    public partial class MainWindow : Window
    {
    private readonly DeepSeekService _deepSeekService;
    private readonly ObservableCollection<MessageDisplay> _messages;

    public MainWindow()
    {
    InitializeComponent();

    string apiKey = "你的DeepSeek-API密钥"; // 应该从配置文件中读取
    _deepSeekService = new DeepSeekService(apiKey);
    _messages = new ObservableCollection<MessageDisplay>();
    MessagesItemsControl.ItemsSource = _messages;
    }

    private async void SendButton_Click(object sender, RoutedEventArgs e)
    {
    await SendMessage();
    }

    private async void MessageTextBox_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.Key == Key.Enter && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
    {
    await SendMessage();
    }
    }

    private async Task SendMessage()
    {
    var userMessage = MessageTextBox.Text.Trim();
    if (string.IsNullOrEmpty(userMessage))
    return;

    // 添加用户消息到界面
    _messages.Add(new MessageDisplay
    {
    Content = $"你: {userMessage}",
    BackgroundColor = Brushes.LightBlue,
    TextColor = Brushes.Black
    });

    MessageTextBox.Clear();

    try
    {
    // 显示加载状态
    var loadingMessage = new MessageDisplay
    {
    Content = "AI: 思考中…",
    BackgroundColor = Brushes.LightGray,
    TextColor = Brushes.Black
    };
    _messages.Add(loadingMessage);

    // 发送请求到 DeepSeek
    var response = await _deepSeekService.SendMessageAsync(userMessage);

    // 移除加载消息,添加实际回复
    _messages.Remove(loadingMessage);
    _messages.Add(new MessageDisplay
    {
    Content = $"AI: {response}",
    BackgroundColor = Brushes.LightGreen,
    TextColor = Brushes.Black
    });

    // 滚动到底部
    ScrollToBottom();
    }
    catch (Exception ex)
    {
    _messages.Add(new MessageDisplay
    {
    Content = $"错误: {ex.Message}",
    BackgroundColor = Brushes.LightCoral,
    TextColor = Brushes.DarkRed
    });
    }
    }

    private void ScrollToBottom()
    {
    if (MessagesItemsControl.Items.Count > 0)
    {
    var border = (Border)VisualTreeHelper.GetChild(MessagesItemsControl, 0);
    var scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
    scrollViewer.ScrollToBottom();
    }
    }
    }

    public class MessageDisplay
    {
    public string Content { get; set; }
    public Brush BackgroundColor { get; set; }
    public Brush TextColor { get; set; }
    }
    }

    5. 高级功能 – 流式响应

    流式响应实现

    csharp

    public class DeepSeekStreamService
    {
    private readonly string _apiKey;
    private readonly string _apiUrl = "https://api.deepseek.com/v1/chat/completions";
    private readonly HttpClient _httpClient;

    public DeepSeekStreamService(string apiKey)
    {
    _apiKey = apiKey;
    _httpClient = new HttpClient();
    _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
    _httpClient.Timeout = TimeSpan.FromMinutes(5); // 设置较长的超时时间
    }

    public async IAsyncEnumerable<string> SendMessageStreamAsync(string userMessage, string systemMessage = null)
    {
    var request = new DeepSeekRequest
    {
    Messages = new List<ChatMessage>(),
    Stream = true // 启用流式响应
    };

    if (!string.IsNullOrEmpty(systemMessage))
    {
    request.Messages.Add(new ChatMessage
    {
    Role = "system",
    Content = systemMessage
    });
    }

    request.Messages.Add(new ChatMessage
    {
    Role = "user",
    Content = userMessage
    });

    var jsonContent = JsonConvert.SerializeObject(request);
    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

    using var response = await _httpClient.PostAsync(_apiUrl, content, HttpCompletionOption.ResponseHeadersRead);
    response.EnsureSuccessStatusCode();

    using var stream = await response.Content.ReadAsStreamAsync();
    using var reader = new StreamReader(stream);

    while (!reader.EndOfStream)
    {
    var line = await reader.ReadLineAsync();
    if (string.IsNullOrEmpty(line) || !line.StartsWith("data: "))
    continue;

    var data = line.Substring(6); // 移除 "data: " 前缀

    if (data == "[DONE]")
    yield break;

    try
    {
    var streamResponse = JsonConvert.DeserializeObject<DeepSeekStreamResponse>(data);
    var contentPiece = streamResponse?.Choices?[0]?.Delta?.Content;

    if (!string.IsNullOrEmpty(contentPiece))
    yield return contentPiece;
    }
    catch (JsonException)
    {
    // 忽略解析错误,继续处理下一行
    }
    }
    }
    }

    // 流式响应模型
    public class DeepSeekStreamResponse
    {
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("object")]
    public string Object { get; set; }

    [JsonProperty("created")]
    public long Created { get; set; }

    [JsonProperty("model")]
    public string Model { get; set; }

    [JsonProperty("choices")]
    public List<StreamChoice> Choices { get; set; }
    }

    public class StreamChoice
    {
    [JsonProperty("index")]
    public int Index { get; set; }

    [JsonProperty("delta")]
    public Delta Delta { get; set; }

    [JsonProperty("finish_reason")]
    public string FinishReason { get; set; }
    }

    public class Delta
    {
    [JsonProperty("role")]
    public string Role { get; set; }

    [JsonProperty("content")]
    public string Content { get; set; }
    }

    6. 配置和最佳实践

    依赖注入配置 (ASP.NET Core)

    csharp

    // Program.cs
    builder.Services.AddSingleton<DeepSeekService>(provider =>
    {
    var configuration = provider.GetRequiredService<IConfiguration>();
    var apiKey = configuration["DeepSeek:ApiKey"];
    return new DeepSeekService(apiKey);
    });

    builder.Services.AddSingleton<DeepSeekStreamService>(provider =>
    {
    var configuration = provider.GetRequiredService<IConfiguration>();
    var apiKey = configuration["DeepSeek:ApiKey"];
    return new DeepSeekStreamService(apiKey);
    });

    错误处理和重试机制

    csharp

    public class ResilientDeepSeekService
    {
    private readonly DeepSeekService _deepSeekService;
    private readonly int _maxRetries = 3;
    private readonly TimeSpan _delay = TimeSpan.FromSeconds(1);

    public ResilientDeepSeekService(string apiKey)
    {
    _deepSeekService = new DeepSeekService(apiKey);
    }

    public async Task<string> SendMessageWithRetryAsync(string userMessage, string systemMessage = null)
    {
    for (int i = 0; i < _maxRetries; i++)
    {
    try
    {
    return await _deepSeekService.SendMessageAsync(userMessage, systemMessage);
    }
    catch (HttpRequestException ex) when (i < _maxRetries – 1)
    {
    await Task.Delay(_delay * (i + 1));
    }
    }

    throw new Exception("所有重试尝试都失败了");
    }
    }

    使用注意事项

  • API 密钥安全:不要将 API 密钥硬编码在代码中,使用环境变量或配置文件

  • 速率限制:注意 DeepSeek API 的调用频率限制

  • 错误处理:妥善处理网络异常和 API 错误

  • 资源清理:及时释放 HttpClient 和其他资源

  • 用户体验:对于长时间操作,提供加载状态和取消功能

  • 这个完整的指南应该能帮助你在各种 C# 应用中成功集成 DeepSeek API!

    赞(0)
    未经允许不得转载:171主机测评 » C#接入AI操作步骤详解(deepseek接入)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址