(三)Net8 使用abp.vnext框架集成 deepseek并实现知识库功能
本代码实现与deepseek进行聊天,下一节将实现在abp.vnext中使用Milvus 和 DeepSeek 构建检索增强生成(RAG)管道,形成自己的知识库。Console.WriteLine($"未知的类型{content.GetType().Name}");contentBuilder.Append("[内容处理错误]");Console.WriteLine($"回复失败,无返回内容");
本代码实现与deepseek进行聊天,下一节将实现在abp.vnext中使用Milvus 和 DeepSeek 构建检索增强生成(RAG)管道,形成自己的知识库
在application层实现与deepseek聊天
public interface IChatService
{
/// <summary>
/// 聊天-回复
/// </summary>
/// <param name="userQuestion"></param>
/// <returns></returns>
Task<string> ProcessChatAsync(string userQuestion);
}
/// <summary>
/// 调用deepseek进行回复
/// </summary>
public class ChatService : IChatService, ITransientDependency
{
private readonly IChatClient _chatClient;
public ChatService(
IChatClient chatClient)
{
_chatClient = chatClient;
}
/// <summary>
/// 聊天-回复
/// </summary>
/// <param name="userQuestion"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<string> ProcessChatAsync(string userQuestion)
{
var messages = new List<ChatMessage>
{
new ChatMessage(ChatRole.System, "你是一个专业的AI助手,请保持回答准确、简洁和相关。"),
new ChatMessage(ChatRole.User, userQuestion)
};
var chatOptions = new ChatOptions
{
ModelId = "deepseek-r1:14b",
Temperature = 0.7f,
MaxOutputTokens = 2000,
TopP = 0.9f,
FrequencyPenalty = 0.1f,
PresencePenalty = 0.1f,
ResponseFormat = ChatResponseFormat.Text
};
var response = await _chatClient.GetResponseAsync(messages, chatOptions);
if (response.Choices.Count == 0)
{
Console.WriteLine($"回复失败,无返回内容");
}
// 处理所有内容类型
var contentBuilder = new StringBuilder();
foreach (var content in response.Choices[0].Contents)
{
try
{
switch (content)
{
case TextContent textContent:
contentBuilder.Append(textContent.Text);
break;
default:
Console.WriteLine($"未知的类型{content.GetType().Name}");
break;
}
}
catch (Exception ex)
{
contentBuilder.Append("[内容处理错误]");
}
}
return contentBuilder.ToString();
}
}
public interface IChatAppService
{
/// <summary>
/// 聊天
/// </summary>
/// <param name="question"></param>
/// <returns></returns>
Task<string> ChatQuestion(string question);
}
/// <summary>
/// deepseek聊天
/// </summary>
public class ChatAppService : ApplicationService, IChatAppService
{
private readonly IChatService _chatService;
/// <summary>
///
/// </summary>
public ChatAppService(IChatService chatService)
{
_chatService = chatService;
}
/// <summary>
/// 聊天
/// </summary>
/// <param name="question"></param>
/// <returns></returns>
public async Task<string> ChatQuestion(string question)
{
return await _chatService.ProcessChatAsync(question);
}
}
更多推荐
所有评论(0)