using System.ClientModel; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Reflection; using System.Text.Json; using Dm.util; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ModelContextProtocol.Server; using OpenAI; using OpenAI.Chat; using OpenAI.Responses; using Volo.Abp.Domain.Services; namespace Yi.Framework.AiHub.Domain.Managers; public class ChatManager : DomainService { private readonly AiGateWayManager _aiGateWayManager; private readonly ILoggerFactory _loggerFactory; public ChatManager(AiGateWayManager aiGateWayManager, ILoggerFactory loggerFactory) { _aiGateWayManager = aiGateWayManager; _loggerFactory = loggerFactory; } public async Task CompleteChatStreamAsync() { //token可以用户传进来 // HttpClient.DefaultProxy = new WebProxy("127.0.0.1:8888"); var modelId = "gpt-5.2"; var client = new OpenAIClient(new ApiKeyCredential("xxx"), new OpenAIClientOptions { Endpoint = new Uri("https://yxai.chat/v1"), }); var agent = client.GetChatClient(modelId) .CreateAIAgent("你是一个专业的网页ai助手"); var thread = agent.GetNewThread(); var tools = GetTools(); var chatOptions = new ChatOptions() { Tools = tools.Select(x => (AITool)x).ToList(), ToolMode = ChatToolMode.Auto }; await foreach (var update in agent.RunStreamingAsync("联网搜索一下,奥德赛第一中学学生会会长是谁", thread, new ChatClientAgentRunOptions(chatOptions))) { // 检查每个更新中的内容 foreach (var content in update.Contents) { switch (content) { case FunctionCallContent functionCall: Console.WriteLine(); Console.WriteLine( $"🔧 工具调用开始: {functionCall.CallId},{functionCall.Name},{functionCall.Arguments}"); break; case FunctionResultContent functionResult: Console.WriteLine(); Console.WriteLine($"✅ 工具调用完成: {functionResult.CallId},{functionResult.Result}"); break; case TextContent textContent: Console.Write($"{textContent.Text}"); break; case UsageContent usageContent: Console.WriteLine(); Console.WriteLine($"✅ 用量统计: {usageContent.Details.TotalTokenCount}"); break; } } } string serializedJson = thread.Serialize(JsonSerializerOptions.Web).GetRawText(); JsonElement reloaded = JsonSerializer.Deserialize(serializedJson, JsonSerializerOptions.Web); var newThread = agent.DeserializeThread(reloaded, JsonSerializerOptions.Web); } private List GetTools() { var toolClasses = typeof(YiFrameworkAiHubDomainModule).Assembly.GetTypes() .Where(x => x.GetCustomAttribute() is not null) .ToList(); List mcpTools = new List(); foreach (var toolClass in toolClasses) { var instance = LazyServiceProvider.GetRequiredService(toolClass); var toolMethods = toolClass.GetMethods() .Where(y => y.GetCustomAttribute() is not null).ToList(); foreach (var toolMethod in toolMethods) { mcpTools.add(AIFunctionFactory.Create(toolMethod, instance)); } } return mcpTools; } }