開始使用免費開始

從用戶端擷取提示詞

現在,使用使用者輸入,從 currency 伺服器擷取特定的提示詞,讓範本與使用者的請求合併。這會是在 LLM 決定是否呼叫換匯工具之前要傳入的內容。

本練習屬於課程

Model Context Protocol(MCP)入門

檢視課程

練習說明

  • 初始化工作階段後,呼叫依名稱取得提示詞的方法,並傳入提示詞名稱與包含使用者輸入的 arguments 字典。
  • 萃取並印出提示詞結果中第一則訊息文字內容。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def read_prompt(user_input: str = "How much is 50 GBP in euros?", prompt_name: str = "convert_currency_prompt") -> str:
    """Retrieve a prompt from the MCP server with user input."""
    params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

            # Retrieve the prompt with the user's input
            prompt = await session.____(prompt_name, arguments={"currency_request": user_input})

            # Print the full prompt text (template + user request)
            text = prompt.____[0].____.____
            print(text)
            return text

asyncio.run(read_prompt(user_input="How much is 50 GBP in euros?"))
編輯並執行程式碼