Skip to content

ClasCat® AI Research

クラスキャット – AgentOS, AI エージェント, MCP, LangChain, AutoGen, AG2, Agno

Menu
  • ホーム
    • ClassCat® AI Research ホーム
    • クラスキャット・ホーム
  • OpenAI API
    • OpenAI Python ライブラリ 1.x : 概要
    • OpenAI ブログ
      • GPT の紹介
      • GPT ストアの紹介
      • ChatGPT Team の紹介
    • OpenAI platform 1.x
      • Get Started : イントロダクション
      • Get Started : クイックスタート (Python)
      • Get Started : クイックスタート (Node.js)
      • Get Started : モデル
      • 機能 : 埋め込み
      • 機能 : 埋め込み (ユースケース)
      • ChatGPT : アクション – イントロダクション
      • ChatGPT : アクション – Getting started
      • ChatGPT : アクション – アクション認証
    • OpenAI ヘルプ : ChatGPT
      • ChatGPTとは何ですか?
      • ChatGPT は真実を語っていますか?
      • GPT の作成
      • GPT FAQ
      • GPT vs アシスタント
      • GPT ビルダー
    • OpenAI ヘルプ : ChatGPT > メモリ
      • FAQ
    • OpenAI ヘルプ : GPT ストア
      • 貴方の GPT をフィーチャーする
    • OpenAI Python ライブラリ 0.27 : 概要
    • OpenAI platform
      • Get Started : イントロダクション
      • Get Started : クイックスタート
      • Get Started : モデル
      • ガイド : GPT モデル
      • ガイド : 画像生成 (DALL·E)
      • ガイド : GPT-3.5 Turbo 対応 微調整
      • ガイド : 微調整 1.イントロダクション
      • ガイド : 微調整 2. データセットの準備 / ケーススタディ
      • ガイド : 埋め込み
      • ガイド : 音声テキスト変換
      • ガイド : モデレーション
      • ChatGPT プラグイン : イントロダクション
    • OpenAI Cookbook
      • 概要
      • API 使用方法 : レート制限の操作
      • API 使用方法 : tiktoken でトークンを数える方法
      • GPT : ChatGPT モデルへの入力をフォーマットする方法
      • GPT : 補完をストリームする方法
      • GPT : 大規模言語モデルを扱う方法
      • 埋め込み : 埋め込みの取得
      • GPT-3 の微調整 : 分類サンプルの微調整
      • DALL-E : DALL·E で 画像を生成して編集する方法
      • DALL·E と Segment Anything で動的マスクを作成する方法
      • Whisper プロンプティング・ガイド
  • Gemini API
    • Tutorials : クイックスタート with Python (1) テキスト-to-テキスト生成
    • (2) マルチモーダル入力 / 日本語チャット
    • (3) 埋め込みの使用
    • (4) 高度なユースケース
    • クイックスタート with Node.js
    • クイックスタート with Dart or Flutter (1) 日本語動作確認
    • Gemma
      • 概要 (README)
      • Tutorials : サンプリング
      • Tutorials : KerasNLP による Getting Started
  • Keras 3
    • 新しいマルチバックエンド Keras
    • Keras 3 について
    • Getting Started : エンジニアのための Keras 入門
    • Google Colab 上のインストールと Stable Diffusion デモ
    • コンピュータビジョン – ゼロからの画像分類
    • コンピュータビジョン – 単純な MNIST convnet
    • コンピュータビジョン – EfficientNet を使用した微調整による画像分類
    • コンピュータビジョン – Vision Transformer による画像分類
    • コンピュータビジョン – 最新の MLPモデルによる画像分類
    • コンピュータビジョン – コンパクトな畳込み Transformer
    • Keras Core
      • Keras Core 0.1
        • 新しいマルチバックエンド Keras (README)
        • Keras for TensorFlow, JAX, & PyTorch
        • 開発者ガイド : Getting started with Keras Core
        • 開発者ガイド : 関数型 API
        • 開発者ガイド : シーケンシャル・モデル
        • 開発者ガイド : サブクラス化で新しい層とモデルを作成する
        • 開発者ガイド : 独自のコールバックを書く
      • Keras Core 0.1.1 & 0.1.2 : リリースノート
      • 開発者ガイド
      • Code examples
      • Keras Stable Diffusion
        • 概要
        • 基本的な使い方 (テキスト-to-画像 / 画像-to-画像変換)
        • 混合精度のパフォーマンス
        • インペインティングの簡易アプリケーション
        • (参考) KerasCV – Stable Diffusion を使用した高性能画像生成
  • TensorFlow
    • TF 2 : 初級チュートリアル
    • TF 2 : 上級チュートリアル
    • TF 2 : ガイド
    • TF 1 : チュートリアル
    • TF 1 : ガイド
  • その他
    • 🦜️🔗 LangChain ドキュメント / ユースケース
    • Stable Diffusion WebUI
      • Google Colab で Stable Diffusion WebUI 入門
      • HuggingFace モデル / VAE の導入
      • LoRA の利用
    • Diffusion Models / 拡散モデル
  • クラスキャット
    • 会社案内
    • お問合せ
    • Facebook
    • ClassCat® Blog
Menu

AG2 ユーザガイド – エージェント・オーケストレーション

Posted on 09/03/202509/04/2025 by Masashi Okumura

AG2 は様々なオーケストレーション・パターンを提供し、進化する財務コンプライアンスシステムに対して、グループチャット・パターンは特に強力です。それは専門エージェントが、動的ハンドオフを使用して連携し、複雑なワークフローを実現することを可能にします。

AG2 : ユーザガイド – 基本概念 : エージェント・オーケストレーション

作成 : クラスキャット・セールスインフォメーション
作成日時 : 09/03/2025
バージョン : v0.9.9

* 本記事は docs.ag2.ai の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :

  • User Guide – Basic Concepts : Agent Orchestration: Coordinating Multiple Agents

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス ⭐️ リニューアルしました 😉

◆ クラスキャット は人工知能に関する各種サービスを提供しています。お気軽にご相談ください :

  • 人工知能導入個別相談会(無償)実施中! [詳細]

  • 人工知能研究開発支援 [詳細]
    1. 自社特有情報を含むチャットボット構築支援
    2. 画像認識 (医療系含む) / 画像生成

  • PoC(概念実証)を失敗させないための支援 [詳細]

◆ お問合せ : 下記までお願いします。

  • クラスキャット セールス・インフォメーション
  • 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

 

以上



クラスキャット

最近の投稿

  • LangChain 1.0 α : コアコンポーネント – 短期メモリ
  • LangChain 1.0 α : コアコンポーネント – ツール
  • LangChain 1.0 α : コアコンポーネント – メッセージ
  • LangChain 1.0 α : コアコンポーネント – モデル
  • LangChain 1.0 α : コアコンポーネント – エージェント

タグ

AG2 (14) Agno (46) AutoGen (13) ClassCat Press Release (20) ClassCat TF/ONNX Hub (11) DGL 0.5 (14) Eager Execution (7) Edward (17) FLUX.1 (16) Gemini (20) HuggingFace Transformers 4.5 (10) HuggingFace Transformers 4.29 (9) Keras 2 Examples (98) Keras 2 Guide (16) Keras 3 (10) Keras Release Note (17) Kubeflow 1.0 (10) LangChain (45) LangGraph (24) LangGraph 0.5 (9) MediaPipe 0.8 (11) Model Context Protocol (16) NNI 1.5 (16) OpenAI Agents SDK (8) OpenAI Cookbook (13) OpenAI platform (10) OpenAI platform 1.x (10) OpenAI ヘルプ (8) TensorFlow 2.0 Advanced Tutorials (33) TensorFlow 2.0 Advanced Tutorials (Alpha) (15) TensorFlow 2.0 Advanced Tutorials (Beta) (16) TensorFlow 2.0 Guide (10) TensorFlow 2.0 Guide (Alpha) (16) TensorFlow 2.0 Guide (Beta) (9) TensorFlow 2.0 Release Note (12) TensorFlow 2.0 Tutorials (20) TensorFlow 2.0 Tutorials (Alpha) (14) TensorFlow 2.0 Tutorials (Beta) (12) TensorFlow 2.4 Guide (24) TensorFlow Deploy (8) TensorFlow Probability (9) TensorFlow Programmer's Guide (22) TensorFlow Release Note (18) TensorFlow Tutorials (33) TF-Agents 0.4 (11)
2025年9月
月 火 水 木 金 土 日
1234567
891011121314
15161718192021
22232425262728
2930  
« 8月    
© 2025 ClasCat® AI Research | Powered by Minimalist Blog WordPress Theme