Lộ trình học›Claude API›Building with the Claude API Mở bản đồ

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

Bài viếtTrung cấp20 phút đọc

Claude được train trên data đến knowledge cutoff (ví dụ 1/2026). Nếu user hỏi:

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

Mở đầu: Claude chỉ là "bộ não đọc sách"

  • "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)

Không có tool use, Claude phải nói:

Xin lỗi, tôi không có thông tin cập nhật...

UX tệ. Và đây không phải là giới hạn không thể vượt — chỉ cần cho Claude "cánh tay" để gọi function lấy data real-time.

Tool Use là gì?

Tool use = structured way cho Claude:

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

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.

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

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

Useless.

Có tool use

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
)


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"

messages.append({"role": "assistant", "content": response.content})
messages.append({
    "role": "user",
    "content": [{
        "type": "tool_result",
        "tool_use_id": tool_call.id,
        "content": result
    }]
})

final = client.messages.create(
    model=model, max_tokens=1000, messages=messages, tools=[get_weather_schema]
)
print(final.content[0].text)

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

Use cases tool use

Real-time data

  • Weather
  • Stock prices
  • Sports scores
  • Current events

Your own data

  • User's order status
  • Employee records
  • Inventory
  • CRM info

Actions

  • Send email
  • Create calendar event
  • Book appointment
  • Update database

Computation

  • Math complex (Claude không giỏi số học phức tạp)
  • Run SQL query
  • Execute code
  • Calculate distance / currency convert

API integrations

  • 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.

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

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.

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

Nếu task:

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

→ Đừ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".

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:

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

Có tool get_order_status:

tools = [get_order_status_schema]
Claude: Your order #12345 has shipped and will arrive tomorrow. 
       Tracking: TN-...

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

Case studies

Support — 3 tools

  • get_order_status(order_id)
  • create_refund_request(order_id, reason)
  • escalate_to_human(ticket_id)

Chatbot resolve 70% case tự động.

Developer assistant — 5 tools

  • read_file(path)
  • edit_file(path, old, new)
  • run_bash(command)
  • search_code(pattern)
  • run_tests()

Chính là Claude Code architecture.

Data analyst — 4 tools

  • run_sql_query(query)
  • get_schema(table_name)
  • create_chart(data, chart_type)
  • export_to_csv(data, filename)

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

Finance — 3 tools

  • get_stock_price(symbol)
  • calculate_portfolio_return(portfolio)
  • get_market_news(topic)

Research tool real-time.

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)

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ự)
  • ...

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

Cho 1 user query, vẽ 5-step flow:
1. User asks: ___
2. Claude requests tool: ___
3. Your code runs: ___
4. Result sent: ___
5. Claude final answer: ___

---

Tóm tắt bài học

Những điều cốt lõi
  • 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.
Kiểm tra nhanh1 câu hỏi · chọn đáp án để xem giải thích
    Bạn đã hoàn thành bài này chưa?Tiến độ lưu trên trình duyệt của bạn.