Parallel Tool Calls — Gọi nhiều tools đồng thời với Claude
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Khai thác tối đa công cụ AI: Về mặt API, Claude có thể trả về nhiều tooluse blocks trong một response: Response ly tuong voi parallel calls: content. Bí quyết nằm ở cách bạn cấu trúc yêu cầu — prompt càng rõ ràng, output càng sát nhu cầu thực tế.
- 2 Thành thật mà nói: Dù bạn truyền betas="interleaved-thinking-2025-05-14" hoặc system prompt yêu cầu parallel calls, Claude 3.7 Sonnet. Phương pháp này hiệu quả trong hầu hết trường hợp, nhưng bạn cần điều chỉnh cho phù hợp ngữ cảnh riêng.
- 3 Theo dữ liệu: import threading import json def getweathercity: """Goi weather API gia lap""" Trong thuc te, day la HTTP request den. Con số 75% minh chứng cho hiệu quả thực tế mà bạn có thể kỳ vọng khi triển khai.
- 4 Khai thác tối đa công cụ AI: import time Test khong dung batch def testsequential: start = time.time Gia su moi tool mat 500ms Sequential: 500ms +. Bí quyết nằm ở cách bạn cấu trúc yêu cầu — prompt càng rõ ràng, output càng sát nhu cầu thực tế.
- 5 Đừng bỏ qua rủi ro: Vấn đề Chi tiết Claude không luôn dùng batch Claude quyết định khi nào dùng batchtool — không guarantee. Hiểu rõ hạn chế giúp bạn tránh những sai lầm tốn kém mà nhiều người mắc phải khi mới bắt đầu.
Khi bạn có một câu hỏi cần nhiều pieces of information độc lập — thời tiết, giờ hiện tại, tỷ giá — thao tác hiệu quả nhất là gọi tất cả APIs cùng lúc. Claude có thể làm điều này bằng cách trả về nhiều tool_use blocks trong một response. Tuy nhiên, trong thực tế với Claude 3.7 Sonnet, điều này không phải lúc nào cũng xảy ra.
Bài này giải thích vấn đề và trình bày giải pháp thực tế: batch meta-tool.
Cách Parallel Tool Calls hoạt động (lý thuyết)
Về mặt API, Claude có thể trả về nhiều tool_use blocks trong một response:
# Response ly tuong voi parallel calls:
# content = [
# ToolUseBlock(id="tu_001", name="get_weather", input={"city": "Ha Noi"}),
# ToolUseBlock(id="tu_002", name="get_time", input={"timezone": "Asia/Ho_Chi_Minh"}),
# ToolUseBlock(id="tu_003", name="get_exchange_rate", input={"from": "USD", "to": "VND"})
# ]
# Neu dieu nay xay ra, ban gui tat ca results cung luc:
tool_results = [
{"type": "tool_result", "tool_use_id": "tu_001", "content": "28 do C, co may"},
{"type": "tool_result", "tool_use_id": "tu_002", "content": "09:45 AM"},
{"type": "tool_result", "tool_use_id": "tu_003", "content": "25,450 VND/USD"},
]
Khi nhận được tất cả results cùng một lượt, client có thể execute chúng song song — giảm latency từ N*T xuống còn T (với T là thời gian mỗi API call).
Vấn đề thực tế: Claude 3.7 Sonnet không luôn parallel
Dù bạn truyền betas=["interleaved-thinking-2025-05-14"] hoặc system prompt yêu cầu parallel calls, Claude 3.7 Sonnet thường chọn gọi tools tuần tự — từng tool một, chờ kết quả rồi mới gọi tool tiếp theo.
import anthropic
client = anthropic.Anthropic()
tools = [
{
"name": "get_weather",
"description": "Lay thong tin thoi tiet hien tai cua mot thanh pho",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "Ten thanh pho"}
},
"required": ["city"]
}
},
{
"name": "get_time",
"description": "Lay gio hien tai theo timezone",
"input_schema": {
"type": "object",
"properties": {
"timezone": {"type": "string", "description": "VD: Asia/Ho_Chi_Minh"}
},
"required": ["timezone"]
}
}
]
# Test xem Claude co parallel khong
response = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=1024,
tools=tools,
messages=[{
"role": "user",
"content": "Cho toi biet thoi tiet Ha Noi va gio hien tai VN?"
}]
)
tool_calls = [b for b in response.content if b.type == "tool_use"]
print(f"So tool calls trong 1 luot: {len(tool_calls)}")
# Ket qua thuong gap: 1 (sequential thay vi 2)
Điều này có nghĩa: thay vì 1 vòng lặp, bạn có 2-3 vòng lặp — mỗi vòng là một round-trip API. Với tools có latency cao (database queries, external APIs), đây là vấn đề nghiêm trọng về performance.
Giải pháp: Batch Meta-Tool
Ý tưởng: tạo một tool đặc biệt nhận vào một danh sách các tool invocations và thực thi tất cả cùng lúc. Claude gọi một tool duy nhất, nhưng tool đó chạy nhiều operations song song.
batch_tool = {
"name": "batch_tool",
"description": """Cong cu dac biet de goi nhieu tools song song.
Su dung khi can nhieu pieces of thong tin doc lap cung luc.
Moi invocation trong batch se duoc thuc thi dong thoi.
QUAN TRONG: Chi dung batch_tool khi cac calls doc lap nhau
(ket qua cua call nay khong anh huong den input cua call khac).""",
"input_schema": {
"type": "object",
"properties": {
"invocations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"tool_name": {
"type": "string",
"description": "Ten tool can goi"
},
"input": {
"type": "object",
"description": "Input cho tool do"
}
},
"required": ["tool_name", "input"]
},
"description": "Danh sach cac tool calls can thuc hien song song"
}
},
"required": ["invocations"]
}
}
Implement Batch Execution
import threading
import json
def get_weather(city):
"""Goi weather API (gia lap)"""
# Trong thuc te, day la HTTP request den weather service
weather_data = {
"Ha Noi": "28 do C, co may, do am 75%",
"Ho Chi Minh": "33 do C, nang, do am 65%",
"Da Nang": "30 do C, it may, do am 70%"
}
return weather_data.get(city, f"Khong co du lieu cho {city}")
def get_time(timezone):
"""Lay gio hien tai theo timezone"""
from datetime import datetime
import pytz
tz = pytz.timezone(timezone)
now = datetime.now(tz)
return now.strftime("%H:%M %d/%m/%Y")
def execute_single_tool(tool_name, tool_input):
"""Thuc thi mot tool don le"""
if tool_name == "get_weather":
return get_weather(tool_input["city"])
elif tool_name == "get_time":
return get_time(tool_input["timezone"])
return f"Tool {tool_name} khong ton tai"
def execute_batch_tool(invocations):
"""
Thuc thi nhieu tools song song bang threading.
Tra ve danh sach ket qua theo thu tu invocations.
"""
results = [None] * len(invocations)
errors = [None] * len(invocations)
def run_tool(index, tool_name, tool_input):
try:
results[index] = execute_single_tool(tool_name, tool_input)
except Exception as e:
errors[index] = str(e)
results[index] = f"Loi: {str(e)}"
# Khoi dong tat ca threads cung luc
threads = []
for i, inv in enumerate(invocations):
t = threading.Thread(
target=run_tool,
args=(i, inv["tool_name"], inv["input"])
)
threads.append(t)
t.start()
# Cho tat ca threads hoan thanh
for t in threads:
t.join()
# Format ket qua
batch_result = {}
for i, inv in enumerate(invocations):
batch_result[inv["tool_name"]] = results[i]
return json.dumps(batch_result, ensure_ascii=False)
def execute_tool(tool_name, tool_input):
"""Router chinh - xu ly ca batch va single tools"""
if tool_name == "batch_tool":
return execute_batch_tool(tool_input["invocations"])
return execute_single_tool(tool_name, tool_input)
Agent Loop với Batch Support
ALL_TOOLS = [batch_tool, get_weather_tool_def, get_time_tool_def]
def run_agent_with_batch(user_message):
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=1024,
tools=ALL_TOOLS,
messages=messages
)
if response.stop_reason == "end_turn":
return response.content[0].text
if response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f"[Tool] {block.name}: {json.dumps(block.input, ensure_ascii=False)[:100]}")
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})
messages.append({"role": "user", "content": tool_results})
else:
break
return ""
Demo và So sánh Latency
import time
# Test khong dung batch
def test_sequential():
start = time.time()
# Gia su moi tool mat 500ms
# Sequential: 500ms + 500ms = 1000ms
print("Sequential: ~1000ms cho 2 tools")
# Test voi batch tool
def test_with_batch():
start = time.time()
response = run_agent_with_batch(
"Cho toi biet thoi tiet Ha Noi va gio hien tai Viet Nam?"
)
elapsed = (time.time() - start) * 1000
print(f"Response: {response}")
print(f"Time: {elapsed:.0f}ms")
test_with_batch()
Output mong đợi khi Claude dùng batch_tool:
[Tool] batch_tool: {"invocations": [
{"tool_name": "get_weather", "input": {"city": "Ha Noi"}},
{"tool_name": "get_time", "input": {"timezone": "Asia/Ho_Chi_Minh"}}
]}
Response: Thoi tiet Ha Noi hien tai la 28 do C, co may, do am 75%.
Gio Viet Nam hien tai la 09:45 SA ngay 26/03/2026.
Time: ~520ms (thay vi ~1020ms sequential)
Với batch tool, cả 2 tools chạy song song — tổng thời gian gần bằng thời gian của 1 tool đơn lẻ.
Khi nào Batch Tool thực sự hữu ích?
Lợi ích lớn nhất khi:
- External API calls có latency cao — database queries, third-party services (100ms+)
- Nhiều tools độc lập cần cùng lúc — dashboard reports, morning briefings
- User experience quan trọng — chatbot cần phản hồi nhanh
Batch tool không cần thiết khi:
- Tools phụ thuộc nhau (output của tool A là input của tool B)
- Tools chạy trong memory — latency đã quá nhỏ
- Chỉ có 1-2 tools trong toàn bộ application
Giới hạn và Lưu ý
| Vấn đề | Chi tiết |
|---|---|
| Claude không luôn dùng batch | Claude quyết định khi nào dùng batch_tool — không guarantee. System prompt có thể giúp nhưng không phải lúc nào cũng hiệu quả. |
| Thread safety | Đảm bảo các tools của bạn thread-safe khi chạy parallel. Tránh shared mutable state. |
| Error handling | Một tool fail không nên làm cả batch fail. Bắt exception per-tool và trả về error message. |
| Timeout | Set timeout cho từng tool trong batch — tránh một slow tool làm chậm cả batch. |
Gợi ý System Prompt
Để Claude ưu tiên dùng batch_tool, thêm instruction vào system prompt:
SYSTEM_PROMPT = """...
Khi can nhieu thong tin doc lap, LUON su dung batch_tool thay vi goi
tung tool mot. Dieu nay giup giam latency va cai thien trai nghiem nguoi dung.
Cac truong hop nen dung batch: thoi tiet nhieu thanh pho, bao cao nhieu metrics,
lay thong tin tu nhieu sources cung luc.
..."""
Kỹ thuật này không thể đảm bảo 100% Claude sẽ luôn dùng batch, nhưng tăng đáng kể tần suất Claude chọn parallel execution.
Bài tiếp theo: kết hợp Vision với Tool Use để trích xuất dữ liệu có cấu trúc từ hình ảnh — ứng dụng multimodal AI thực tế nhất trong năm 2026.
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.



