S-07 · TRACK 03 · PATTERNS

Tool Use

Từ "nói" sang "làm". Function calling, ReAct loop, code execution — pattern quan trọng nhất để agent tác động lên thế giới thật. Chapter 5 sách Gulli (20 trang, dày nhất Part 1).

Buổi 7 — Chúng ta sẽ đi qua gì?
🚩

01 · Vì sao cần tool?

Giới hạn của LLM thuần — knowledge cutoff, no action

🔧

02 · Cơ chế function calling

Schema, tool_call, tool_result, feedback loop

🔄

03 · Biến thể

Native · ReAct · Code exec · MCP · Skills

💻

04 · Thực chiến

Code Python, framework compare, sandbox

🎯

05 · Takeaways

5 điểm nhớ + homework

01

Vì sao Tool Use
là bước ngoặt của LLM?

LLM thuần — những giới hạn cốt lõi

LLM một mình

Knowledge cutoff — không biết giá cổ phiếu hôm nay.

Không đọc file riêng — không truy hồi DB, không xem log.

Không tác động — không gửi email, không tạo issue, không chuyển tiền.

Không tính toán chính xác — math phức tạp hay sai lệch.

Không có state — không nhớ giữa turn nếu không có tool memory.

LLM + Tools

Truy realtime — API weather, price, stock.

Đọc/ghi file — Read, Write, Grep, filesystem.

Gọi service — send_email, create_ticket, run_query.

Code execution — Python sandbox tính toán chính xác.

Kết nối agent khác — qua MCP hoặc A2A (S-10).

Tool Use là bước biến LLM từ text generator thành agent đúng nghĩa.

02

Cơ chế
Function calling & feedback loop

Tool = hàm với schema — model chọn & gọi
Tool = một hàm được mô tả bằng JSON schema (name, description, parameters). Model đọc schema, quyết định gọi, sinh tool_call với arguments. Framework thực thi ⇒ trả tool_result về context ⇒ model tiếp tục.
tool_schema.json
"name": "get_weather",
"description": "Get current weather for a city. Use only when user asks about weather.",
"input_schema": {
  "type": "object",
  "properties": {
    "city": {"type": "string", "description": "City name in English"},
    "unit": {"type": "string", "enum": ["C", "F"]}
  },
  "required": ["city"]
}

Description CHÍNH LÀ prompt cho router nội bộ — viết mô tả rõ ràng quan trọng hơn viết code hàm.

Flow 5 bước — ReAct loop
Bước 1

Reason

Model nghĩ: "cần tool nào?"

Bước 2

Tool Call

Sinh JSON call với args.

Bước 3

Execute

Framework thực thi hàm.

Bước 4

Observe

Tool_result ⇒ context.

Bước 5

Continue

Model dùng kết quả ⇒ trả lời hoặc tool tiếp.

ReAct = Reason + Act (Yao et al., 2022). Loop này chạy nhiều turn cho đến khi model quyết định trả lời cuối.

03

5 biến thể
của Tool Use

Từ native call đến Skill package
🔧

Native

OpenAI tools, Claude tool_use, Gemini function_declarations. Chuẩn API provider.

🔄

ReAct

Loop text-based: Thought/Action/Observation. Dùng khi model không có native tool.

💻

Code Exec

Python/JS sandbox. Anthropic Code Execution, OpenAI Code Interpreter. Math & data.

🔌

MCP

Universal protocol. Bất kỳ MCP server nào cũng plug & play. Chi tiết S-10.

🎯

Skills

Claude Skill: package (prompt + tool + resource) load theo demand. Tiết kiệm context.

Xu hướng 2025: dịch từ Native tool per appMCP server chia sẻSkill catalogs theo domain.

04

Thực chiến
Code · Framework · Sandbox

Code — Native tool_use với Claude
weather_agent.py
import anthropic

tools = [{
    "name": "get_weather",
    "description": "Get current weather for a city.",
    "input_schema": {"type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]}
}]

def run_tool(name, args):
    if name == "get_weather":
        return weather_api.get(args["city"])

messages = [{"role": "user", "content": "Thời tiết Hà Nội hôm nay?"}]

while True:
    resp = client.messages.create(model="claude-sonnet-4-6", tools=tools, messages=messages)
    if resp.stop_reason == "end_turn": break
    for block in resp.content:
        if block.type == "tool_use":
            result = run_tool(block.name, block.input)
            messages.append({"role": "assistant", "content": resp.content})
            messages.append({"role": "user",
                "content": [{"type": "tool_result",
                    "tool_use_id": block.id, "content": str(result)}]})
So sánh cách khai báo tool
Provider/Framework Cách khai báo Parallel tools Code exec
OpenAI tools=[{type:function}] ✅ multi tool_calls Code Interpreter (Assistants)
Anthropic Claude tools=[{input_schema}] ✅ parallel tool_use Code Execution beta
Google Gemini function_declarations ✅ automatic function calling Code Execution native
LangChain @tool decorator Runnable parallel PythonREPLTool
Claude Code Native Bash/Read/Edit/Grep + Skills + MCP ✅ nhiều tool/turn Bash sandbox
6 anti-pattern — sai lầm phổ biến
🔥

Quá nhiều tool

>50 tool trong prompt ⇒ model confuse, chọn sai. Chia theo domain / dùng Skill.

💬

Description mơ hồ

"Do stuff" ⇒ model không biết khi nào gọi. Description = prompt cho router.

Không idempotent

Retry ⇒ gọi lại ⇒ gửi email 2 lần. Thêm request_id + idempotency key.

🚫

Không rate limit

Loop lỗi ⇒ đấm API 1000 req/s. Circuit breaker + budget cap.

🔐

Không sandbox code

Cho exec() tuỳ ý ⇒ RCE. Dùng E2B, Firecracker VM, gVisor.

📋

Không log tool_call

Không biết agent làm gì ⇒ audit fail, debug bó tay.

Case VN 🇳🇻 — 6 lĩnh vực Tool Use thực chiến
🌐

1. Truy hồi realtime

Agent thời tiết gọi API theo địa điểm ⇒ format phản hồi thân thiện.

Tool: get_weather, search web.

🛒

2. E-commerce · CRM

Kiểm tồn kho, trạng thái đơn hàng, xử lý thanh toán qua API.

Tool: check_stock, get_order.

💸

3. Tài chính · phân tích

Lấy giá cổ phiếu → gọi calculator tính lãi. LLM tự yếu math.

Tool: quote, calculator.

4. Liên lạc

Trợ lý cá nhân gửi email/Slack/Zalo với nội dung trích từ user.

Tool: send_email, send_slack.

💻

5. Thực thi code

Agent lập trình chạy Python sandbox → phân tích output.

Tool: python_exec, Bash.

🔌

6. IoT · điều khiển

Nhà thông minh: tắt đèn, bật điều hoà qua API smart home.

Tool: set_device_state.

Ranh giới: function calling = hàm code định trước. Tool calling rộng hơn — có thể là API, DB query, hoặc chỉ dẫn gửi tới agent chuyên biệt khác (bắc cầu sang A2A ở S-10).

Nguồn: Cẩm nang thực hành xây dựng HTTM (VN Gulli Ch.5) · local hoá ví dụ.

Claude Code toolkit — anatomy của agent kỹ thuật

🛠 Native tools (built-in)

  • Read / Write / Edit — filesystem.
  • Bash — shell sandbox.
  • Grep / Glob — search code.
  • WebFetch / WebSearch.
  • TaskCreate / TaskUpdate — plan mode (S-08).
  • Agent — spawn subagent (A2A trong nhà).

🔌 Extension mechanisms

  • Skills — gói tool + prompt + resource, load theo demand (S-10).
  • MCP servers — universal protocol (S-10).
  • Hooks — trigger custom trước/sau tool call.
  • Slash commands — user-invokable skill.
  • Subagent — role chuyên biệt (Explore, Plan…).

Đây là tham chiếu chuẩn để hiểu tool ecosystem. Khi build agent riêng, câu hỏi luôn là: tool nào native, tool nào Skill, tool nào MCP?

Tham chiếu: Khám phá Claude Code — Không gian thiết kế Hệ thống Tác tử (VN).

CLI thực chiến — Tool Use với 3 tool

🤖 Claude Code

# Native tool có sẵn
# Read, Write, Edit, Bash
# Grep, Glob, WebFetch...

# Xem allowlist tool
claude
# /help → xem tool có sẵn

# Custom tool qua Skill
mkdir .claude/skills/weather
# SKILL.md + script

# Config permission tool
# ~/.claude/settings.json
"permissions": {
  "allow": ["Bash(npm:*)"]
}

# One-shot chạy tool
claude "Grep TODO" \
  --permission-mode acceptEdits

⚡ Cursor

# Built-in tools trong Agent
# Read/Edit/Run/Search

cursor .
# Cmd+I → Agent mode
# @file @folder @code
# @web @docs @git

# Custom tool qua MCP
# ~/.cursor/mcp.json
{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["server.js"]
    }
  }
}

# Terminal tool: run cmd
# Cursor tự đề xuất
# npm test → approve/deny

💎 Gemini CLI

# Built-in tools
# --tools code_execution
# --tools google_search

gemini --tools \
  code_execution \
  -p "Tính 15! bằng Python"

# Sandbox tool exec
gemini --sandbox \
  -p "Chạy script test.py"

# YOLO mode (auto-approve)
# CẨN THẬN production
gemini --yolo -p "..."

# File attachment
gemini -p "Review" \
  -a src/main.py

Cẩn thận: --yolo (Gemini) và --dangerously-skip-permissions (Claude) bỏ mọi confirm — chỉ dùng khi test isolated.
Windows Bash: Claude Code chạy trên Git Bash / WSL2 tốt nhất. Gemini CLI chạy PowerShell OK. Cursor có Terminal tích hợp.

05

Takeaways
& homework

5 điều nhớ
1

Tool Use = biến LLM thành agent thực thụ. Không có tool = chỉ là text generator.

2

Description quan trọng hơn code. Nó là prompt cho router nội bộ trong LLM.

3

ReAct loop = Reason → Act → Observe → Continue cho đến khi end_turn.

4

Tool side-effect luôn idempotent + rate-limited + sandboxed. Đặc biệt là code exec.

5

Xu hướng: Native ⇒ MCP ⇒ Skills để tool tái sử dụng liên app.

Bài tập & chuẩn bị buổi 8
📝

Tự kiểm tra

  • • Liệt kê 5 tool app bạn có thể expose cho agent.
  • • Với mỗi tool, viết description <100 từ, chỉ khi nào dùng.
  • • Tool nào cần idempotency key? Rate limit?
📚

Đọc trước

  • • A. Gulli — Ch.5 Tool Use (20 trang).
  • • Yao et al. — ReAct: Synergizing Reasoning and Acting.
  • • Anthropic docs — Tool use.
🔗

Tài liệu VN

  • Khám phá Claude Code.
  • Cẩm nang Claude & N8N toàn diện.
  • Hướng dẫn xây dựng Claude Skill chuyên nghiệp.
Hết buổi 7

Buổi 8 — Planning & Reflection
Từ "làm" sang "lên kế hoạch & tự đánh giá". Ch.4 + Ch.6 sách Gulli.