Aan de slagBegin gratis

Docstrings en type hints toevoegen

Tijd om je convert_currency()-tool makkelijker te maken voor LLM's met behulp van docstrings en type hints. Zonder deze informatie kan het LLM mogelijk niet goed kiezen welke tool het moet aanroepen, of geeft het waarden verkeerd door aan de argumenten—allebei leiden ze tot onbetrouwbare app-prestaties!

Er is al een MCP-server geïnstantieerd met FastMCP en toegewezen aan mcp.

Deze oefening maakt deel uit van de cursus

Introductie tot Model Context Protocol (MCP)

Bekijk cursus

Oefeninstructies

  • Voeg passende types toe aan de functieargumenten en het geretourneerde object.
  • Vul de docstring aan zodat de drie functieargumenten overeenkomen met hun definities.

Interactieve oefening met praktijkervaring

Probeer deze oefening door deze voorbeeldcode aan te vullen.

# 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"))
Code bewerken en uitvoeren