Aggiungere docstring e type hint
È il momento di rendere il tuo strumento convert_currency() più facile da usare per gli LLM tramite docstring e type hint. Senza questi, l'LLM potrebbe non riuscire a scegliere in modo efficace quale strumento chiamare, oppure potrebbe passare valori errati agli argomenti—entrambi casi che portano a prestazioni dell'applicazione inaffidabili!
Un server MCP è già stato istanziato usando FastMCP e assegnato a mcp.
Questo esercizio fa parte del corso
Introduzione al Model Context Protocol (MCP)
Istruzioni dell'esercizio
- Aggiungi i tipi appropriati agli argomenti della funzione e all'oggetto restituito.
- Completa la docstring in modo che i tre argomenti della funzione corrispondano alle loro definizioni.
esercizio interattivo pratico
Prova questo esercizio completando questo codice di esempio.
# 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"))