始める無料で始める

ドキュメント文字列と型ヒントの追加

LLM が convert_currency() ツールを正しく使えるよう、ドキュメント文字列型ヒントを追加しましょう。これらがないと、LLM はどのツールを呼び出すべきか判断できなかったり、引数に誤った値を渡してしまったりする可能性があります。どちらも、アプリケーションの動作が不安定になる原因です。

FastMCP を使って MCP サーバーがすでに作成され、mcp に割り当てられています。

この演習はコースの一部です

Model Context Protocol(MCP)入門

コースを見る

演習の手順

  • 関数の引数と戻り値に適切な型を追加してください。
  • 3 つの関数引数とその定義が一致するよう、ドキュメント文字列を完成させてください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Adding typing to the function arguments and return object
@mcp.tool()
def convert_currency(amount: ____, from_currency: ____, to_currency: ____) -> ____:
    # Complete the docstring with the function arguments
    """
    Convert an amount from one currency to another using current exchange rates.

    Args:
        ____: The amount to convert
        ____: Source currency code (e.g., 'USD', 'EUR', 'GBP')
        ____: Target currency code (e.g., 'USD', 'EUR', 'GBP')

    Returns:
        A string with the conversion result and exchange rate
    """

    url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"

    response = requests.get(url)
    data = response.json()
    rate = data['rates'].get(to_currency)

    if rate is None:
        return f"Could not find exchange rate for {from_currency} to {to_currency}"

    converted_amount = amount * rate
    return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency} (Rate: {rate})"

print(convert_currency(amount=100, from_currency="EUR", to_currency="USD"))
コードを編集して実行