从客户端检索提示
现在请结合用户输入,从 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?"))