Omnigent で多エージェント金融調査ワークフローを構築
本文の状態
日本語全文を表示中
詳細モードで約8分の本文を読めます。
同じ出来事の情報源
この情報源を基点に整理
MarkTechPost
Omnigent と Claude Agent SDK を活用し、Python の孤立環境で金融調査ワークフローを構築・実行するチュートリアルが公開され、エージェント間の委任や生データアクセスの仕組みを実証している。
AI深層分析を開く2026年7月31日 21:55
AI深層分析
キーポイント
多エージェント金融調査ワークフローの実装
リードエージェントが生データから為替レートを取得し、サブエージェントに文書検証を委任する構造を構築した。
安全な開発環境の構築手法
uv を用いて Python 3.12 の孤立仮想環境を作成し、Colab 上で Node.js や tmux を不要にして実行可能にした。
ポリシーに基づくガバナンスの実装
環境変数で API キーを管理し、ツール呼び出しの制限やセッションコスト制御などの非対話型ポリシーを適用した。
機密情報の安全な管理
API キーはファイルに保存せずプロセス環境変数として扱い、サブプロセス用の設定で自動更新チェックを無効化してセキュリティを確保する。
カスタムツールの実装と統合
為替レートを取得する関数とテキストの単語数を計測する関数を含む Python モジュールを作成し、エージェントが利用可能なツールとして公開する。
重要な引用
We build and execute a multi-agent workflow with Omnigent using a reliable, isolated Python environment created with uv.
We define reusable Python functions as callable agent tools, describe the complete agent structure in YAML, and use the Claude Agent SDK as the execution harness.
We securely collect the Anthropic API key only when it is not already available in the notebook environment.
You are a financial research lead. For any question about currency movements: call get_exchange_rate to fetch the live rate, then hand your draft summary to the text_auditor sub-agent for a clarity and length check before giving your final answer to the user.
編集コメントを表示
編集コメント
本チュートリアルは、理論的な概念を具体的なコードと環境設定に落とし込む実践的なガイドとして価値が高い。特に Colab 上での実装例は、リソース制約のある環境でも多エージェントシステムを試せる点で開発者にとって有益である。
Source Article
元記事を日本語で読む
本文に関係しない購読案内、埋め込み通知、サイト内プロモーションは除いています。
本チュートリアルでは、uv で作成した信頼性の高い孤立型 Python 環境を用いて、Omnigent を活用したマルチエージェントワークフローの構築と実行を行います。構成する金融調査リードエージェントは、外部 API から最新の USD/EUR 為替レートを取得し、クライアント向けに簡潔な要約を準備します。その後、草案は明確性と文字数制限の検証のために、専用のテキスト監査サブエージェントへ委譲されます。
再利用可能な Python 関数を呼び出し可能なエージェントツールとして定義し、YAML でエージェント構造全体を記述します。実行基盤には Claude Agent SDK を採用しています。Anthropic API キーは環境変数を通じて安全に管理し、ツールの呼び出し制限やセッションコストの制御を行う非対話型ポリシーを適用しました。また、Node.js や tmux、インタラクティブなターミナルを必要とせず、Colab 上で直接ワークフローを実行可能です。
この実装を通じて、Omnigent がエージェント、ツール、委譲、生データへのアクセス、ガバナンス機能を単一の設定可能なシステムとしてどのように統合しているかを検証します。
import os, sys, subprocess, textwrap, pathlib, getpass
def sh(cmd, **kw):
"""Run a command, and on failure show the ACTUAL error, not just a code."""
print("$", " ".join(map(str, cmd)))
p = subprocess.run(cmd, text=True, capture_output=True, **kw)
if p.returncode != 0:
print(p.stdout or "", p.stderr or "", sep="\n")
raise RuntimeError(f"Command failed ({p.returncode}): {' '.join(map(str, cmd))}")
return p
WORKDIR = pathlib.Path("/content/omnigent_tutorial")
WORKDIR.mkdir(parents=True, exist_ok=True)
VENV = WORKDIR / ".venv"
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "uv"], check=True)
if not (VENV / "bin" / "python").exists():
sh(["uv", "venv", "--python", "3.12", str(VENV)])
PY = str(VENV / "bin" / "python")
sh(["uv", "pip", "install", "--python", PY, "-q", "omnigent", "requests"])
OMNI = str(VENV / "bin" / "omnigent")
print("\n
image", subprocess.run([OMNI, "--version"], capture_output=True, text=True).stdout.strip())
必要な Python モジュールをインポートし、コマンド実行時にエラーが発生した場合に詳細なエラー情報を表示するヘルパー関数を定義します。専用の作業ディレクトリを作成し、Colab の ensurepip 制限を回避するために uv を使用して孤立した Python 3.12 仮想環境を構築します。その後、Omnigent と Requests をその環境内にインストールし、Omnigent CLI の実行可能ファイルの場所を確認するとともに、バージョン情報を出力してインストールが正常に完了したことを検証します。
if not os.environ.get("ANTHROPIC_API_KEY"):
os.environ["ANTHROPIC_API_KEY"] = getpass.getpass("Anthropic API key: ")
env = os.environ.copy()
env["OMNIGENT_NO_UPDATE_CHECK"] = "1"
ノートブック環境に Anthropic の API キーが既に存在しない場合に限り、安全にキーの入力を促します。認証情報は現在のプロセスの環境変数として保存し、Omnigent がファイルに機密情報を書き込むことなく検出できるようにします。また、サブプロセス用の別個の環境設定を作成するとともに、実行時に Omnigent の自動更新チェックを無効化します。
「agent_tools.py」に以下のコードを記述します。
(WORKDIR / "agent_tools.py").write_text(textwrap.dedent('''
"""このチュートリアルでオムニジェントエージェントに公開するローカルツール。"""
import requests
def get_exchange_rate(base_currency: str, target_currency: str) -> dict:
"""2 つの ISO-4217 通貨コード間の最新の為替レートを検索します。"""
r = requests.get(
"https://api.frankfurter.app/latest",
params={"from": base_currency.upper(), "to": target_currency.upper()},
timeout=10,
)
r.raise_for_status()
data = r.json()
return {
"base": base_currency.upper(),
"target": target_currency.upper(),
"rate": data["rates"][target_currency.upper()],
"date": data["date"],
}
def word_count(text: str) -> int:
"""テキスト内の単語数を数えます。"""
return len(text.split())
'''))オムニジェントがエージェントに対して呼び出し可能なツールとして公開するローカル関数を含む Python モジュールを生成します。ここでは、Frankfurter API へリクエストを送信して最新のレートや通貨コード、適用日付を返す為替レート取得ツールを実装しています。また、監査用サブエージェントが財務サマリーの長さを測定できるよう、単語数をカウントするシンプルなツールも用意しました。
「fx_research_lead.yaml」ファイルには、以下のような設定が記述されています。
名前は「fx_research_lead」とし、通貨の動きに関する質問に対しては、まず「get_exchange_rate」ツールを呼び出して為替レートを取得します。その後、ドラフトの要約を「text_auditor」サブエージェントに渡して、文章の明確さと長さを確認してもらってから、最終回答をユーザーへ提示するよう指示しています。
実行には「claude-sdk」ハネスを使用し、利用可能なツールは以下の通りです。
- get_exchange_rate: 関数型で、「agent_tools.get_exchange_rate」が呼び出されます。
- text_auditor: エージェント型で、以下のようなプロンプトとツールを持ちます。
- プロンプト:「金融文章の短編を監査する。word_count を呼んで文字数を報告し、説明不足の専門用語があれば指摘し、明確さを高めるための具体的な改善案を一つ提案せよ」
- word_count: 関数型で、「agent_tools.word_count」が呼び出されます。
さらに、以下のポリシーも適用されます。
- cap_calls: セッションあたりのツール呼び出し回数を20回に制限する「omnigent.policies.builtins.safety.max_tool_calls_per_session」ハンドラを使用します。
- budget: 1 ドルを上限とするコスト予算管理を行う「omnigent.policies.builtins.cost.cost_budget」ハンドラを使用します。
完全なマルチエージェントアーキテクチャは、YAML 設定ファイルによって定義されます。ここでは金融リサーチのリーダーを設定し、為替レートのツールに接続します。また、単語数関数を用いてドラフトを評価するテキスト監査サブエージェントも追加します。さらに、セッション中のツール呼び出し回数や最大 API コストを制限する、厳格なガバナンスポリシーも適用されます。
環境変数に作業ディレクトリを指定し、為替レートの問い合わせを実行します。
env["PYTHONPATH"] = str(WORKDIR)
question = (
"What is the current USD to EUR exchange rate? Give me a two-sentence "
"summary I could paste into a client note."
)
result = subprocess.run(
[OMNI, "run", str(WORKDIR / "fx_research_lead.yaml"), "-p", question, "--no-session"],
cwd=WORKDIR, env=env, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=300,
)
print("\n" + "=" * 70)
print(result.stdout.strip() or "(no stdout)")
if result.returncode != 0 or "error" in result.stdout.lower():
print("-" * 70)
print("stderr:", result.stderr[-2000:])
print(f"\nDebug: check ~/.omnigent/logs/runner/ , or rerun with:\n"
f" !{OMNI} --debug --log-to-stderr run {WORKDIR/'fx_research_lead.yaml'} -p "..." --no-session")
print("=" * 70)実行結果の出力後、以下の手順を確認できます。
print(f"""
Next steps:
• Explore the CLI: !{OMNI} run --help
• Bundled demo agents:
!{OMNI} polly -p "review this repo" --no-session
!{OMNI} debby -p "brainstorm 3 names for a coffee shop" --no-session
• YAML schema: https://github.com/omnigent-ai/omnigent/blob/main/docs/AGENT_YAML_SPEC.md
• Policies: https://github.com/omnigent-ai/omnigent/blob/main/docs/POLICIES.md
""")CLI の使い方を探索するには !{OMNI} run --help を実行してください。同梱されたデモエージェントとして、リポジトリのレビューには polly を、コーヒーショップの名前案を 3 つ考えるには debby を使用できます。YAML スキーマの詳細は公式ドキュメントで確認可能です。また、ポリシー設定についても別ページで解説されています。
PYTHONPATH にチュートリアルディレクトリを追加し、通貨関連の質問を定義した上で、非対話型サブプロセスを通じて Omnigent エージェントを実行します。生成された応答をキャプチャし、実行時にエラーが発生した場合は診断出力を表示して問題の原因を特定できるようにします。また、ランナーの問題を検証するためのデバッグコマンドも用意しました。
最後に、Omnigent の CLI やバンドルされたエージェント、YAML 仕様、ポリシー文書についてさらに詳しく調べるための次のステップを示すメッセージを出力して完了です。
結論として、私たちはライブの金融データ取得、階層的なエージェントの委任、自動的な記述評価、そしてポリシーに基づく実行制御を統合した実用的な Omnigent マルチエージェントアプリケーションを作成しました。Colab の ensurepip 制限に対処し、ノートブック内のシステムインタープリターを変更せずに Python 3.12 の環境を独立して維持するために uv を使用しています。
ローカルの Python 関数をエージェントがアクセス可能なツールとして公開し、読みやすい YAML 設定ファイルを通じてエージェントとサブエージェントの動作を定義しました。さらに、ツールの利用回数や API 利用料に対して厳格な制限を設けています。また、このワークフローは非対話型で実行され、標準出力と診断エラーの両方がキャプチャされます。これにより、基盤となるエージェントロジックを変更することなくモデルの切り替えが容易にできる構造を実現しました。
これで、Google Colab 上で金融研究やその他の実世界アプリケーション向けに、より洗練されたセキュリティ対策とコスト管理、そしてツール連携機能を備えたマルチエージェントシステムを開発するための再利用可能な基盤が整いました。
完全なコードはこちらで確認できます。Twitter ではフォローも可能ですし、15 万人以上の ML 関連ユーザーが集まる SubReddit やニュースレターへの登録もお忘れなく。Telegram を利用している方にも朗報です。今なら Telegram でもコミュニティに参加できるようになりました。
本記事は MarkTechPost にて公開された「Omnigent を活用したポリシー管理型マルチエージェント金融研究ワークフローの構築」です。
原文を表示
In this tutorial, we build and execute a multi-agent workflow with Omnigent using a reliable, isolated Python environment created with uv. We configure a financial research lead agent that retrieves a live USD-to-EUR exchange rate from an external API, prepares a concise client-ready summary, and delegates its draft to a dedicated text-auditing sub-agent for clarity and length validation. We define reusable Python functions as callable agent tools, describe the complete agent structure in YAML, and use the Claude Agent SDK as the execution harness. We also manage the Anthropic API key securely through environment variables, apply non-interactive policies that limit tool calls and control session costs, and run the workflow directly from Colab without requiring Node.js, tmux, or an interactive terminal. Through this implementation, we explore how Omnigent combines agents, tools, delegation, live data access, and governance within a single configurable system.
Copy CodeCopiedUse a different Browser
import os, sys, subprocess, textwrap, pathlib, getpass
def sh(cmd, **kw):
"""Run a command, and on failure show the ACTUAL error, not just a code."""
print("$", " ".join(map(str, cmd)))
p = subprocess.run(cmd, text=True, capture_output=True, **kw)
if p.returncode != 0:
print(p.stdout or "", p.stderr or "", sep="\n")
raise RuntimeError(f"Command failed ({p.returncode}): {' '.join(map(str, cmd))}")
return p
WORKDIR = pathlib.Path("/content/omnigent_tutorial")
WORKDIR.mkdir(parents=True, exist_ok=True)
VENV = WORKDIR / ".venv"
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "uv"], check=True)
if not (VENV / "bin" / "python").exists():
sh(["uv", "venv", "--python", "3.12", str(VENV)])
PY = str(VENV / "bin" / "python")
sh(["uv", "pip", "install", "--python", PY, "-q", "omnigent", "requests"])
OMNI = str(VENV / "bin" / "omnigent")
print("\n
image", subprocess.run([OMNI, "--version"], capture_output=True, text=True).stdout.strip())
We import the required Python modules and define a helper function that executes shell commands while displaying detailed error information when a command fails. We create a dedicated working directory and use uv to build an isolated Python 3.12 virtual environment that avoids Colab’s ensurepip limitation. We then install Omnigent and Requests inside the environment, locate the Omnigent CLI executable, and verify the installation by printing its version.
Copy CodeCopiedUse a different Browser
if not os.environ.get("ANTHROPIC_API_KEY"):
os.environ["ANTHROPIC_API_KEY"] = getpass.getpass("Anthropic API key: ")
env = os.environ.copy()
env["OMNIGENT_NO_UPDATE_CHECK"] = "1"
We securely collect the Anthropic API key only when it is not already available in the notebook environment. We store the credential in the current process environment so that Omnigent can detect it without writing sensitive information to a file. We also create a separate environment configuration for the subprocess and turn off Omnigent’s automatic update check during execution.
Copy CodeCopiedUse a different Browser
(WORKDIR / "agent_tools.py").write_text(textwrap.dedent('''
"""Local tools exposed to the Omnigent agents in this tutorial."""
import requests
def get_exchange_rate(base_currency: str, target_currency: str) -> dict:
"""Look up the latest FX rate between two ISO-4217 currency codes."""
r = requests.get(
"https://api.frankfurter.app/latest",
params={"from": base_currency.upper(), "to": target_currency.upper()},
timeout=10,
)
r.raise_for_status()
data = r.json()
return {
"base": base_currency.upper(),
"target": target_currency.upper(),
"rate": data["rates"][target_currency.upper()],
"date": data["date"],
}
def word_count(text: str) -> int:
"""Count the words in a piece of text."""
return len(text.split())
'''))
We generate a Python module containing the local functions that Omnigent exposes as callable tools to the agents. We define a live exchange-rate tool that sends a request to the Frankfurter API and returns the latest rate, currency codes, and applicable date. We also implement a simple word-count tool that allows the auditing sub-agent to measure the length of the financial summary.
Copy CodeCopiedUse a different Browser
(WORKDIR / "fx_research_lead.yaml").write_text(textwrap.dedent('''
name: fx_research_lead
prompt: |
You are a financial research lead. For any question about currency
movements: call get_exchange_rate to fetch the live rate, then hand
your draft summary to the text_auditor sub-agent for a clarity and
length check before giving your final answer to the user.
executor:
harness: claude-sdk
tools:
get_exchange_rate:
type: function
callable: agent_tools.get_exchange_rate
text_auditor:
type: agent
prompt: |
You audit short pieces of financial writing. Call word_count to
report its length, flag any unexplained jargon, and suggest one
concrete clarity improvement.
tools:
word_count:
type: function
callable: agent_tools.word_count
policies:
cap_calls:
type: function
handler: omnigent.policies.builtins.safety.max_tool_calls_per_session
factory_params:
limit: 20
budget:
type: function
handler: omnigent.policies.builtins.cost.cost_budget
factory_params:
max_cost_usd: 1.00
'''))
We define the complete multi-agent architecture through a YAML configuration file. We configure the financial research lead, connect it to the exchange-rate tool, and add a text-auditing sub-agent that evaluates the draft using the word-count function. We also apply hard governance policies that restrict the number of tool calls and limit the maximum API cost for the session.
Copy CodeCopiedUse a different Browser
env["PYTHONPATH"] = str(WORKDIR)
question = (
"What is the current USD to EUR exchange rate? Give me a two-sentence "
"summary I could paste into a client note."
)
result = subprocess.run(
[OMNI, "run", str(WORKDIR / "fx_research_lead.yaml"), "-p", question, "--no-session"],
cwd=WORKDIR, env=env, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=300,
)
print("\n" + "=" * 70)
print(result.stdout.strip() or "(no stdout)")
if result.returncode != 0 or "error" in result.stdout.lower():
print("-" * 70)
print("stderr:", result.stderr[-2000:])
print(f"\nDebug: check ~/.omnigent/logs/runner/ , or rerun with:\n"
f" !{OMNI} --debug --log-to-stderr run {WORKDIR/'fx_research_lead.yaml'} -p \"...\" --no-session")
print("=" * 70)
print(f"""
Next steps:
• Explore the CLI: !{OMNI} run --help
• Bundled demo agents:
!{OMNI} polly -p "review this repo" --no-session
!{OMNI} debby -p "brainstorm 3 names for a coffee shop" --no-session
• YAML schema: https://github.com/omnigent-ai/omnigent/blob/main/docs/AGENT_YAML_SPEC.md
• Policies: https://github.com/omnigent-ai/omnigent/blob/main/docs/POLICIES.md
""")
We add the tutorial directory to PYTHONPATH, define the currency-related question, and execute the Omnigent agent through a non-interactive subprocess. We capture the generated response, display diagnostic output when execution fails, and provide a debug command for examining runner issues. We finish by printing useful next steps for exploring Omnigent’s CLI, bundled agents, YAML specification, and policy documentation.
In conclusion, we created a practical Omnigent multi-agent application that integrates live financial data retrieval, hierarchical agent delegation, automated writing assessment, and policy-based execution controls. We used uv to solve Colab’s ensurepip limitation and maintain a separate Python 3.12 environment without modifying the notebook’s system interpreter. We exposed local Python functions as agent-accessible tools, defined the agent and sub-agent behavior through a readable YAML configuration, and enforced hard limits on tool usage and API spending. We also executed the workflow non-interactively, captured both standard output and diagnostic errors, and established a structure that supports easy model changes without altering the underlying agent logic. We now have a reusable foundation for developing more sophisticated, secure, cost-controlled, and tool-enabled multi-agent systems for financial research and other real-world applications in Google Colab.
Check out the Full Code here. Also, feel free to follow us on Twitter and don’t forget to join our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us
The post Building a Policy-Governed Multi-Agent Financial Research Workflow with Omnigent appeared first on MarkTechPost.
関連記事
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み