เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

สร้างข้อความและเรียกใช้ LLM

เมื่อสร้างฟังก์ชันช่วย get_context_from_mcp(user_query) สำหรับดึง resource text และ prompt text เรียบร้อยแล้ว ถึงเวลาส่งข้อมูลเหล่านั้นไปยัง LLM!

เซิร์ฟเวอร์สกุลเงิน, get_context_from_mcp(), get_tools_from_mcp(), call_mcp_tool() และ Claude client ถูกตั้งค่าไว้ในเบื้องหลังแล้ว สิ่งที่ต้องทำคือเติมฟังก์ชันที่สร้าง prompt เรียกโมเดล และจัดการกับทั้งกรณีที่ได้รับข้อความตอบกลับโดยตรงและกรณีที่มีการเรียกใช้ tool นอกจากนี้ยังมีตัวอย่าง input ของผู้ใช้ทั้งแบบคลุมเครือและแบบชัดเจน เพื่อทดสอบว่า MCP prompt ที่สร้างไว้ให้ผลลัพธ์ต่างกันหรือไม่

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Model Context Protocol (MCP) เบื้องต้น

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ใน บรรทัดที่ 37 ให้สร้าง full_prompt โดยต่อ prompt_text, สตริง "\n\nSupported currencies:\n" และ resource_text เข้าด้วยกัน
  • ใน บรรทัดที่ 47 ให้ส่ง full_prompt (ในฐานะเนื้อหาของข้อความ user) และรายการ anthropic_tools ไปยังโมเดล
  • ใน บรรทัดที่ 52-55 ถ้า stop_reason ของ response เป็น "end_turn" ให้ return str(text)
  • ใน บรรทัดที่ 58-60 ถ้า stop_reason ของ response เป็น "tool_use" ให้ส่ง .name และ .input ของ tool use block ไปยัง call_mcp_tool()

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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

async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
    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()
            resource_result = await session.read_resource("file://currencies.txt")
            resource_text = resource_result.contents[0].text
            prompt_result = await session.get_prompt("convert_currency_prompt",
                arguments={"currency_request": user_query})
            prompt_text = prompt_result.messages[0].content.text
            return resource_text, prompt_text

async def get_tools_from_mcp():
    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()
            response = await session.list_tools()
            return response.tools

async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
    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()
            result = await session.call_tool(tool_name, arguments)
            return str(result.content[0].text)

async def call_llm_with_context(user_query: str):
    """Call the LLM with resource and prompt context from MCP."""
    resource_text, prompt_text = await get_context_from_mcp(user_query)

    # Combine the resource and prompt text
    full_prompt = ____ + "\n\nSupported currencies:\n" + ____

    client = AsyncAnthropic(api_key="")
    mcp_tools = await get_tools_from_mcp()
    anthropic_tools = [{"name": t.name, "description": t.description or "", "input_schema": t.inputSchema} for t in mcp_tools]

    # Send full_prompt (as a user message) and the tools list to the model
    response = await client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=[{"role": "user", "content": ____}],
        tools=anthropic_tools,
    )

    # Return the text response
    if response.stop_reason == "____":
        text = next((block.text for block in response.content if block.type == "text"), "")
        print(f"\nAssistant: {text}")
        return str(____)

    # Call the tool requested in the LLM's tool use
    if response.stop_reason == "____":
        tool_use = next(block for block in response.content if block.type == "tool_use")
        result = await call_mcp_tool(____.name, ____)
        followup = await client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=1024,
            messages=[
                {"role": "user", "content": full_prompt},
                {"role": "assistant", "content": response.content},
                {"role": "user", "content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": result}]},
            ],
            tools=anthropic_tools,
        )
        final_text = next((block.text for block in followup.content if block.type == "text"), None)
        if final_text:
            print(f"\nAssistant: {final_text}")
            return str(final_text)

print("=== Ambiguous request (prompt asks for clarification) ===")
asyncio.run(call_llm_with_context("Convert some euros to dollars"))
print("\n=== Unambiguous request (model calls tool) ===")
asyncio.run(call_llm_with_context("How much is 50 GBP in euros?"))
แก้ไขและรันโค้ด