เพิ่มความแข็งแกร่งให้กับการเรียกใช้ API Tool
ในการใช้งานจริง เครื่องมือ convert_currency() ของเซิร์ฟเวอร์สกุลเงินไม่ควรค้างอยู่หาก API อัตราแลกเปลี่ยนตอบสนองช้าหรือเข้าไม่ได้ เพื่อรับมือกับปัญหานี้ จะได้นำ timeout มาใช้กับ request และตรวจสอบให้แน่ใจว่าหากเกิดข้อผิดพลาด ระบบจะส่งข้อความแจ้งเตือนที่กระชับและชัดเจนกลับไปยังผู้ใช้ แทนที่จะโยน exception ดิบๆ
MCP server ได้ถูกสร้างและเก็บไว้ในตัวแปร mcp เรียบร้อยแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- เพิ่ม logic แบบ try-except เพื่อพยายามส่ง API request และจัดการข้อผิดพลาดอย่างราบรื่นด้วยการดักจับ exception หากเกิดข้อผิดพลาดขึ้น
- เพิ่ม timeout 10 วินาทีให้กับการเรียก
requests.get()เพื่อป้องกันไม่ให้ request ค้างอยู่โดยไม่มีกำหนด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
@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"))