API-hulpmiddel-aanroepen robuust maken
In productie mag de convert_currency()-tool van de currency-server niet blijven hangen als de wisselkoers-API traag is of niet bereikbaar. Om dit te voorkomen implementeer je een timeout voor het verzoek en zorg je dat elke mislukking een korte, duidelijke foutmelding aan de gebruiker teruggeeft in plaats van een ruwe exception.
Er is al een MCP-server geïnstantieerd en opgeslagen in de variabele mcp.
Deze oefening maakt deel uit van de cursus
Introductie tot Model Context Protocol (MCP)
Oefeninstructies
- Implementeer try-except-logica die de API-aanvraag probeert uit te voeren en netjes faalt door de uitzondering op te vangen als er een fout optreedt.
- Voeg een timeout van 10 seconden toe aan de aanroep
requests.get()zodat het verzoek niet oneindig blijft hangen.
Interactieve oefening met praktijkervaring
Probeer deze oefening door deze voorbeeldcode aan te vullen.
@mcp.tool()
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""
Convert an amount from one currency to another using current exchange rates.
Args:
amount: The amount to convert
from_currency: Source currency code (e.g., 'USD', 'EUR', 'GBP')
to_currency: 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}"
# Implement try-except to gracefully handle errors
____:
# Add a 10-second timeout so the request does not hang
r = requests.get(url, ____=____)
r.raise_for_status()
data = r.json()
rate = data["rates"].get(to_currency)
if rate is None:
return f"Could not find exchange rate for {from_currency} to {to_currency}"
return f"{amount} {from_currency} = {amount * rate:.2f} {to_currency} (Rate: {rate})"
____ requests.exceptions.RequestException as e:
return f"Error converting currency: {e}"
print(convert_currency(10, "USD", "EUR"))