Přidání docstringů a typových anotací
Teď svůj nástroj convert_currency() lépe připravíš pro LLM pomocí docstringů a typových anotací. Bez nich nemusí LLM správně poznat, který nástroj použít, nebo může předávat argumentům nesprávné hodnoty — obojí vede k nespolehlivému chování aplikace!
MCP server byl již vytvořen pomocí FastMCP a přiřazen do proměnné mcp.
Toto cvičení je součástí kurzu
Introduction to Model Context Protocol (MCP)
Pokyny k cvičení
- Přidej vhodné typy k argumentům funkce i k návratové hodnotě.
- Dopiš docstring tak, aby odpovídal třem argumentům funkce a jejich definicím.
Interaktivní cvičení na vyzkoušení si v praxi
Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.
# 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"))