1
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?

AutoGenを使って複数のモデルに同時に話しかけてみた

Last updated at Posted at 2025-02-03

はじめに

最近話題のAutogenを触ってみたく、Azure OpenAIを使って試しにコンソールアプリを作ってみました。
Autogenは複数のAIエージェントに協力させて、複雑な問題解決を可能にするフレームワークです。今回は単純に複数のAI達とグループチャットをするサンプルを作ってみました。

実装のポイント

以下に、主要な実装部分を紹介します。

  1. 必要なパッケージのインポート

    using AutoGen.OpenAI;
    using AutoGen;
    using Azure.AI.OpenAI;
    using AutoGen.OpenAI.Extension;
    using AutoGen.Core;
    using Azure;
    using System;
    using System.Threading.Tasks;
    using System.Text;
    
  2. メインメソッドの設定
    UserProxyがユーザーとの仲介役になってくれます

     static async Task Main(string[] args){
     var azureOpenAIClient = InitializeAzureOpenAIClient();
    
     var userProxyAgent = new UserProxyAgent(
         name: "user",
         humanInputMode: HumanInputMode.ALWAYS)
         .RegisterPrintMessage();
    
     var groupChat = InitializeGroupChat(azureOpenAIClient, userProxyAgent);
    
     // Set console encoding to UTF-8 to prevent garbled characters
     Console.OutputEncoding = Encoding.UTF8;
     Console.WriteLine("Let't talk with GPTs!!");
     var userMessage = Console.ReadLine();
    
     var groupChatManager = new GroupChatManager(groupChat);
    
     bool isContentFiltered = false;
     do
     {
         try
         {
             var history = await userProxyAgent.InitiateChatAsync(
                 receiver: groupChatManager,
                 message: userMessage,
                 maxRound: 10);
             isContentFiltered = false;
         }
         catch (RequestFailedException ex) when (ex.Status == 400 )
         {
             Console.WriteLine("may be content filtered");
             userMessage = Console.ReadLine();
             isContentFiltered = true;
         }
         catch (Exception ex)
         {
             Console.WriteLine($"unexpected error: {ex.Message}");
             Console.WriteLine(ex.StackTrace);
             Console.WriteLine("press any key to exit...");
             Console.ReadLine();
             Environment.Exit(1);
             isContentFiltered = false; // ループを終了するためにfalseに設定
         }
     } while (isContentFiltered); }
    
  3. Azure OpenAIクライアントの初期化

    Azure OpenAIサービスに接続するためのクライアントを作成します。

    static AzureOpenAIClient InitializeAzureOpenAIClient() {
        var azureOpenAIEndpoint = "your endpoint";
        var azureOpenAIKey = "your key";
        return new AzureOpenAIClient(new Uri(azureOpenAIEndpoint), new AzureKeyCredential(azureOpenAIKey));
    }
    
  4. グループチャットの初期化

    複数のエージェントを初期化し、グループチャットに登録します。

    static GroupChat InitializeGroupChat(AzureOpenAIClient azureOpenAIClient, MiddlewareAgent<UserProxyAgent> userAgent)
    {
        var model = "gpt-4o";
        //Autogen 0.4系なら動くかも
        //var model = "o1-mini";
    
    
        var economist = new OpenAIChatAgent(
            name: "Economist",
            systemMessage: "You are a professional economoist.",
            chatClient: azureOpenAIClient.GetChatClient(model))
            .RegisterMessageConnector()
            .RegisterPrintMessage();
    
        var politician = new OpenAIChatAgent(
            name: "Politican",
            systemMessage: "You are a politician.",
            chatClient: azureOpenAIClient.GetChatClient(model))
            .RegisterMessageConnector()
            .RegisterPrintMessage();
    
        var citizen = new OpenAIChatAgent(
            name: "Citizen",
            systemMessage: "You are a citizen",
            chatClient: azureOpenAIClient.GetChatClient(model))
            .RegisterMessageConnector()
            .RegisterPrintMessage();
    
        return new GroupChat(
            members: new List<IAgent> { economist, politician, citizen, userAgent });}
    
            
    

UserProxyAgentについて

UserProxyAgentは、ユーザーの代理として動作するエージェントクラスです。ユーザーからの入力を受け取り、それを他のエージェントやシステムに伝達する役割を持ちます。

• 名前の指定: nameプロパティでエージェント名を設定します(例: "user")。
• 入力モードの設定: HumanInputMode.ALWAYSを指定することで、常にユーザー入力を待機します。
• メッセージの登録: .RegisterPrintMessage()を使用して、受信したメッセージをコンソールなどに表示します。
• チャットの開始: InitiateChatAsyncメソッドでチャットを開始し、他のエージェントとメッセージをやり取りします。
このエージェントを利用することで、ユーザーからの入力を効率的に処理し、他のエージェントとの対話を実現できます

        var userProxyAgent = new UserProxyAgent(
            name: "user",
            humanInputMode: HumanInputMode.ALWAYS)
            .RegisterPrintMessage();

GroupChatManagerについて

GroupChatManagerは、複数のエージェント間のグループチャットを管理するクラスです。GroupChatオブジェクトを受け取り、エージェント間のメッセージ交換を制御します。

• エージェントの管理: GroupChat内のエージェント(例: Economist、Politician、Citizen)を一括管理します。
• メッセージのブロードキャスト: 一つのメッセージを全てのエージェントに配信し、各エージェントからの応答を管理します。
• チャットセッションの制御: チャットのラウンド数やメッセージ履歴を管理します

結果

アプリケーションを実行すると、コンソールに以下のように表示されます。

Let't talk with GPTs!!

日本の未来について会話してみましょう

Let't talk with GPTs!!
Tell me about the future in Japan in one senetence.

結構みんな楽観的ですね。システムプロンプトがテキトーだからだと思います。

Let't talk with GPTs!!
Tell me about the future in Japan in one senetence.
from: Economist
Japan's future is likely to be characterized by technological innovation, adaptations to an aging population, and efforts to maintain economic stability in the face of global challenges.

from: Politican
Japan's future will hinge on leveraging technological advancements, addressing demographic shifts, and enhancing economic resilience to navigate a rapidly evolving global landscape.

from: Citizen
Japan's future will focus on leveraging technology and innovation, addressing its aging population, and strengthening its economic and geopolitical standing amid evolving global dynamics.

まとめ

Autogenを試しに使ってみましたが便利ですね。エージェントから他エージェントへプロンプトを投げて結果を返却、FunctionCallingも可能なようなので気が向いたら試してみたいと思います

1
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
1
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?