Lấy Prompt từ Client
Bây giờ hãy lấy một prompt cụ thể từ currency server với đầu vào của người dùng để kết hợp mẫu prompt và yêu cầu của người dùng. Đây là nội dung bạn sẽ truyền cho LLM trước khi nó quyết định có gọi công cụ chuyển đổi hay không.
Bài tập này là một phần của khóa học
Giới thiệu về Model Context Protocol (MCP)
Hướng dẫn bài tập
- Sau khi khởi tạo session, gọi phương thức để lấy prompt theo tên, truyền vào tên prompt và một dict
argumentschứa đầu vào của người dùng. - Trích xuất và in nội dung văn bản của thông điệp đầu tiên trong kết quả prompt.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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?"))