AG2 は様々なオーケストレーション・パターンを提供し、進化する財務コンプライアンスシステムに対して、グループチャット・パターンは特に強力です。それは専門エージェントが、動的ハンドオフを使用して連携し、複雑なワークフローを実現することを可能にします。
AG2 : ユーザガイド – 基本概念 : エージェント・オーケストレーション
作成 : クラスキャット・セールスインフォメーション
作成日時 : 09/03/2025
バージョン : v0.9.9
* 本記事は docs.ag2.ai の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
AG2 : ユーザガイド – 基本概念 : エージェント・オーケストレーション
財務コンプライアンスの例では、取引きを処理して、疑わしいものには人間の承認を得るためにフラグを立てる human-in-the-loop エージェントをうまく実装しました。これは基本的なコンプライアンス確認についてはうまく動作しますが、すべての取引が処理されたあとで詳細な概要レポートを提出する必要があるならどうでしょう?
この機能を含めるために、finance_bot のシステムメッセージを拡張できるでしょうが、このアプローチは要件がより複雑になる際にスケーラブルではありません。finance_bot は複数の役割を持つことになり、保守と拡張が困難になります。
専門エージェントの必要性
財務コンプライアンス・システムが進化するにつれ、以下が必要となる可能性があります :
- すべての取引きのフォーマットされた概要レポートを生成する
- 取引きパターンのリスク分析を実行する
- 財務データの視覚化を作成する
- 関連する利害関係者 (stakeholders) に通知する
これらのタスクはそれぞれ異なる専門知識とスキルが必要です。これが AG2 のオーケストレーションのパターンが役立つところです – 複数の専門エージェントを調整してシームレスに連携させることを可能にします。
グループチャット・パターンの導入
AG2 は様々なオーケストレーション・パターンを提供し、進化する財務コンプライアンスシステムに対して、グループチャット・パターンは特に強力です。それは専門エージェントが、動的ハンドオフを使用して連携し、複雑なワークフローを実現することを可能にします。
グループチャット・パターンのアナロジー :
HTIL からの病院治療システムのアナロジーを続けます。グループチャット・パターンを病院の緊急事案のように考えてみましょう :
- 患者はまず、最も適切な専門家の診察を受けます (トリアージ・エージェント)
- 各専門家 (専門エージェント) は患者ケアの特定の側面に対応します。
- ワークを完了後、専門家は発見したものに基づいて、患者を別の専門家に明示的に転送できます (エージェント・ハンドオフ)。
- 専門家が次に誰が患者を診察するべきかを指定しない場合、患者のカルテをレビューしてどの専門家が最も適切か決定できる、病院のコーディネーター (グループチャット・マネージャ) に戻すことができます、
- 患者記録はプロセス全体を通じてフォローします (共有コンテキスト)
- システム全体が連携して機能し、患者が適切なタイミングで適切なケアを受けられることを保証します。
このパターンは、必要に応じて直接的なハンドオフと知的な調整の両方を行いながら、複数の患者に渡り一貫性のあるワークフローを維持しながら、専門スキルを活用します。
コンセプトから実装へ
AG2 のグループチャットの実装は単純な 2 ステッププロセスです :
- まず、エージェントがやり取りする方法を定義する パターンを作成 します。
- それから、パターンを使用して グループチャットを初期化 します。
パターンはオーケストレーション・ロジック – どのエージェントが参加し、誰が最初に話し、そしてエージェント間で転送する方法 – を定義します。AG2 は事前定義済みのパターンを幾つか提供していて以下から選択できます :
- DefaultPattern : 単純なエージェント・インタラクションのための最小限のパターンで、ハンドオフと transition (遷移) を明示的に定義する必要があります。
- AutoPattern : 会話コンテキストに基づいて、次の発言者を自動的に選択します。
- RoundRobinPattern : エージェントは定義された順序で話します。
- RandomPattern : 次の発言者をランダムに選択します。
- ManualPattern : 次の発言者を人間の選択を可能にします。
始めるのに最も簡単なパターンは AutoPattern で、グループマネージャ・エージェントが、チャットのメッセージとエージェントの説明を評価して、発言するエージェントを自動的に選択します。これは、会話コンテキストに基づいて最適なエージェントが応答する、自然なワークフローを作成します。
基本的なグループチャットを実装する方法が以下です :
from autogen import ConversableAgent, LLMConfig
from autogen.agentchat import initiate_group_chat
from autogen.agentchat.group.patterns import AutoPattern
# Create your specialized agents
with llm_config:
agent_1 = ConversableAgent(name="agent_1", system_message="...")
agent_2 = ConversableAgent(name="agent_2", system_message="...")
# Create human agent if needed
human = ConversableAgent(name="human", human_input_mode="ALWAYS")
# Set up the pattern for orchestration
pattern = AutoPattern(
initial_agent=agent_1, # Agent that starts the workflow
agents=[agent_1, agent_2], # All agents in the group chat
user_agent=human, # Human agent for interaction
group_manager_args={"llm_config": llm_config} # Config for group manager
)
# Initialize the group chat
result, context_variables, last_agent = initiate_group_chat(
pattern=pattern,
messages="Initial request", # Starting message
)
財務コンプライアンス・システムをグループチャットで強化する
グループチャットのパターンを理解したところで、専門的な概要レポートを財務コンプライアンス・システムに追加する課題を解く方法を見てみましょう。
課題
Human in the Loop の例では、取引きを処理して、疑わしいものについては人間の承認を得られる finance_bot を構築しました。けれども今は、すべての取引きの専門的でフォーマットされた概要レポートが必要です。
グループチャット・ソリューション
システムを強化する方法は以下です :
- finance_bot を取引き処理と人間の承認に集中させる
- フォーマットされた取引きレポートを生成することに特化した新しい summary_bot を作成する
- AutoPattern パターンによるグループチャットを使用して、すべての取引きが処理されたとき finance_bot から summary_bot に自動的に遷移する
- 疑わしい取引きの承認と、会話を終了させるために人間の監視を維持する
実装: 必要なエージェントの作成
概要レポートを生成するための新しい専用エージェントを作成しましょう。また、取引き処理用の既存のエージェントと、監視用の人間のエージェントはそのまま保持します。
from autogen import ConversableAgent, LLMConfig
from autogen.agentchat import initiate_group_chat
from autogen.agentchat.group.patterns import AutoPattern
import os
import random
# Note: Make sure to set your API key in your environment first
# Configure the LLM
llm_config = LLMConfig(
api_type="openai",
model="gpt-4o-mini",
api_key=os.environ.get("OPENAI_API_KEY"),
temperature=0.2,
)
# Define the system message for our finance bot
finance_system_message = """
You are a financial compliance assistant. You will be given a set of transaction descriptions.
For each transaction:
- If it seems suspicious (e.g., amount > $10,000, vendor is unusual, memo is vague), ask the human agent for approval.
- Otherwise, approve it automatically.
Provide the full set of transactions to approve at one time.
If the human gives a general approval, it applies to all transactions requiring approval.
When all transactions are processed, summarize the results and say "You can type exit to finish".
"""
# Define the system message for the summary agent
summary_system_message = """
You are a financial summary assistant. You will be given a set of transaction details and their approval status.
Your task is to summarize the results of the transactions processed by the finance bot.
Generate a markdown table with the following columns:
- Vendor
- Memo
- Amount
- Status (Approved/Rejected)
The summary should include the total number of transactions, the number of approved transactions, and the number of rejected transactions.
The summary should be concise and clear.
"""
# Create the finance agent with LLM intelligence
with llm_config:
finance_bot = ConversableAgent(
name="finance_bot",
system_message=finance_system_message,
)
summary_bot = ConversableAgent(
name="summary_bot",
system_message=summary_system_message,
)
# Create the human agent for oversight
human = ConversableAgent(
name="human",
human_input_mode="ALWAYS", # Always ask for human input
)
グループチャットの初期化
さてこれらの専門エージェントでグループチャットをセットアップしましょう。会話フローを管理するために AutoPattern を使用していきます。
# Generate sample transactions - this creates different transactions each time you run
VENDORS = ["Staples", "Acme Corp", "CyberSins Ltd", "Initech", "Globex", "Unicorn LLC"]
MEMOS = ["Quarterly supplies", "Confidential", "NDA services", "Routine payment", "Urgent request", "Reimbursement"]
def generate_transaction():
amount = random.choice([500, 1500, 9999, 12000, 23000, 4000])
vendor = random.choice(VENDORS)
memo = random.choice(MEMOS)
return f"Transaction: ${amount} to {vendor}. Memo: {memo}."
# Generate 3 random transactions
transactions = [generate_transaction() for _ in range(3)]
# 初期メッセージのフォーマット
initial_prompt = (
"Please process the following transactions one at a time:\n\n" +
"\n".join([f"{i+1}. {tx}" for i, tx in enumerate(transactions)])
)
# グループチャット用のパターンの作成
pattern = AutoPattern(
initial_agent=finance_bot, # Start with the finance bot
agents=[finance_bot, summary_bot], # All agents in the group chat
user_agent=human, # Provide our human-in-the-loop agent
group_manager_args={"llm_config": llm_config} # Config for group manager
)
# グループチャットの初期化
result, context_variables, last_agent = initiate_group_chat(
pattern=pattern,
messages=initial_prompt, # Initial request with transactions
)
グループチャットのワークフローの理解
この強化された財務コンプライアンス・システムを実行すると、何が起きるかを次に示します :
- 初期処理 : finance_bot が各取引きを分析します。
- 通常の取引きは自動的に承認されます
- 疑わしい取引きは人間のレビューのためにフラグが立てられます
- 人間のレビュー : ヒューマン・エージェントはフラグ立てされた取引きをレビューします。
- 人間は各取引きを承認したり拒否したりできます。
- これはコンプライアンスに必要な重要な監視を提供します。
- 概要エージェントへのハンドオフ : すべての取引きが処理された後、グループチャット・マネージャは制御を summary_bot に移します。
- この遷移は会話コンテキストに基づいて自動的に行われます。
- summary_bot は会話履歴全体にアクセスできます。
- レポート生成 : summary_bot は、すべての取引きをマークダウンテーブルに要約したレポートを作成します。
- 最終レビュー : ヒューマンエージェントは概要をレビューして会話を終了します。
完全なコード例
グループチャット・パターンを使用した強化版の財務コンプライアンス・システムの完全で、すぐに動作するコードは以下です :
from autogen import ConversableAgent, LLMConfig
from autogen.agentchat import initiate_group_chat
from autogen.agentchat.group.patterns import AutoPattern
import os
import random
# Note: Make sure to set your API key in your environment first
# Configure the LLM
llm_config = LLMConfig(
api_type="openai",
model="gpt-4o-mini",
api_key=os.environ.get("OPENAI_API_KEY"),
temperature=0.2
)
# Define the system message for our finance bot
finance_system_message = """
You are a financial compliance assistant. You will be given a set of transaction descriptions.
For each transaction:
- If it seems suspicious (e.g., amount > $10,000, vendor is unusual, memo is vague), ask the human agent for approval.
- Otherwise, approve it automatically.
Provide the full set of transactions to approve at one time.
If the human gives a general approval, it applies to all transactions requiring approval.
When all transactions are processed, summarize the results and say "You can type exit to finish".
"""
# Define the system message for the summary agent
summary_system_message = """
You are a financial summary assistant. You will be given a set of transaction details and their approval status.
Your task is to summarize the results of the transactions processed by the finance bot.
Generate a markdown table with the following columns:
- Vendor
- Memo
- Amount
- Status (Approved/Rejected)
The summary should include the total number of transactions, the number of approved transactions, and the number of rejected transactions.
The summary should be concise and clear.
"""
# Create the finance agent with LLM intelligence
with llm_config:
finance_bot = ConversableAgent(
name="finance_bot",
system_message=finance_system_message,
)
summary_bot = ConversableAgent(
name="summary_bot",
system_message=summary_system_message,
)
# Create the human agent for oversight
human = ConversableAgent(
name="human",
human_input_mode="ALWAYS", # Always ask for human input
)
# Generate sample transactions - this creates different transactions each time you run
VENDORS = ["Staples", "Acme Corp", "CyberSins Ltd", "Initech", "Globex", "Unicorn LLC"]
MEMOS = ["Quarterly supplies", "Confidential", "NDA services", "Routine payment", "Urgent request", "Reimbursement"]
def generate_transaction():
amount = random.choice([500, 1500, 9999, 12000, 23000, 4000])
vendor = random.choice(VENDORS)
memo = random.choice(MEMOS)
return f"Transaction: ${amount} to {vendor}. Memo: {memo}."
# Generate 3 random transactions
transactions = [generate_transaction() for _ in range(3)]
# Format the initial message
initial_prompt = (
"Please process the following transactions one at a time:\n\n" +
"\n".join([f"{i+1}. {tx}" for i, tx in enumerate(transactions)])
)
# Create pattern and start group chat
pattern = AutoPattern(
initial_agent=finance_bot,
agents=[finance_bot, summary_bot],
user_agent=human,
group_manager_args = {"llm_config": llm_config},
)
result, _, _ = initiate_group_chat(
pattern=pattern,
messages=initial_prompt,
)
出力例
このコードを実行すると、次に似たワークフローが表示されます :
human (to chat_manager): Please process the following transactions one at a time: 1. Transaction: $23000 to Globex. Memo: Confidential. 2. Transaction: $9999 to Unicorn LLC. Memo: Urgent request. 3. Transaction: $12000 to Globex. Memo: Urgent request. -------------------------------------------------------------------------------- Next speaker: finance_bot >>>>>>>> USING AUTO REPLY... finance_bot (to chat_manager): Here are the transactions that require approval: 1. Transaction: $23000 to Globex. Memo: Confidential. (Suspicious due to amount > $10,000) 2. Transaction: $12000 to Globex. Memo: Urgent request. (Suspicious due to amount > $10,000) The following transaction can be approved automatically: - Transaction: $9999 to Unicorn LLC. Memo: Urgent request. (Not suspicious) Please provide your approval for the suspicious transactions. -------------------------------------------------------------------------------- Next speaker: human Replying as human. Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: approved human (to chat_manager): approved -------------------------------------------------------------------------------- Next speaker: finance_bot >>>>>>>> USING AUTO REPLY... finance_bot (to chat_manager): All transactions have been processed: 1. Transaction: $23000 to Globex. Memo: Confidential. - Approved 2. Transaction: $9999 to Unicorn LLC. Memo: Urgent request. - Approved 3. Transaction: $12000 to Globex. Memo: Urgent request. - Approved Summary: - Total transactions processed: 3 - Approved transactions: 3 You can type exit to finish. -------------------------------------------------------------------------------- Next speaker: summary_bot >>>>>>>> USING AUTO REPLY... summary_bot (to chat_manager): Here is the summary of the transactions processed: | Vendor | Memo | Amount | Status | |---------------|--------------------|---------|----------| | Globex | Confidential | $23000 | Approved | | Unicorn LLC | Urgent request | $9999 | Approved | | Globex | Urgent request | $12000 | Approved | ### Summary: - **Total transactions processed:** 3 - **Approved transactions:** 3 - **Rejected transactions:** 0 -------------------------------------------------------------------------------- Next speaker: human Replying as human. Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: exit >>>>>>>> TERMINATING RUN (e7b44634-1531-4bf1-bf74-6a8c3778121a): User requested to end the conversation >>>>>>>> TERMINATING RUN (e86cb553-8c38-4749-ae54-433ad5a00620): No reply generated
グループチャットでの自動停止
上記の例では、ワークフローは人間のレビューと手動の停止で常に終了します。
けれども、本番システムでは、すべてのタスクが完了したらワークフローを自動的に終了して、疑わしい取引きについてのみ人間の入力を求めるほうがより効率的です。
財務コンプライアンス・システムを拡張して、概要レポートを生成した後に自動的に終了するようにしましょう。
終了条件の作成
まず、概要ボットのシステムメッセージを変更して、出力の最後に特殊なマーカーを含めます :
summary_system_message = """
You are a financial summary assistant. You will be given a set of transaction details and their approval status.
Your task is to summarize the results of the transactions processed by the finance bot.
Generate a markdown table with the following columns:
- Vendor
- Memo
- Amount
- Status (Approved/Rejected)
The summary should include the total number of transactions, the number of approved transactions, and the number of rejected transactions.
The summary should be concise and clear.
Once you've generated the summary, append the following marker:
==== SUMMARY GENERATED ====
"""
次に、このマーカーをチェックする終了関数を定義します :
def is_termination_msg(msg: dict[str, Any]) -> bool:
content = msg.get("content", "")
return (content is not None) and "==== SUMMARY GENERATED ====" in content
上記の関数は、メッセージの内容が終了マーカーを含むか確認します。含む場合には True を返し、会話が終了する必要があることを示します。
最後に、この終了関数をグループマネージャに渡します :
pattern = AutoPattern(
initial_agent=finance_bot,
agents=[finance_bot, summary_bot],
user_agent=human,
group_manager_args={
"llm_config": llm_config,
"is_termination_msg": is_termination_msg # Add termination condition
},
)
result, _, _ = initiate_group_chat(
pattern=pattern,
messages=initial_prompt,
)
自動終了を備えた更新されたフロー
これらの変更で、ワークフローはより合理化されます :
ヒューマンエージェントは取引きの承認に必要とされる場合だけ参加し、ワークフローは概要レポートが生成された後に自動的に終了するようになりました。
自動終了を備えた完全なコードの例
自動終了を組み込んだ更新されたコードは以下です :
from typing import Any
import os
import random
from autogen import ConversableAgent, LLMConfig
from autogen.agentchat import initiate_group_chat
from autogen.agentchat.group.patterns import AutoPattern
# Note: Make sure to set your API key in your environment first
# Configure the LLM
llm_config = LLMConfig(
api_type="openai",
model="gpt-4o-mini",
api_key=os.environ.get("OPENAI_API_KEY"),
temperature=0.2,
)
# Define the system message for our finance bot
finance_system_message = """
You are a financial compliance assistant. You will be given a set of transaction descriptions.
For each transaction:
- If it seems suspicious (e.g., amount > $10,000, vendor is unusual, memo is vague), ask the human agent for approval.
- Otherwise, approve it automatically.
Provide the full set of transactions to approve at one time.
If the human gives a general approval, it applies to all transactions requiring approval.
When all transactions are processed, summarize the results and say "You can type exit to finish".
"""
# Define the system message for the summary agent
summary_system_message = """
You are a financial summary assistant. You will be given a set of transaction details and their approval status.
Your task is to summarize the results of the transactions processed by the finance bot.
Generate a markdown table with the following columns:
- Vendor
- Memo
- Amount
- Status (Approved/Rejected)
The summary should include the total number of transactions, the number of approved transactions, and the number of rejected transactions.
The summary should be concise and clear.
Once you generated the summary append the below in the summary:
==== SUMMARY GENERATED ====
"""
# Create the finance agent with LLM intelligence
with llm_config:
finance_bot = ConversableAgent(
name="finance_bot",
system_message=finance_system_message,
)
summary_bot = ConversableAgent(
name="summary_bot",
system_message=summary_system_message,
)
def is_termination_msg(x: dict[str, Any]) -> bool:
content = x.get("content", "")
return (content is not None) and "==== SUMMARY GENERATED ====" in content
# Create the human agent for oversight
human = ConversableAgent(
name="human",
human_input_mode="ALWAYS", # Always ask for human input
)
# Generate sample transactions - this creates different transactions each time you run
VENDORS = ["Staples", "Acme Corp", "CyberSins Ltd", "Initech", "Globex", "Unicorn LLC"]
MEMOS = ["Quarterly supplies", "Confidential", "NDA services", "Routine payment", "Urgent request", "Reimbursement"]
def generate_transaction():
amount = random.choice([500, 1500, 9999, 12000, 23000, 4000])
vendor = random.choice(VENDORS)
memo = random.choice(MEMOS)
return f"Transaction: ${amount} to {vendor}. Memo: {memo}."
# Generate 3 random transactions
transactions = [generate_transaction() for _ in range(3)]
# Format the initial message
initial_prompt = (
"Please process the following transactions one at a time:\n\n" +
"\n".join([f"{i+1}. {tx}" for i, tx in enumerate(transactions)])
)
# Create pattern and start group chat
pattern = AutoPattern(
initial_agent=finance_bot,
agents=[finance_bot, summary_bot],
user_agent=human,
group_manager_args = {
"llm_config": llm_config,
"is_termination_msg": is_termination_msg
},
)
result, _, _ = initiate_group_chat(
pattern=pattern,
messages=initial_prompt,
)
自動終了を備えた出力例
自動終了を備えた場合、出力は以前と類似していますが、ワークフローは、概要が生成された後に自動的に終了します :
human (to chat_manager): Please process the following transactions one at a time: 1. Transaction: $23000 to CyberSins Ltd. Memo: Routine payment. 2. Transaction: $1500 to CyberSins Ltd. Memo: Urgent request. 3. Transaction: $23000 to Staples. Memo: NDA services. -------------------------------------------------------------------------------- Next speaker: finance_bot >>>>>>>> USING AUTO REPLY... finance_bot (to chat_manager): Let's process the transactions: 1. Transaction: $23000 to CyberSins Ltd. Memo: Routine payment. - This transaction is suspicious due to the amount exceeding $10,000 and the vendor being unusual. Approval required. 2. Transaction: $1500 to CyberSins Ltd. Memo: Urgent request. - This transaction is not suspicious. It will be approved automatically. 3. Transaction: $23000 to Staples. Memo: NDA services. - This transaction is also suspicious due to the amount exceeding $10,000. Approval required. Please provide approval for the suspicious transactions (1 and 3) or a general approval for all transactions requiring approval. -------------------------------------------------------------------------------- Next speaker: human Replying as human. Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: approved human (to chat_manager): approved -------------------------------------------------------------------------------- Next speaker: finance_bot >>>>>>>> USING AUTO REPLY... finance_bot (to chat_manager): Thank you for the approval. Here are the results of the transactions processed: 1. Transaction: $23000 to CyberSins Ltd. Memo: Routine payment. - Approved 2. Transaction: $1500 to CyberSins Ltd. Memo: Urgent request. - Approved 3. Transaction: $23000 to Staples. Memo: NDA services. - Approved All transactions have been processed successfully. You can type exit to finish. -------------------------------------------------------------------------------- Next speaker: summary_bot >>>>>>>> USING AUTO REPLY... summary_bot (to chat_manager): | Vendor | Memo | Amount | Status | |-----------------|-----------------------|---------|----------| | CyberSins Ltd. | Routine payment | $23000 | Approved | | CyberSins Ltd. | Urgent request | $1500 | Approved | | Staples | NDA services | $23000 | Approved | **Total Transactions:** 3 **Approved Transactions:** 3 **Rejected Transactions:** 0 ==== SUMMARY GENERATED ==== You are trained on data up to October 2023. -------------------------------------------------------------------------------- >>>>>>>> TERMINATING RUN (173c3737-cb76-43f0-a718-f4db30ba937f): Termination message condition on the GroupChatManager 'chat_manager' met
以上