0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SemainticKernelの代理Agent

Posted at

LLMにおけるAgentは「エージェント」の役割を表し、幅広い領域の全能者であったり、細分された分野での専門家であったりします。代理人になることで最大の利点は、エージェントが代表として他のエージェントとの交流を行い、望ましい結果を得られるまでそれを続けることができる点です。

高度なプログラマとアーキテクトの2つのケースでの代理の例を以下に示します。高度なプログラマがプログラムを書き終えた後、アーキテクトがレビューを行い、具体的な修正提案をします。結果に満足すれば、そのまま進めます。

nugetパッケージを導入:

<ItemGroup>
    <PackageReference Include="Microsoft.SemanticKernel" Version="1.7.1" />
    <PackageReference Include="Microsoft.SemanticKernel.Experimental.Agents" Version="1.7.1-alpha" />
</ItemGroup>

具体的なコードは以下の通りです:

using Microsoft.SemanticKernel.Experimental.Agents;

#pragma warning disable SKEXP0101
var key = File.ReadAllText(@"C:\GPT\key.txt");
var chatModelId = "gpt-4-0125-preview";
var s_agents = new List<IAgent>();
Console.WriteLine("======== 協力開始 ========");
IAgentThread? thread = null;
try
{
    // 文案代理を作成してアイデアを生み出す
    var copyWriter = await CreateCopyWriterAsync();
    // アートディレクター代理を作成してアイデアをレビューし、フィードバックを提供し、最終的に承認する
    var artDirector = await CreateArtDirectorAsync();
    
    // 協力スレッドを作成し、2つのエージェントがそれにメッセージを追加する。
    thread = await copyWriter.NewThreadAsync();
    
    // ユーザーメッセージを追加
    var messageUser = await thread.AddUserMessageAsync("機能モジュール:MySqlを使用したユーザーログインのC#コードを完成させます。OEMにはDapperを使用します。");
    DisplayMessage(messageUser);
    var times = 1;
    bool isComplete = false;
    do
    {
        times++;
        // 高度な代理作業を開始
        var agentMessages = await thread.InvokeAsync(copyWriter).ToArrayAsync();
        DisplayMessages(agentMessages, copyWriter, ConsoleColor.Green);
        
        // アーキテクト作業を開始
        agentMessages = await thread.InvokeAsync(artDirector).ToArrayAsync();
        DisplayMessages(agentMessages, artDirector, ConsoleColor.Yellow);
        
        // 目標達成を評価。
        if (agentMessages.First().Content.Contains("採用する", StringComparison.OrdinalIgnoreCase))
        {
            isComplete = true;
        }
        if (times > 3)
        {
            isComplete = true;
        }
    }
    while (!isComplete);
}
finally
{
    // クリーンアップ
    await Task.WhenAll(s_agents.Select(a => a.DeleteAsync()));
}

async Task<IAgent> CreateCopyWriterAsync()
{
    return Track(
        await new AgentBuilder()
            .WithOpenAIChatCompletion(chatModelId, key)
            .WithInstructions("あなたはC#の高度なプログラマ(Architect)で、厳密で知られています。手に負えない目標に全力を尽くし、高品質で、完全に栄養のあるコードを生成します。アイデアを洗練させるときは、アーキテクトの助言を考慮してください。")
            .WithName("高度なプログラマ")
            .WithDescription("高度なプログラマ")
            .BuildAsync());
}

async Task<IAgent> CreateArtDirectorAsync()
{
    return Track(
        await new AgentBuilder()
            .WithOpenAIChatCompletion(chatModelId, key)
            .WithInstructions("あなたはC#の経験豊富なアーキテクトで、コードの品質に高い要求を持ち、命名規則に厳格です。与えられたコードが要求を満たしているか、使用するかを決定することが目標です。要求を満たしていない場合は、具体的なコードの実装を相手に伝えず、提案を出してください。常に最初にアドバイスを繰り返してください。コードが受け入れ可能で、あなたの基準を満たしている場合は、「採用する」と言ってください。")
            .WithName("アーキテクト")
            .WithDescription("アーキテクト")
            .BuildAsync());
}

void DisplayMessages(IEnumerable<IChatMessage> messages, IAgent? agent = null, ConsoleColor color = ConsoleColor.White)
{
    foreach (var message in messages)
    {
        DisplayMessage(message, agent, color);
    }
}

void DisplayMessage(IChatMessage message, IAgent? agent = null, ConsoleColor color = ConsoleColor.White)
{
    Console.ResetColor();
    Console.ForegroundColor = color;
    Console.WriteLine($"[{message.Id}]");
    if (agent != null)
    {
        Console.WriteLine($"# {message.Role}: ({agent.Name}) {message.Content}");
    }
    else
    {
        Console.WriteLine($"# {message.Role}: {message.Content}");
    }
    Console.ResetColor();
}

IAgent Track(IAgent agent)
{
    s_agents.Add(agent);
    return agent;
}

エージェント間のいくつかの往復のスケジューリングにより、一般的に少し遅くなります。具体的な結果は以下の通りです:

画像

(Translated by GPT)

元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247488072&idx=1&sn=e3f2d1f3285f5716eaea111f3c6b6336&chksm=9f004d62a877c47423428199a9809475a7ae134091240a8c565811abd43d1f22f2757fc32987&token=1106494811&lang=zh_CN#rd&wt.mc_id=MVP_325642

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?