南阳网站建设域名公司网站开发 百度编辑器
2026/1/11 8:57:51 网站建设 项目流程
南阳网站建设域名公司,网站开发 百度编辑器,地方门户网站系统,秋风最新消息基于 Microsoft Agent Framework 实现第三方聊天历史存储 理解 Microsoft Agent Framework Microsoft Agent Framework 是一个用于构建对话式 AI 应用的框架#xff0c;支持自然语言处理和上下文管理。其核心组件包括 Bot Framework SDK 和 Azure Bot Service#xff0c;但…基于 Microsoft Agent Framework 实现第三方聊天历史存储理解 Microsoft Agent FrameworkMicrosoft Agent Framework 是一个用于构建对话式 AI 应用的框架支持自然语言处理和上下文管理。其核心组件包括 Bot Framework SDK 和 Azure Bot Service但默认聊天历史通常存储在 Azure 服务中。具体实现可参考NetCoreKevin的kevin.AI.AgentFramework和KevinAIChatMessageStore服务模块基于NET构建的现代化AI智能体Saas企业级架构项目地址githubhttps://github.com/junkai-li/NetCoreKevinGitee: https://gitee.com/netkevin-li/NetCoreKevin配置自定义存储提供程序**实现ChatMessageStore**创建自定义存储类继承Microsoft.Bot.Builder.IStorage需实现以下方法publicsealedclassKevinChatMessageStore:ChatMessageStore{privateIKevinAIChatMessageStore_chatMessageStore;publicstringThreadDbKey{get;privateset;}publicKevinChatMessageStore(IKevinAIChatMessageStorevectorStore,JsonElementserializedStoreState,stringAIChatsId,JsonSerializerOptions?jsonSerializerOptionsnull){this._chatMessageStorevectorStore??thrownewArgumentNullException(nameof(vectorStore));this.ThreadDbKeyAIChatsId;}publicoverrideasyncTaskAddMessagesAsync(IEnumerableChatMessagemessages,CancellationTokencancellationToken){await_chatMessageStore.AddMessagesAsync(messages.Select(xnewChatHistoryItemDto(){Keythis.ThreadDbKeyx.MessageId,TimestampDateTimeOffset.UtcNow,ThreadIdthis.ThreadDbKey,MessageIdx.MessageId,Rolex.Role.Value,SerializedMessageJsonSerializer.Serialize(x),MessageTextx.Text}).ToList(),cancellationToken);// 设置前景色为红色// 保存原始颜色以便之后恢复ConsoleColororiginalColorConsole.ForegroundColor;Console.ForegroundColorConsoleColor.Red;Console.WriteLine(聊天消息记录:,Color.Red);messages.Select(xx.Text).ToList().ForEach(tConsole.WriteLine(t));// 设置前景色为红色Console.ForegroundColorConsoleColor.Red;Console.WriteLine(聊天消息记录添加完成,Color.Red);// 恢复原始颜色Console.ForegroundColororiginalColor;}publicoverrideasyncTaskIEnumerableChatMessageGetMessagesAsync(CancellationTokencancellationToken){vardataawait_chatMessageStore.GetMessagesAsync(this.ThreadDbKey,cancellationToken);varmessagesdata.ConvertAll(xJsonSerializer.DeserializeChatMessage(x.SerializedMessage!)!);messages.Reverse();ConsoleColororiginalColorConsole.ForegroundColor;Console.ForegroundColorConsoleColor.Red;Console.WriteLine(所有聊天消息记录开始:,Color.Red);messages.Select(xx.Text).ToList().ForEach(tConsole.WriteLine(t));Console.WriteLine(所有聊天消息记录结束:,Color.Red);// 恢复原始颜色Console.ForegroundColororiginalColor;returnmessages;}publicoverrideJsonElementSerialize(JsonSerializerOptions?jsonSerializerOptionsnull)// We have to serialize the thread id, so that on deserialization you can retrieve the messages using the same thread id.JsonSerializer.SerializeToElement(this.ThreadDbKey);}实现IKevinAIChatMessageStoreTaskAddMessagesAsync(ListChatHistoryItemDtochatHistoryItems,CancellationTokencancellationToken);TaskListChatHistoryItemDtoGetMessagesAsync(stringthreadId,CancellationTokencancellationToken);实现注入到AI中间件中1.定义AI服务/// summary/// AI服务/// /summarypublicclassAIAgentService:IAIAgentService{publicAIAgentService(){}publicasyncTaskAIAgentCreateOpenAIAgent(stringname,stringprompt,stringdescription,stringurl,stringmodel,stringkeySecret,IListAITool?toolsnull,ChatResponseFormat?chatResponseFormatnull,FuncIChatClient,IChatClient?clientFactorynull,ILoggerFactory?loggerFactorynull,IServiceProvider?servicesnull){OpenAIClientOptionsopenAIClientOptionsnewOpenAIClientOptions();openAIClientOptions.EndpointnewUri(url);varainewOpenAIClient(newApiKeyCredential(keySecret),openAIClientOptions);if(chatResponseFormat!default){ChatOptionschatOptionsnew(){ResponseFormatchatResponseFormat};returnai.GetChatClient(model).CreateAIAgent(newChatClientAgentOptions(){Namename,Instructionsprompt,ChatOptionschatOptions,Descriptiondescription});}returnai.GetChatClient(model).CreateAIAgent(instructions:prompt,name:name,prompt,tools,clientFactory,loggerFactory,services);}publicasyncTaskAIAgentCreateOpenAIAgent(stringmsg,stringurl,stringmodel,stringkeySecret,ChatClientAgentOptionschatClientAgentOptions){OpenAIClientOptionsopenAIClientOptionsnewOpenAIClientOptions();openAIClientOptions.EndpointnewUri(url);varainewOpenAIClient(newApiKeyCredential(keySecret),openAIClientOptions);returnai.GetChatClient(model).CreateAIAgent(chatClientAgentOptions);}/// summary/// 智能体转换为McpServerTool/// /summary/// param nameaIAgent智能体/param/// returns/returns/// exception crefNotImplementedException/exceptionpublicMcpServerToolAIAgentAsMcpServerTool(AIAgentaIAgent){returnMcpServerTool.Create(aIAgent.AsAIFunction());}/// summary/// 获取代理/// /summary/// returns/returnspublicIChatClientGetChatClient(stringurl,stringmodel,stringkeySecret){OpenAIClientOptionsopenAIClientOptionsnewOpenAIClientOptions();openAIClientOptions.EndpointnewUri(url);varainewOpenAIClient(newApiKeyCredential(model),openAIClientOptions);returnai.GetChatClient(keySecret).AsIChatClient();}publicasyncTask(AIAgent,AgentRunResponse)CreateOpenAIAgentAndSendMSG(stringmsg,stringname,stringprompt,stringdescription,stringurl,stringmodel,stringkeySecret,IListAITool?toolsnull,ChatResponseFormat?chatResponseFormatnull,FuncIChatClient,IChatClient?clientFactorynull,ILoggerFactory?loggerFactorynull,IServiceProvider?servicesnull){OpenAIClientOptionsopenAIClientOptionsnewOpenAIClientOptions();openAIClientOptions.EndpointnewUri(url);varainewOpenAIClient(newApiKeyCredential(keySecret),openAIClientOptions);varaiAgentai.GetChatClient(model).CreateAIAgent(instructions:prompt,name:name,prompt,tools,clientFactory,loggerFactory,services);if(chatResponseFormat!default){ChatOptionschatOptionsnew(){ResponseFormatchatResponseFormat};aiAgentai.GetChatClient(model).CreateAIAgent(newChatClientAgentOptions(){Namename,Instructionsprompt,ChatOptionschatOptions,Descriptiondescription});}varreslutawaitaiAgent.RunAsync(msg);return(aiAgent,reslut);}publicasyncTask(AIAgent,AgentRunResponse)CreateOpenAIAgentAndSendMSG(stringmsg,stringurl,stringmodel,stringkeySecret,ChatClientAgentOptionschatClientAgentOptions){OpenAIClientOptionsopenAIClientOptionsnewOpenAIClientOptions();openAIClientOptions.EndpointnewUri(url);varainewOpenAIClient(newApiKeyCredential(keySecret),openAIClientOptions);varaiAgentai.GetChatClient(model).CreateAIAgent(chatClientAgentOptions);varreslutawaitaiAgent.RunAsync(msg);return(aiAgent,reslut);}}2.使用AI服务addAi.Content(awaitaIAgentService.CreateOpenAIAgentAndSendMSG(add.Content,aIModels.EndPoint,aIModels.ModelName,aIModels.ModelKey,newChatClientAgentOptions{Nameaiapp.Name,InstructionsaIPrompts.Prompt,DescriptionaIPrompts.Description??你是一个智能体,请根据你的提示词进行相关回答,ChatMessageStoreFactoryctx{// Create a new chat message store for this agent that stores the messages in a vector store.returnnewKevinChatMessageStore(kevinAIChatMessageStore,ctx.SerializedState,par.AIChatsId.ToString(),ctx.JsonSerializerOptions);}})).Item2.Text;数据库设计建议对于关系型数据库如 SQL Server建议的表结构/// summary/// 专门用于存储AI聊天记录的表/// /summary[Table(TAIChatMessageStore)][Description(专门用于存储AI聊天记录的表)][Index(nameof(Key))][Index(nameof(ThreadId))][Index(nameof(Role))][Index(nameof(MessageId))]publicclass TAIChatMessageStore : CUD_User {[MaxLength(200)]publicstringKey{ get;set;}[MaxLength(100)]publicstring ThreadId { get;set;}[Description(消息时间stamp)]publicDateTimeOffset?Timestamp{ get;set;}/// summary/// 角色标识/// /summary[MaxLength(50)]publicstring Role { get;set;}publicstring SerializedMessage { get;set;}/// summary/// 消息内容/// /summarypublicstring? MessageText { get;set;}/// summary/// 消息id/// /summary[Description(消息id)][MaxLength(100)]publicstring? MessageId { get;set;} }实现数据持久化写入示例使用 Entity Framework Core 保存数据publicasyncTaskAddMessagesAsync(ListChatHistoryItemDtochatHistoryItems,CancellationTokencancellationToken){varadddatachatHistoryItems.Select(tnewTAIChatMessageStore{IdSnowflakeIdService.GetNextId(),CreateTimeDateTime.Now,CreateUserIdCurrentUser.UserId,IsDeletefalse,TenantIdCurrentUser.TenantId,ThreadIdt.ThreadId,Timestampt.Timestamp,Rolet.Role,Keyt.Key,SerializedMessaget.SerializedMessage,MessageTextt.MessageText,MessageIdt.MessageId}).ToList();aIChatMessageStoreRp.AddRange(adddata);awaitaIChatMessageStoreRp.SaveChangesAsync();}读取示例publicTaskListChatHistoryItemDtoGetMessagesAsync(stringthreadId,CancellationTokencancellationToken){returnaIChatMessageStoreRp.Query().Where(tt.ThreadIdthreadIdt.IsDeletefalse).Select(tnewChatHistoryItemDto{Keyt.Key,ThreadIdt.ThreadId,Timestampt.Timestamp,SerializedMessaget.SerializedMessage,MessageTextt.MessageText,Rolet.Role,MessageIdt.MessageId}).ToListAsync();}性能优化建议为高频查询字段如UserId和ChannelId添加索引实现数据分片策略应对大规模历史记录考虑使用 Redis 缓存热点对话数据安全注意事项加密存储敏感对话内容实现数据保留策略定期清理旧记录遵守 GDPR 等数据隐私法规测试验证方法编写单元测试验证存储接口实现使用 Bot Framework Emulator 进行端到端测试进行负载测试验证性能表现扩展可能性添加全文检索支持如 Azure Cognitive Search实现跨渠道对话历史同步开发分析模块生成对话洞察报告这种实现方式允许完全控制数据存储位置和格式同时保持与 Bot Framework 的兼容性。根据具体需求可选择 SQL Server、Cosmos DB 或其他数据库解决方案。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询