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

การใช้งาน Tool ของ LLM ใน MCP Server

คุณได้สร้าง MCP server ที่มี tool สำหรับแปลงสกุลเงินโดยใช้อัตราแลกเปลี่ยนแบบเรียลไทม์ การนำ MCP server นี้ไปเชื่อมต่อกับ LLM จะช่วยให้ LLM ตอบคำถามเกี่ยวกับสกุลเงินและอัตราแลกเปลี่ยนได้อย่างแม่นยำ—ซึ่งโดยปกติแล้ว LLM ไม่สามารถทำได้

โค้ดส่วนใหญ่ถูกเตรียมไว้ให้แล้ว เนื่องจากเป้าหมายหลักคือการทำความเข้าใจกระบวนการทำงาน (workflow) มากกว่าการท่องจำ syntax

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

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

ดูคอร์ส

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

  • ส่ง user query (user_query) และรายการ tool ที่จัดรูปแบบแล้ว (anthropic_tools) ไปยัง Claude
  • เรียกใช้ MCP tool ที่ LLM เลือก โดยใช้ชื่อและอาร์กิวเมนต์ที่ดึงมาจาก tool use block
  • ส่งผลลัพธ์ (result) กลับไปยัง Claude เพื่อรับคำตอบสุดท้าย

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

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

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

async def call_anthropic_llm(user_query: str):
    """Call Claude with MCP tools."""
    
    print(f"\nUser: {user_query}\n")

    mcp_tools = await get_tools_from_mcp()
    
    anthropic_tools = []
    for tool in mcp_tools:
        anthropic_tool = {
            "name": tool.name,
            "description": tool.description or "",
            "input_schema": tool.inputSchema,
        }
        anthropic_tools.append(anthropic_tool)
    
    # Send the user query and formatted tools to the LLM
    client = AsyncAnthropic(api_key="")

    response = await client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=____,
        tools=____,
    )

    if response.stop_reason == "tool_use":
        tool_use = next(block for block in response.content if block.type == "tool_use")
        name = tool_use.name
        args = tool_use.input

        print(f"Model decided to call: {name}")
        print(f"Arguments: {args}\n")

        # Call the MCP tool
        result = await call_mcp_tool(____, ____)

        # Send the result back to Claude for the final response
        followup = await client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=1024,
            messages=[
                {"role": "user", "content": user_query},
                {"role": "assistant", "content": response.content},
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": tool_use.id,
                            "content": ____,
                        }
                    ],
                },
            ],
            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)
        else:
            print("No follow-up message from model.")

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


if __name__ == "__main__":
    asyncio.run(call_anthropic_llm("How much is 250 US dollars in euros?"))
แก้ไขและรันโค้ด