शुरू करेंमुफ़्त में शुरू करें

API टूल कॉल्स को मज़बूत बनाना

प्रोडक्शन में, करेंसी सर्वर का convert_currency() टूल तब भी हैंग नहीं होना चाहिए जब एक्सचेंज-रेट API धीमी हो या पहुँच से बाहर हो. इसे कम करने के लिए, आप रिक्वेस्ट में timeout जोड़ेंगे और सुनिश्चित करेंगे कि किसी भी विफलता पर कच्चे exception के बजाय उपयोगकर्ता को छोटा, स्पष्ट एरर संदेश लौटे.

एक MCP सर्वर पहले से इंस्टैंशिएट किया जा चुका है और वैरिएबल mcp में स्टोर है.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Model Context Protocol (MCP) परिचय

पाठ्यक्रम देखें

अभ्यास निर्देश

  • ऐसा try-except लॉजिक लागू करें जो API रिक्वेस्ट करने की कोशिश करे, और exception को पकड़कर एरर आने पर शालीनता से फेल हो जाए.
  • requests.get() कॉल में 10 सेकंड का timeout जोड़ें ताकि रिक्वेस्ट अनिश्चितकाल तक हैंग न रहे.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

@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"))
कोड संपादित करें और चलाएँ