Nhập môn Tool Use — Cho Claude "bàn tay"

5 — Tool UseTrung cấp20 phút

Claude được train trên data đến knowledge cutoff (ví dụ 1/2026). Nếu user hỏi: - "Giá Bitcoin hôm nay?" → Claude không biết (data cutoff) - "Weather Hanoi ngay bây giờ?" → không biết - "Đơn hàng của tôi status?" → không biết (data riêng của bạn)

Bạn sẽ học được
  • Giải thích tool use giải quyết vấn đề gì (Claude không biết real-time info)
  • Mô tả 4 bước flow tool use: request → tool request → data retrieval → final response
  • Nhận diện use case phù hợp tool use
  • Hiểu tại sao tool use là cửa ngõ vào agents

Tool Use là gì?

Tool use = structured way cho Claude:

Nó không là Claude tự gọi API. Claude request bạn gọi. Bạn thực thi. Bạn gửi kết quả về. Claude dùng.

  • Nhận diện mình cần thông tin bên ngoài
  • Request function name + parameters cụ thể
  • Chờ bạn thực thi function
  • Dùng kết quả để answer user

4-step flow

┌───────────────────────────────────────────────────┐
│                                                   │
│  1. User asks                                     │
│     "Weather in SF?"                              │
│                     │                             │
│                     ▼                             │
│  2. Claude requests tool                          │
│     "Call get_weather(location='SF')"             │
│                     │                             │
│                     ▼                             │
│  3. Your server runs function                     │
│     weather_api.get("SF") → "72°F, sunny"         │
│                     │                             │
│                     ▼                             │
│  4. You send result back to Claude                │
│     "72°F, sunny" → Claude                        │
│                     │                             │
│                     ▼                             │
│  5. Claude responds to user                       │
│     "It's 72°F and sunny in SF."                  │
│                                                   │
└───────────────────────────────────────────────────┘

Weather example

Không có tool use

Useless.

Có tool use

User: Weather SF?
Claude: I don't have access to real-time weather.

Có tool use

Chi tiết từng bước ở bài 6.31-6.34.

# Step 1: User message với tool schema
messages = [{"role": "user", "content": "Weather SF?"}]

response = client.messages.create(
    model=model,
    max_tokens=1000,
    messages=messages,
    tools=[get_weather_schema],  # ← Cho Claude biết có tool
)

# Step 2: Claude requests tool
# response.content có:
# - TextBlock: "I'll check the weather for you"
# - ToolUseBlock: {name: "get_weather", input: {"location": "SF"}}

# Step 3: Bạn chạy function
if response.stop_reason == "tool_use":
    tool_call = response.content[-1]  # last block thường là ToolUse
    result = get_weather(**tool_call.input)  # "72°F, sunny"

# Step 4: Gửi result back
messages.append({"role": "assistant", "content": response.content})
messages.append({
    "role": "user",
    "content": [{
        "type": "tool_result",
        "tool_use_id": tool_call.id,
        "content": result
    }]
})

# Step 5: Final response
final = client.messages.create(
    model=model, max_tokens=1000, messages=messages, tools=[get_weather_schema]
)
print(final.content[0].text)
# "It's currently 72°F and sunny in San Francisco."

Use cases tool use

Real-time data

Your own data

Actions

Computation

API integrations

  • Weather
  • Stock prices
  • Sports scores
  • Current events
  • User's order status
  • Employee records
  • Inventory
  • CRM info
  • Send email
  • Create calendar event
  • Book appointment
  • Update database
  • Math complex (Claude không giỏi số học phức tạp)
  • Run SQL query
  • Execute code
  • Calculate distance / currency convert
  • Google Maps
  • OpenWeather
  • Salesforce
  • GitHub

Tool use vs function calling (naming)

Anthropic gọi "tool use". OpenAI gọi "function calling". Cả hai same concept.

Gần đây convention shift: tool = function Claude can call. Tool use covers:

  • Your custom tools (function bạn viết)
  • Built-in tools (Anthropic provides: web search, code execution, text editor — covered in Module 6)
  • MCP tools (tools qua MCP servers — covered in Module 8)

Tool use — cửa ngõ vào agents

Agent = Claude + many tools + multi-turn loop.

Bài 6.30-6.34 dạy 1 tool 1 turn. Bài 6.35-6.37 dạy multi-tool multi-turn. Đó chính là agent.

Nắm tool use = nắm agent. Không có cách khác tắt.

┌──────────────────────────────────────┐
│                                      │
│    AGENT                             │
│    ┌─────────┐                       │
│    │ Claude  │  ←─ multi-turn loop   │
│    └────┬────┘                       │
│         │                            │
│    ┌────┴─────┐                      │
│    │  Tools   │                      │
│    ├──────────┤                      │
│    │ tool_1   │                      │
│    │ tool_2   │                      │
│    │ tool_3   │                      │
│    │ ...      │                      │
│    └──────────┘                      │
│                                      │
└──────────────────────────────────────┘

Khi nào KHÔNG cần tool use?

Nếu task:

→ Đừng add tool use. Tốn complexity không cần.

Quy tắc: Add tool chỉ khi Claude thực sự cần — không "just in case".

  • Pure language (translate, summarize, rewrite)
  • Không cần fresh data
  • Không cần compute exact numbers
  • Không cần actions

Ví dụ thực chiến: Chatbot customer support

Task: Trả lời "Đơn hàng của tôi status?"

Không có tool:

Có tool get_order_status:

User: Order #12345 status?
Claude: I don't have access to your order info.

Task: Trả lời "Đơn hàng của tôi status?"

tools = [get_order_status_schema]
# schema định nghĩa: input=order_id, returns status string

# User hỏi → Claude request tool với order_id=12345
# Your server: query DB → "Shipped, arriving tomorrow"
# Gửi result → Claude final response

Ví dụ thực chiến: Chatbot customer support (tiếp)

UX transform. Customer hạnh phúc. Support ticket giảm 50%.

Claude: Your order #12345 has shipped and will arrive tomorrow. 
       Tracking: TN-...

Case studies

🎧 Support — 3 tools

Chatbot resolve 70% case tự động.

💻 Developer assistant — 5 tools

Chính là Claude Code architecture.

📊 Data analyst — 4 tools

Data analyst tự nhiên language → SQL → visualization.

💰 Finance — 3 tools

Research tool real-time.

  • get_order_status(order_id)
  • create_refund_request(order_id, reason)
  • escalate_to_human(ticket_id)
  • read_file(path)
  • edit_file(path, old, new)
  • run_bash(command)
  • search_code(pattern)
  • run_tests()
  • run_sql_query(query)
  • get_schema(table_name)
  • create_chart(data, chart_type)
  • export_to_csv(data, filename)
  • get_stock_price(symbol)
  • calculate_portfolio_return(portfolio)
  • get_market_news(topic)

Các khái niệm cần nhớ

TermDefinition
ToolFunction bạn expose cho Claude gọi
Tool schemaJSON định nghĩa tool (name, description, params)
Tool use blockBlock trong response khi Claude request tool
Tool resultKết quả bạn gửi Claude sau khi chạy tool
Stop reason "tool_use"Claude dừng vì muốn tool (không end_turn)

Anti-patterns

❌ Add tool "just in case"

5 tool, Claude chỉ dùng 1. Tool schema tốn token mỗi request.

Fix: Add tool based on user need, remove unused.

❌ Tool làm nhiều thứ

do_everything(action, params) → Claude không biết khi nào call.

Fix: 1 tool = 1 concern. get_weather, get_stock_price riêng.

❌ Tool description vague

"name: 'tool', description: 'does stuff'"

Fix: Detail 3-4 câu (bài 6.31).

❌ Không validate input

Tool crash khi Claude pass param sai → lỗi cho user.

Fix: Validate + raise meaningful error.

Áp dụng ngay

Bài tập 1: Identify tools cho app của bạn (10 phút)

Bài tập 2: Sketch flow (10 phút)

Cho 1 user query, vẽ 5-step flow:

  • User asks: ___
  • Claude requests tool: ___
  • Your code runs: ___
  • Result sent: ___
  • Claude final answer: ___
## Tools for my app

Tools list:
1. [name]: [what it does] — [when Claude should call]
2. ...

KHÔNG cần:
- [task1] (Claude làm tự)
- ...

Tóm tắt

🎯 Tool use cho Claude "bàn tay" — gọi function bên ngoài.

🎯 4-step flow: Ask → Tool request → Execute → Final response.

🎯 3 loại tool: custom (bạn viết), built-in (Anthropic), MCP (cộng đồng).

🎯 Tool use = foundation của agents. Không nắm tool use = không xây được agent.

🎯 Add tool khi Claude THỰC SỰ cần. "Just in case" = tech debt.

Nội dung này có hữu ích không?