はじめに
IBM の AI コーディングアシスタント Bob を使うと、プロジェクトの作成から Python ツールの実装・テスト・登録・エージェント化まで、メッセージを送るだけで完結します。
この記事では、ADK の @tool デコレータを活用した Python ツール直接登録(orchestrate tools import --kind python)の手順を、実際の Bob へのメッセージとともに紹介します。
完成するもの
| 成果物 | 内容 |
|---|---|
currency_tools.py |
@tool デコレータで実装した通貨変換ツール 2 本 |
test_currency_tools.py |
pytest による自動テスト(20 件すべて合格) |
currency_agent.yaml |
watsonx Orchestrate 用 Agent 定義ファイル |
| WxO ツール |
convert_currency / list_supported_currencies
|
| WxO エージェント |
currency_agent(LLM: groq/openai/gpt-oss-120b) |
前提条件
- IBM Bob がインストールされていること。まだの場合は IBM Bob 無料トライアル に登録してご利用ください。
- watsonx Agent Development Kit(ADK) のローカル環境が起動していること。環境をお持ちでない場合は、watsonx Orchestrate ADK 入門チュートリアル を参照してセットアップしてください。
全体の流れ
Bob へのメッセージ 1 件ごとに次のステップへと進んでいきます。
Bob → currency_tools.py → pytest → orchestrate tools import → orchestrate agents import
(@tool デコレータ) (ToolResponse) (--kind python) (YAML)
Step 1:プロジェクトディレクトリの作成と仮想環境のセットアップ
まず Bob にプロジェクトの骨格を作ってもらいます。
Bob へのメッセージ ①
currency-agent というプロジェクトディレクトリを作成し、Python 仮想環境をセットアップしてアクティブ化してください。
Bob は以下のコマンドを順番に実行します。
# プロジェクトディレクトリの作成
mkdir currency-agent && cd currency-agent
# 仮想環境の初期化
python -m venv .venv
# 仮想環境の有効化(Mac / Linux)
source .venv/bin/activate
この時点でのディレクトリ構造は次のとおりです。
currency-agent/
└── .venv/ # Python 仮想環境(自動生成)
確認ポイント: ターミナルのプロンプトに
(.venv)が表示されれば、仮想環境の有効化は成功です。
Step 2:ADKのインストール
続いて、watsonx Orchestrate の ADK パッケージをインストールします。
Bob へのメッセージ ②
Python 仮想環境をアクティブ化し、ibm-watsonx-orchestrate がインストールされているか確認してください。
Bob がインストール状況を確認し、未インストールであればそのまま実行します。
source .venv/bin/activate
pip install ibm-watsonx-orchestrate
インストールされる主なパッケージは以下のとおりです。
-
ibm-watsonx-orchestrate2.14.0 -
ibm-watsonx-orchestrate-clients2.14.0 -
ibm-watsonx-orchestrate-core2.14.0
Step 3:currency_tools.py の実装
次に、通貨変換ツールを実装します。
Bob へのメッセージ ③
ibm_watsonx_orchestrate.agent_builder.tools の @tool デコレータを使って watsonx Orchestrate 用の Python ツールファイルを作成してください。
共通の為替レート辞書を共有する 2 つのツールを実装してください:
1. convert_currency(amount, from_currency, to_currency) — USD 基準のハードコードされた為替レートを使って、ある通貨から別の通貨に金額を変換します。対応通貨:USD、JPY、EUR、GBP、CNY。
2. list_supported_currencies() — 対応している通貨コードとその名称の一覧を返します。
Google スタイルの docstring を使用し、ファイル名は currency_tools.py にしてください。
Bob が生成するコードの全体像は次のとおりです。
from ibm_watsonx_orchestrate.agent_builder.tools import tool
# 共有レート辞書(USD 基準)
_EXCHANGE_RATES: dict[str, float] = {
"USD": 1.0,
"JPY": 149.50,
"EUR": 0.92,
"GBP": 0.79,
"CNY": 7.24,
}
_CURRENCY_NAMES: dict[str, str] = {
"USD": "US Dollar",
"JPY": "Japanese Yen",
"EUR": "Euro",
"GBP": "British Pound Sterling",
"CNY": "Chinese Yuan Renminbi",
}
@tool
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""Convert an amount from one currency to another using hardcoded exchange rates.
Args:
amount: The monetary amount to convert.
from_currency: The ISO 4217 currency code to convert from (e.g. "USD").
to_currency: The ISO 4217 currency code to convert to (e.g. "JPY").
Returns:
A human-readable string describing the converted amount.
"""
from_currency = from_currency.upper()
to_currency = to_currency.upper()
if from_currency not in _EXCHANGE_RATES:
return f"Unsupported currency: {from_currency}. Supported currencies: {', '.join(_EXCHANGE_RATES)}."
if to_currency not in _EXCHANGE_RATES:
return f"Unsupported currency: {to_currency}. Supported currencies: {', '.join(_EXCHANGE_RATES)}."
amount_in_usd = amount / _EXCHANGE_RATES[from_currency]
converted = amount_in_usd * _EXCHANGE_RATES[to_currency]
return (
f"{amount:,.2f} {from_currency} = {converted:,.2f} {to_currency} "
f"(rate: 1 {from_currency} = {_EXCHANGE_RATES[to_currency] / _EXCHANGE_RATES[from_currency]:.6f} {to_currency})"
)
@tool
def list_supported_currencies() -> str:
"""List all supported currency codes and their full names.
Returns:
A formatted string listing all supported ISO 4217 currency codes
and their corresponding names.
"""
lines = [f"{code}: {name}" for code, name in _CURRENCY_NAMES.items()]
return "Supported currencies:\n" + "\n".join(lines)
設計のポイント
-
_EXCHANGE_RATESと_CURRENCY_NAMESを 2 つのツールで共有することで、重複を排除しています(DRY 原則) - 通貨コードは
.upper()で大文字に正規化しているため、"usd"のような小文字入力も受け付けます - 未対応の通貨コードが指定された場合は、例外を投げるのではなくエラーメッセージを文字列で返します
- Google スタイルの docstring に Args / Returns を明記しておくと、watsonx Orchestrate がツールの説明として自動的に活用します
Step 4:pytest によるユニットテスト
実装が完成したら、Bob にテストを書いて実行してもらいます。
Bob へのメッセージ ④
currency_tools.py の 2 つの通貨ツールに対してユニットテストを作成して実行してください。convert_currency は 3 組以上の通貨ペアでテストし、list_supported_currencies が 5 つの通貨をすべて返すことを検証してください。
注意点:ToolResponse ラッパー
@tool デコレータを付けた関数の戻り値は、自動的に ToolResponse オブジェクトにラップされます。そのため、テストでは .content プロパティを通じて実際の値にアクセスする必要があります。Bob はこれを考慮し、str と ToolResponse の両方に対応したヘルパー関数を定義します。
def _content(result) -> str:
"""ToolResponse または str どちらでも文字列内容を返すヘルパー。"""
return result.content if hasattr(result, "content") else str(result)
テストコードの例
class TestConvertCurrency:
def test_usd_to_jpy(self):
result = _content(convert_currency(100, "USD", "JPY"))
expected = 100 * _EXCHANGE_RATES["JPY"] / _EXCHANGE_RATES["USD"]
assert f"{expected:.2f} JPY" in result
def test_lowercase_currency_codes_accepted(self):
result = _content(convert_currency(100, "usd", "jpy"))
expected = 100 * _EXCHANGE_RATES["JPY"] / _EXCHANGE_RATES["USD"]
assert f"{expected:.2f} JPY" in result
def test_unsupported_from_currency(self):
result = _content(convert_currency(100, "XXX", "USD"))
assert "Unsupported currency: XXX" in result
class TestListSupportedCurrencies:
def test_contains_all_five_currency_codes(self):
result = _content(list_supported_currencies())
for code in ("USD", "JPY", "EUR", "GBP", "CNY"):
assert code in result
def test_result_starts_with_header(self):
result = _content(list_supported_currencies())
assert result.startswith("Supported currencies:")
実行結果
============================= test session starts ==============================
collected 20 items
test_currency_tools.py::TestConvertCurrency::test_usd_to_jpy PASSED
test_currency_tools.py::TestConvertCurrency::test_jpy_to_eur PASSED
test_currency_tools.py::TestConvertCurrency::test_gbp_to_cny PASSED
test_currency_tools.py::TestConvertCurrency::test_eur_to_usd PASSED
test_currency_tools.py::TestConvertCurrency::test_same_currency_returns_same_amount PASSED
test_currency_tools.py::TestConvertCurrency::test_lowercase_currency_codes_accepted PASSED
test_currency_tools.py::TestConvertCurrency::test_result_contains_from_and_to_currency PASSED
test_currency_tools.py::TestConvertCurrency::test_result_contains_rate_info PASSED
test_currency_tools.py::TestConvertCurrency::test_unsupported_from_currency PASSED
test_currency_tools.py::TestConvertCurrency::test_unsupported_to_currency PASSED
test_currency_tools.py::TestConvertCurrency::test_unsupported_error_lists_supported_currencies PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_contains_all_five_currency_codes PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_contains_all_five_currency_names PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_exactly_five_currencies_listed PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_result_starts_with_header PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_usd_full_name_present PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_jpy_full_name_present PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_eur_full_name_present PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_gbp_full_name_present PASSED
test_currency_tools.py::TestListSupportedCurrencies::test_cny_full_name_present PASSED
============================== 20 passed in 0.39s ==============================
Step 5:watsonx Orchestrate へのツール登録
テストが通ったら、ツールを watsonx Orchestrate に登録します。
Bob へのメッセージ ⑤
currency_tools.py の Python ツールを orchestrate tools import コマンドを使って watsonx Orchestrate にインポートしてください。--kind python を使い、requirements ファイルも含めてください。
Bob はまず pip freeze から開発用パッケージ(pytest など)を除いた requirements.txt を生成してから、インポートコマンドを実行します。
# pytest など開発用パッケージを除外して生成
pip freeze | grep -v "^pytest\|^pluggy\|^iniconfig" > requirements.txt
orchestrate tools import \
--kind python \
--file currency_tools.py \
--requirements-file requirements.txt
成功すると以下のメッセージが表示されます(既存ツールがある場合は updated と表示されます)。
[INFO] - Using requirement file: "requirements.txt"
[INFO] - Tool 'convert_currency' updated successfully
[INFO] - Tool 'list_supported_currencies' updated successfully
Step 6:エージェントの作成と登録
最後に、登録したツールを使うエージェントを定義して watsonx Orchestrate に登録します。
Bob へのメッセージ ⑥
通貨変換エージェント用の Agent YAML ファイルを作成してください。仕様は https://developer.watson-orchestrate.ibm.com/agents/build_agent を参照し、LLM は groq/openai/gpt-oss-120b を使用してください。エージェントは convert_currency と list_supported_currencies ツールを使うように設定してください。作成後、orchestrate コマンドラインを使ってエージェントをインポートしてください。
生成される currency_agent.yaml
Bob は既存エージェントの YAML を orchestrate agents export でエクスポートし、実際のスキーマ(spec_version: v1)を参照して生成します。
kind: native
name: currency_agent
display_name: Currency Conversion Agent
description: |-
A currency conversion agent that converts amounts between major world currencies.
Use this agent to convert between USD, JPY, EUR, GBP, and CNY,
or to list all supported currencies and their full names.
llm: groq/openai/gpt-oss-120b
style: react
instructions: |-
You are a helpful currency conversion assistant.
You have access to two tools:
- convert_currency: converts an amount from one currency to another
- list_supported_currencies: returns all supported currency codes and their full names
...
tools:
- convert_currency
- list_supported_currencies
starter_prompts:
is_default_prompts: false
prompts:
- id: convert_usd_to_jpy
title: Convert USD to JPY
prompt: How much is 100 USD in JPY?
state: active
welcome_content:
welcome_message: Hello! I'm the Currency Conversion Agent.
description: Ask me to convert amounts between USD, JPY, EUR, GBP, and CNY.
is_default_message: false
is_schedulable: false
spec_version: v1
インポートと警告
orchestrate agents import --file currency_agent.yaml
style: react を使用すると次の非推奨警告が表示されますが、インポート自体は成功します。
[WARNING] - The selected style 'react' is set to be deprecated.
Please update to 'react_core' to avoid future issues.
[INFO] - Agent 'currency_agent' imported successfully
補足: 将来に向けて
style: react_coreへの変更が推奨されています(移行ガイド参照)。
Bob が自動でやってくれること
| 作業 | 手作業の場合 | Bob を使った場合 |
|---|---|---|
| プロジェクト作成・仮想環境の構築 | コマンドを調べて手動実行 | ディレクトリ作成から有効化まで一気に実行 |
| ADK パッケージのインストール確認 |
pip show で確認してから手動インストール |
確認からインストールまで連続して実行 |
@tool を使ったコードの実装 |
ADK ドキュメントを読みながら書く | 指示文から完全なコードを生成 |
| テストコードの作成(ToolResponse 対応) | ToolResponse の存在を知らないと全件失敗 | 失敗ログから原因を特定し .content アクセスに自動修正 |
| requirements ファイルの作成 | 手動で内容を調べて記述 | ツール専用ファイルを自動で作成 |
| Agent YAML の作成 | 仕様ページを読み込んで一から記述 | URL を渡すだけで仕様を取得して自動生成 |
| スタイル非推奨警告への対応 | 警告を読んで手動修正 | 警告を検知し react_core に自動修正・再インポート |
ラボ終了時のファイル構成
currency-agent/
├── .venv/ # Python 仮想環境
├── currency_tools.py # @tool デコレータで実装した 2 ツール
├── test_currency_tools.py # pytest(20 件すべて合格)
├── currency_agent.yaml # WxO エージェント定義(style: react)
└── requirements.txt # ランタイム依存パッケージ一覧(pytest 等を除外)
watsonx Orchestrate(アクティブ環境)
├── ツール
│ ├── convert_currency
│ └── list_supported_currencies
└── エージェント: currency_agent(LLM: groq/openai/gpt-oss-120b)
まとめ
@tool デコレータを使った Python ADK 方式には、次のような特徴があります。
- プロジェクトのゼロベース構築から始められる — ディレクトリ作成・仮想環境セットアップも Bob に任せられます
- Python ファイル 1 枚から直接 WxO にツールを登録できる — MCP サーバーのような別プロセスは不要です
-
テストでは
_content(result)ヘルパー経由でアクセスする —@toolデコレータが戻り値をToolResponseにラップするため、hasattr(result, "content")で判定します -
list_supported_currenciesの戻り値は文字列形式 —"Supported currencies:\nUSD: US Dollar\n..."のような改行区切りの文字列を返します - Agent YAML のツール参照はツール名のみで記述します
-
style: react_coreへの移行を推奨 — 現在はreactでも動作しますが、非推奨警告が表示されます
Bob はコードの生成だけでなく、エラーの解釈・自動修正・CLI コマンドの組み立てまで一貫してサポートしてくれます。日本語でメッセージを送るだけで、実装から登録まで約 35 分で完走できます。