การดึง Prompt จาก Client
ลองดึง prompt เฉพาะจาก currency server โดยรับ input จากผู้ใช้ เพื่อรวม template เข้ากับคำขอของผู้ใช้ นี่คือสิ่งที่จะส่งให้ LLM ก่อนที่มันจะตัดสินใจเรียกใช้ conversion tool
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- หลังจาก initialize session แล้ว ให้เรียกเมธอดสำหรับดึง prompt ตามชื่อ โดยส่งชื่อ prompt และ dict ของ
argumentsที่มี input ของผู้ใช้ - ดึงและแสดงผล text content ของข้อความแรกในผลลัพธ์ของ prompt
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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?"))