惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
A
About on SuperTechFans
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
Recent Announcements
Recent Announcements
D
DataBreaches.Net
B
Blog
博客园 - 【当耐特】
爱范儿
爱范儿
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
WordPress大学
WordPress大学
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
I
InfoQ
Engineering at Meta
Engineering at Meta
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
Microsoft Azure Blog
Microsoft Azure Blog
雷峰网
雷峰网
量子位
G
Google Developers Blog

博客园 - 桂素伟

Semantic Kernel:开启MCP Semantic Kernel:Phi-4 mini的tools .NET10:解决json序列化时引用自己 .NET10:字符数字 Semantic Kernel:接入本地deepseek-r1:1.5b Semantic Kernel:接入azure中的deepseek-r1 C#中的Channel .NET9中基于策略角色验证的包冲突 .NET9中使用Options Semantic Kernel:OpenAPI的Plugin Semantic Kernel:Phi-4试用 AI应用开发的浅见 Semantic Kernel:Process UnitsNet 库简介 .NET9里WinForm更新了什么 SemanticKernel系列,AI系列,SmartFill介绍视频系列 更流畅的asp.net api的错误返回 用.srt字幕文件生成.wav语音 自制实时翻译小工具
Semantic Kernel:新Agent代理
桂素伟 · 2025-03-02 · via 博客园 - 桂素伟

  在之前的SemanticKernel中,有一篇关于Agent的文章,不过现在看来其中使用的包过时,所以这篇来更新一下。原文章如下:

Semantic Kernel:Agent代理

桂素伟,公众号:桂迹Semantic Kernel:Agent代理

  原来项目引有的Nuget包如下,版本停留在了1.18.2,2024年9月4日

   最新的Agent包已更还,如下:

  下面是用最新的包进行的更换,代码注释说明了每个类型和方法的功能,这里就不说了。目前有个问题,就是在创建各个代理的时间,Name不能是中文,否则报http 400的错误,相信之后会有所改善。

using Microsoft.SemanticKernel.Agents.Chat;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel;
using System.ClientModel;
using System.Collections.ObjectModel;
using System.Reflection.Emit;
using System;
#pragma warning disable
var modelID = "gpt-4o";
var openAIKey = File.ReadAllText("c://gpt/key.txt");
var kernel = Kernel.CreateBuilder()
           .AddOpenAIChatCompletion(modelID, openAIKey).Build();
//创建翻译家代理
var agentTranslator = await CreateTranslatorAsync(kernel);
//创建审核员代理
var agentAuditor = await CreateAuditorAsync(kernel);
//创建一个代理聊天组,先让翻译家翻译,然后审核员审核
var chat = new AgentGroupChat(agentTranslator, agentAuditor)
{
    ExecutionSettings = new()
    {
        // 这里使用了一个 TerminationStrategy 子类,当代理消息包含术语 "采用它" 时将终止。
        TerminationStrategy = new AdoptTerminationStrategy("采用它")
        {
            Agents = [agentAuditor],
            MaximumIterations = 6,
        }
    }
};
//添加聊天消息
var chatMessage = new ChatMessageContent(AuthorRole.User, File.ReadAllText("content.txt"));
chat.AddChatMessage(chatMessage);
Console.WriteLine(chatMessage);
var lastAgent = string.Empty;
Console.WriteLine();
// 这里使用了异步流来处理代理的消息。
await foreach (var response in chat.InvokeStreamingAsync())
{
    if (string.IsNullOrEmpty(response.Content))
    {
        continue;
    }
    //输入角色和代理名称
    if (!lastAgent.Equals(response.AuthorName, StringComparison.Ordinal))
    {
        Console.WriteLine($"\n# {response.Role} - {response.AuthorName ?? "*"}:");
        lastAgent = response.AuthorName ?? string.Empty;
    }
    Console.Write(response.Content);
}
//ChatMessageContent[] history = await chat.GetChatMessagesAsync().Reverse().ToArrayAsync();
//全部的内容
//for (int index = 0; index < history.Length; index++)
//{
//    Console.WriteLine(history[index]);
//}
Console.WriteLine($"\n[已完成: {chat.IsComplete}]");
async Task<ChatCompletionAgent> CreateAuditorAsync(Kernel kernel)
{
    var agentTranslator = new ChatCompletionAgent()
    {
        Instructions = """
                你是一位中日文翻译的翻译审核员,你有丰富的翻译和审核经验,对翻译质量有较高的要求,总是严格要求,反复琢磨,以求得到更为准确的翻译。
                目标是确定给定翻译否符合要求,是否采用。
                如果翻译内容可以接受并且符合您的标准,请说:采用它。
                """,
        Name = "Auditor",
        Kernel = kernel,
    };
    return agentTranslator;
}
async Task<OpenAIAssistantAgent> CreateTranslatorAsync(Kernel kernel)
{
    var agentAuditor = await OpenAIAssistantAgent.CreateAsync(
            clientProvider: OpenAIClientProvider.ForOpenAI(new ApiKeyCredential(openAIKey)),
            definition: new OpenAIAssistantDefinition(modelID)
            {
                Instructions = """
                您是一位把中文翻译成日文的翻译家。
                你会把用户的输入,全神贯注于手头的目标,翻译成准确,高质量的译文。
                完善翻译内容时,请考虑翻译 Auditor 的建议。
                """,
                Name = "JapaneseTranslator",
            },
            kernel: kernel);
    return agentAuditor;
}
class AdoptTerminationStrategy(string adoptCommand) : TerminationStrategy
{
    protected override Task<bool> ShouldAgentTerminateAsync(Agent agent, IReadOnlyList<ChatMessageContent> history, CancellationToken cancellationToken)
        => Task.FromResult(history[history.Count - 1].Content?.Contains(adoptCommand, StringComparison.OrdinalIgnoreCase) ?? false);
}

运行结果:

   文章来源微信公众号

  想要更快更方便的了解相关知识,可以关注微信公众号 

****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524