การเพิ่ม Docstring และ Type Hint
ถึงเวลาทำให้ฟังก์ชัน convert_currency() ของคุณใช้งานง่ายขึ้นสำหรับ LLM ผ่าน docstring และ type hint หากไม่มีสิ่งเหล่านี้ LLM อาจเลือกเรียกใช้ฟังก์ชันผิด หรือส่งค่าให้อาร์กิวเมนต์ไม่ถูกต้อง—ซึ่งทั้งสองกรณีส่งผลให้แอปพลิเคชันทำงานไม่น่าเชื่อถือ!
MCP server ถูกสร้างขึ้นแล้วโดยใช้ FastMCP และกำหนดให้กับตัวแปร mcp
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- เพิ่ม type ที่เหมาะสมให้กับอาร์กิวเมนต์ของฟังก์ชันและออบเจกต์ที่ return
- เติม docstring ให้ครบโดยระบุคำอธิบายของอาร์กิวเมนต์ทั้งสามตัวให้ตรงกัน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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"))