定義 MCP 伺服器的 Prompt
你正在為匯率換算的 MCP 伺服器新增一個可重用的提示,讓 LLM 知道如何處理換匯請求,以及在需要釐清時該怎麼詢問(例如缺少金額或幣別代碼)。這能降低使用者的提示負擔,並讓助理更可靠。
已經建立好一個 MCP 伺服器實例。請使用 @mcp.prompt() 裝飾器新增一個提示,並撰寫一個函式,回傳包含提示樣板且附加使用者請求的內容。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 使用
@mcp.prompt()裝飾一個函式,並將標題設為"Currency Conversion"。 - 定義一個接收
currency_request: str的函式,回傳一個包含提示樣板與使用者請求的字串。 - 以範例請求呼叫此提示函式,並印出結果以驗證可正常運作。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define a prompt for currency conversion
____
def ____(currency_request: str) -> str:
return f"""You are a currency conversion assistant.
Your task is to:
1. Extract the amount and source currency from the user's natural language input.
2. Identify the target currency.
3. Use the conversion tool to convert the amount.
Rules:
- If the amount or currencies are ambiguous or missing, ask the user for clarification.
- Use only supported currency codes (e.g., USD, EUR, GBP).
User's currency conversion request: {currency_request}"""
# Test the prompt function
print(____("100 USD to EUR"))