LLM không thể tự làm gì cả. Chúng tạo ra văn bản. Đó là toàn bộ khả năng của chúng. Chúng không thể kiểm tra thời tiết, truy vấn database, gửi email, chạy code hay đọc file. Mọi “AI agent” bạn từng thấy đều là một LLM tạo ra JSON cho biết cần gọi function nào -- rồi code của bạn mới thực sự gọi function đó. Model là bộ não. Tool là đôi tay. Function calling là hệ thần kinh nối hai thứ ấy với nhau.
Mục tiêu bài học
- Triển khai một vòng lặp function calling: định nghĩa schema cho các tool, phân tích JSON của tool call từ model, thực thi function và trả kết quả về
- Thiết kế schema cho tool với mô tả rõ ràng và parameter có kiểu dữ liệu để model gọi một cách đáng tin cậy
- Xây dựng một vòng lặp agent nhiều lượt, kết nối nhiều function call để trả lời những câu hỏi phức tạp
- Xử lý các trường hợp đặc biệt của function calling: gọi nhiều tool song song, chuyển tiếp lỗi và ngăn vòng lặp tool vô hạn
Vấn đề
Bạn xây dựng một chatbot. Người dùng hỏi: “Thời tiết ở Tokyo lúc này thế nào?”
Model trả lời: “Tôi không có dữ liệu thời tiết theo thời gian thực, nhưng dựa vào mùa hiện tại, Tokyo có lẽ khoảng 15 độ C...”
Đó là Hallucination được che bằng một lời giải thích. Model không biết thời tiết. Nó sẽ không bao giờ tự biết. Thời tiết thay đổi từng giờ. Dữ liệu training của model đã cũ nhiều tháng.
Để trả lời đúng, bạn phải gọi OpenWeatherMap API, lấy nhiệt độ hiện tại và trả về con số thực. Model không thể gọi API. Code của bạn thì có thể. Mảnh ghép còn thiếu là một protocol có cấu trúc, cho phép model nói “Tôi cần gọi API thời tiết với những argument này”, rồi cho phép code của bạn thực thi lời gọi và đưa kết quả trở lại cho model.
Đó là function calling. Model xuất JSON có cấu trúc, mô tả cần gọi function nào với những argument nào. Ứng dụng của bạn thực thi function đó. Kết quả được đưa trở lại cuộc hội thoại. Model dùng kết quả để tạo câu trả lời cuối cùng.
Không có function calling, LLM chỉ là những cuốn bách khoa toàn thư. Có nó, chúng trở thành agent.
Khái niệm
Vòng lặp Function Calling
Mọi lần dùng tool đều theo cùng một vòng lặp 5 bước.
Bước 1: người dùng gửi tin nhắn. Bước 2: model nhận tin nhắn cùng với các định nghĩa tool (JSON Schema mô tả các function có thể dùng). Bước 3: thay vì trả lời bằng văn bản, model xuất một tool call -- một JSON object có cấu trúc, chứa tên function và các argument. Bước 4: code của bạn thực thi function và lấy kết quả. Bước 5: kết quả được đưa trở lại model, lúc này đã có dữ liệu thực để tạo câu trả lời cuối cùng.
Model không bao giờ thực thi thứ gì. Nó chỉ quyết định gọi gì và dùng những argument nào. Code của bạn là bên thực thi.
Định nghĩa Tool: Hợp đồng JSON Schema
Mỗi tool được định nghĩa bằng một JSON Schema cho model biết function đó làm gì, nhận những argument nào và các argument phải có kiểu dữ liệu gì.
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city. Returns temperature in Celsius and conditions.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g. 'Tokyo' or 'San Francisco'"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature units"
}
},
"required": ["city"]
}
}
}Các trường description rất quan trọng. Model đọc chúng để quyết định khi nào và dùng tool ra sao. Một mô tả mơ hồ như “lấy thời tiết” khiến model chọn tool kém chính xác hơn “Lấy thời tiết hiện tại của một thành phố. Trả về nhiệt độ tính bằng độ C và tình trạng thời tiết.” Mô tả chính là prompt để chọn tool.
So sánh các Provider
Mọi provider lớn đều hỗ trợ function calling, nhưng API của họ khác nhau.
| Provider | Parameter trong API | Định dạng Tool Call | Gọi song song | Bắt buộc gọi |
|---|---|---|---|---|
| OpenAI (GPT-5, o4) | tools | tool_calls[].function | Có (nhiều lời gọi trong một lượt) | tool_choice="required" |
| Anthropic (Claude 4.6/4.7) | tools | content[].type="tool_use" | Có (nhiều block) | tool_choice={"type":"any"} |
| Google (Gemini 3) | function_declarations | functionCall | Có | function_calling_config |
| Open-weight (Llama 4, Qwen3, DeepSeek-V3) | Trường tools có sẵn trên Llama 4; Hermes hoặc ChatML trên các model khác | Kết hợp nhiều định dạng | Tùy model | Dựa vào prompt hoặc tool_choice nếu được hỗ trợ |
Đến năm 2026, ba provider đóng đã tiến tới những định dạng dựa trên JSON Schema gần như giống nhau. Llama 4 có sẵn trường tools với cấu trúc giống OpenAI. Các bản fine-tuning của model open-weight vẫn khác nhau — định dạng Hermes (NousResearch) phổ biến nhất với các bản fine-tuning của bên thứ ba. Với tool dùng chung giữa nhiều host, hãy ưu tiên MCP (Phase 11 · 14) hơn function calling viết trực tiếp trong ứng dụng — cùng một server có thể phục vụ tất cả.
Tool Choice: Auto, Required, Specific
Bạn kiểm soát khi nào model dùng tool.
Auto (mặc định): model quyết định gọi tool hay trả lời trực tiếp. “2+2 bằng bao nhiêu?” -- trả lời trực tiếp. “Thời tiết thế nào?” -- gọi tool.
Required: model phải gọi ít nhất một tool. Dùng chế độ này khi bạn biết yêu cầu của người dùng cần đến tool. Nó ngăn model đoán mò thay vì tra dữ liệu thực.
Specific function: buộc model gọi một function cụ thể. tool_choice={"type":"function", "function": {"name": "get_weather"}} đảm bảo tool thời tiết được gọi, bất kể câu hỏi là gì. Dùng cách này để định tuyến -- khi logic ở bước trước đã xác định cần dùng tool nào.
Gọi Function Song Song
GPT-4o và Claude có thể gọi nhiều function trong một lượt. Người dùng hỏi: “Thời tiết ở Tokyo và New York thế nào?” Model xuất đồng thời hai tool call:
[
{"name": "get_weather", "arguments": {"city": "Tokyo"}},
{"name": "get_weather", "arguments": {"city": "New York"}}
]Code của bạn thực thi cả hai (lý tưởng là đồng thời), trả về cả hai kết quả, rồi model tổng hợp thành một câu trả lời. Cách này giảm số lượt trao đổi từ 2 xuống 1. Với những agent cần 5–10 tool call cho mỗi câu hỏi, gọi song song giúp giảm latency 60–80%.
Structured Outputs và Function Calling
Lesson 03 đã trình bày structured outputs. Function calling dùng cùng cơ chế JSON Schema, nhưng cho mục đích khác.
Structured outputs: buộc model tạo dữ liệu theo một cấu trúc cụ thể. Output chính là sản phẩm cuối cùng. Ví dụ: trích thông tin sản phẩm từ văn bản thành {name, price, in_stock}.
Function calling: model cho biết ý định thực hiện một hành động. Output là một bước trung gian. Ví dụ: get_weather(city="Tokyo") -- model đang yêu cầu một hành động, chưa tạo câu trả lời cuối cùng.
Dùng structured outputs khi bạn muốn trích xuất dữ liệu. Dùng function calling khi bạn muốn model tương tác với các hệ thống bên ngoài.
Bảo mật: Những Quy tắc Không thể Bỏ qua
Function calling là khả năng nguy hiểm nhất bạn có thể trao cho một LLM. Model chọn thứ sẽ được thực thi. Nếu bộ tool của bạn có truy vấn database, model sẽ tạo truy vấn. Nếu có lệnh shell, model sẽ viết lệnh.
Quy tắc 1: Không bao giờ đưa SQL do model tạo thẳng vào database. Model có thể và sẽ tạo DROP TABLE, kiểu tấn công chèn UNION hoặc truy vấn trả về mọi hàng. Luôn dùng parameter cho truy vấn. Luôn kiểm tra hợp lệ. Luôn dùng danh sách các thao tác được phép.
Quy tắc 2: Chỉ cho phép những function trong danh sách. Model chỉ có thể gọi những function bạn định nghĩa rõ ràng. Đừng bao giờ tạo một tool chung kiểu “thực thi function bất kỳ theo tên”. Nếu bạn có 50 function nội bộ, chỉ đưa ra 5 function người dùng cần.
Quy tắc 3: Kiểm tra argument. Model có thể truyền tên thành phố là "; DROP TABLE users; --". Hãy kiểm tra từng argument theo kiểu dữ liệu, phạm vi và định dạng mong đợi trước khi thực thi.
Quy tắc 4: Lọc kết quả từ tool. Nếu tool trả về dữ liệu nhạy cảm (API key, PII, lỗi nội bộ), hãy lọc trước khi gửi kết quả lại cho model. Model sẽ đưa nguyên văn kết quả từ tool vào câu trả lời.
Quy tắc 5: Giới hạn số lần gọi tool. Một model mắc trong vòng lặp có thể gọi tool hàng trăm lần. Hãy đặt mức tối đa (10–20 lời gọi cho mỗi cuộc hội thoại là hợp lý). Chặn các vòng lặp vô hạn.
Xử lý Lỗi
Tool có thể lỗi. API có thể hết thời gian chờ. Database có thể ngừng hoạt động. File có thể không tồn tại. Model cần biết khi nào tool lỗi và vì sao.
Trả lỗi dưới dạng kết quả có cấu trúc từ tool, thay vì ném exception:
{
"error": true,
"message": "City 'Toky' not found. Did you mean 'Tokyo'?",
"code": "CITY_NOT_FOUND"
}Model đọc kết quả đó, điều chỉnh argument rồi thử lại. Model khá giỏi tự sửa khi nhận thông báo lỗi có cấu trúc. Chúng xử lý kém khi nhận phản hồi rỗng hoặc lỗi chung chung như “đã xảy ra sự cố”.
MCP: Model Context Protocol
MCP là tiêu chuẩn mở của Anthropic để các tool hoạt động được với nhiều hệ thống. Thay vì mỗi ứng dụng tự định nghĩa tool của mình, MCP cung cấp một protocol chung: tool được phục vụ bởi MCP server và được MCP client (như Claude Code, Cursor hoặc ứng dụng của bạn) sử dụng.
Một MCP server có thể cung cấp tool cho mọi client tương thích. Một Postgres MCP server cho mọi agent tương thích với MCP quyền truy cập database. Một GitHub MCP server cho mọi agent quyền truy cập repository. Tool được định nghĩa một lần, dùng ở mọi nơi.
MCP đối với function calling cũng giống như HTTP đối với mạng máy tính. Nó chuẩn hóa lớp truyền tải để tool có thể dùng ở nhiều nơi.
Tự xây dựng
Bước 1: Định nghĩa Tool Registry
Xây dựng một registry lưu định nghĩa và phần triển khai của các tool. Mỗi tool có một định nghĩa JSON Schema (thứ model nhìn thấy) và một Python function (thứ code của bạn thực thi).
import ast
import json
import math
import time
import hashlib
TOOL_REGISTRY = {}
def register_tool(name, description, parameters, function):
TOOL_REGISTRY[name] = {
"definition": {
"type": "function",
"function": {
"name": name,
"description": description,
"parameters": parameters,
},
},
"function": function,
}Bước 2: Triển khai 5 Tool
Xây dựng một calculator, một tool tra thời tiết, một tool mô phỏng tìm kiếm web, một tool đọc file và một tool chạy code.
def calculator(expression, precision=2):
allowed = set("0123456789+-*/.() ")
if not all(c in allowed for c in expression):
return {"error": True, "message": f"Invalid characters in expression: {expression}"}
try:
result = eval(expression, {"__builtins__": {}}, {"math": math})
return {"result": round(float(result), precision), "expression": expression}
except Exception as e:
return {"error": True, "message": str(e)}
WEATHER_DB = {
"tokyo": {"temp_c": 18, "condition": "cloudy", "humidity": 72, "wind_kph": 14},
"new york": {"temp_c": 22, "condition": "sunny", "humidity": 45, "wind_kph": 8},
"london": {"temp_c": 12, "condition": "rainy", "humidity": 88, "wind_kph": 22},
"san francisco": {"temp_c": 16, "condition": "foggy", "humidity": 80, "wind_kph": 18},
"sydney": {"temp_c": 25, "condition": "sunny", "humidity": 55, "wind_kph": 10},
}
def get_weather(city, units="celsius"):
key = city.lower().strip()
if key not in WEATHER_DB:
suggestions = [c for c in WEATHER_DB if c.startswith(key[:3])]
return {
"error": True,
"message": f"City '{city}' not found.",
"suggestions": suggestions,
"code": "CITY_NOT_FOUND",
}
data = WEATHER_DB[key].copy()
if units == "fahrenheit":
data["temp_f"] = round(data["temp_c"] * 9 / 5 + 32, 1)
del data["temp_c"]
data["city"] = city
return data
SEARCH_DB = {
"python function calling": [
{"title": "OpenAI Function Calling Guide", "url": "https://platform.openai.com/docs/guides/function-calling", "snippet": "Learn how to connect LLMs to external tools."},
{"title": "Anthropic Tool Use", "url": "https://docs.anthropic.com/en/docs/tool-use", "snippet": "Claude can interact with external tools and APIs."},
],
"MCP protocol": [
{"title": "Model Context Protocol", "url": "https://modelcontextprotocol.io", "snippet": "An open standard for connecting AI models to data sources."},
],
"weather API": [
{"title": "OpenWeatherMap API", "url": "https://openweathermap.org/api", "snippet": "Free weather API with current, forecast, and historical data."},
],
}
def web_search(query, max_results=3):
key = query.lower().strip()
for db_key, results in SEARCH_DB.items():
if db_key in key or key in db_key:
return {"query": query, "results": results[:max_results], "total": len(results)}
return {"query": query, "results": [], "total": 0}
FILE_SYSTEM = {
"data/config.json": '{"model": "gpt-4o", "temperature": 0.7, "max_tokens": 4096}',
"data/users.csv": "name,email,role\nAlice,[email protected],admin\nBob,[email protected],user",
"README.md": "# My Project\nA tool-use agent built from scratch.",
}
def read_file(path):
if ".." in path or path.startswith("/"):
return {"error": True, "message": "Path traversal not allowed.", "code": "FORBIDDEN"}
if path not in FILE_SYSTEM:
available = list(FILE_SYSTEM.keys())
return {"error": True, "message": f"File '{path}' not found.", "available_files": available, "code": "NOT_FOUND"}
content = FILE_SYSTEM[path]
return {"path": path, "content": content, "size_bytes": len(content), "lines": content.count("\n") + 1}
def run_code(code, language="python"):
if language != "python":
return {"error": True, "message": f"Language '{language}' not supported. Only 'python' is available."}
try:
tree = ast.parse(code)
except SyntaxError as e:
return {"error": True, "message": f"SyntaxError: {e}", "code": "SYNTAX_ERROR"}
unsafe_names = {"exec", "eval", "compile", "__import__", "open", "globals", "locals", "vars", "getattr", "setattr", "delattr"}
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
return {"error": True, "message": "Forbidden operation: import is not allowed", "code": "SECURITY_VIOLATION"}
if isinstance(node, ast.Attribute) and node.attr.startswith("__") and node.attr.endswith("__"):
return {"error": True, "message": "Forbidden operation: dunder attribute access is not allowed", "code": "SECURITY_VIOLATION"}
if isinstance(node, ast.Name) and node.id in unsafe_names:
return {"error": True, "message": f"Forbidden operation: {node.id} is not allowed", "code": "SECURITY_VIOLATION"}
try:
local_vars = {}
exec(code, {"__builtins__": {"print": print, "range": range, "len": len, "str": str, "int": int, "float": float, "list": list, "dict": dict, "sum": sum, "min": min, "max": max, "abs": abs, "round": round, "sorted": sorted, "enumerate": enumerate, "zip": zip, "map": map, "filter": filter, "math": math}}, local_vars)
result = local_vars.get("result", None)
return {"success": True, "result": result, "variables": {k: str(v) for k, v in local_vars.items() if not k.startswith("_")}}
except Exception as e:
return {"error": True, "message": f"{type(e).__name__}: {e}"}Một danh sách chặn dựa trên substring đọc code như văn bản, nên sẽ bỏ sót bất cứ thứ gì không khớp đúng chuỗi ký tự. Nếu phân tích code thành cây cú pháp rồi duyệt cây, bộ kiểm tra có thể từ chối import statement, truy cập thuộc tính dunder (các chuỗi __class__ và __globals__ có thể dẫn ngược tới interpreter thực) và tên các builtin không an toàn dựa trên cấu trúc thay vì cách viết. Dù vậy, hãy xem đây là bộ lọc để học, không phải một ranh giới bảo mật thực sự. Mọi bộ kiểm tra chạy trong cùng process đều dùng chung interpreter với code nó chạy, và một người dùng quyết tâm vẫn có thể tìm ra những object có thể truy cập. Hệ thống production chạy code không đáng tin cậy trong một process hoặc container riêng (subprocess đã bị hạ quyền, gVisor, Firecracker hoặc dịch vụ chạy code), để nếu thoát khỏi môi trường cách ly, kẻ tấn công chỉ vào được một môi trường dùng xong rồi bỏ chứ không phải service của bạn.
Bước 3: Đăng ký Tất cả Tool
def register_all_tools():
register_tool(
"calculator", "Evaluate a mathematical expression. Supports +, -, *, /, parentheses, and decimals. Returns the numeric result.",
{"type": "object", "properties": {"expression": {"type": "string", "description": "Math expression, e.g. '(10 + 5) * 3'"}, "precision": {"type": "integer", "description": "Decimal places in result", "default": 2}}, "required": ["expression"]},
calculator,
)
register_tool(
"get_weather", "Get current weather for a city. Returns temperature, condition, humidity, and wind speed.",
{"type": "object", "properties": {"city": {"type": "string", "description": "City name, e.g. 'Tokyo' or 'San Francisco'"}, "units": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature units, defaults to celsius"}}, "required": ["city"]},
get_weather,
)
register_tool(
"web_search", "Search the web for information. Returns a list of results with title, URL, and snippet.",
{"type": "object", "properties": {"query": {"type": "string", "description": "Search query"}, "max_results": {"type": "integer", "description": "Maximum results to return", "default": 3}}, "required": ["query"]},
web_search,
)
register_tool(
"read_file", "Read the contents of a file. Returns the file content, size, and line count.",
{"type": "object", "properties": {"path": {"type": "string", "description": "Relative file path, e.g. 'data/config.json'"}}, "required": ["path"]},
read_file,
)
register_tool(
"run_code", "Run a small Python snippet behind a static-analysis guard and a restricted interpreter. This is a teaching filter, not real isolation. Set a 'result' variable to return output.",
{"type": "object", "properties": {"code": {"type": "string", "description": "Python code to execute"}, "language": {"type": "string", "enum": ["python"], "description": "Programming language"}}, "required": ["code"]},
run_code,
)Bước 4: Xây dựng Vòng lặp Function Calling
Đây là phần cốt lõi. Nó mô phỏng việc model quyết định gọi tool nào, thực thi tool và đưa kết quả trở lại.
def simulate_model_decision(user_message, tools, conversation_history):
msg = user_message.lower()
if any(word in msg for word in ["weather", "temperature", "forecast"]):
cities = []
for city in WEATHER_DB:
if city in msg:
cities.append(city)
if not cities:
for word in msg.split():
if word.capitalize() in [c.title() for c in WEATHER_DB]:
cities.append(word)
if not cities:
cities = ["tokyo"]
calls = []
for city in cities:
calls.append({"name": "get_weather", "arguments": {"city": city.title()}})
return calls
if any(word in msg for word in ["calculate", "compute", "math", "what is", "how much"]):
for token in msg.split():
if any(c in token for c in "+-*/"):
return [{"name": "calculator", "arguments": {"expression": token}}]
if "+" in msg or "-" in msg or "*" in msg or "/" in msg:
expr = "".join(c for c in msg if c in "0123456789+-*/.() ")
if expr.strip():
return [{"name": "calculator", "arguments": {"expression": expr.strip()}}]
return [{"name": "calculator", "arguments": {"expression": "0"}}]
if any(word in msg for word in ["search", "find", "look up", "google"]):
query = msg.replace("search for", "").replace("look up", "").replace("find", "").strip()
return [{"name": "web_search", "arguments": {"query": query}}]
if any(word in msg for word in ["read", "file", "open", "cat", "show"]):
for path in FILE_SYSTEM:
if path.split("/")[-1].split(".")[0] in msg:
return [{"name": "read_file", "arguments": {"path": path}}]
return [{"name": "read_file", "arguments": {"path": "README.md"}}]
if any(word in msg for word in ["run", "execute", "code", "python"]):
return [{"name": "run_code", "arguments": {"code": "result = 'Hello from the sandbox!'", "language": "python"}}]
return []
def execute_tool_call(tool_call):
name = tool_call["name"]
args = tool_call["arguments"]
if name not in TOOL_REGISTRY:
return {"error": True, "message": f"Unknown tool: {name}", "code": "UNKNOWN_TOOL"}
tool = TOOL_REGISTRY[name]
func = tool["function"]
start = time.time()
try:
result = func(**args)
except TypeError as e:
result = {"error": True, "message": f"Invalid arguments: {e}"}
elapsed_ms = round((time.time() - start) * 1000, 2)
return {"tool": name, "result": result, "execution_time_ms": elapsed_ms}
def run_function_calling_loop(user_message, max_iterations=5):
conversation = [{"role": "user", "content": user_message}]
tool_definitions = [t["definition"] for t in TOOL_REGISTRY.values()]
all_tool_results = []
for iteration in range(max_iterations):
tool_calls = simulate_model_decision(user_message, tool_definitions, conversation)
if not tool_calls:
break
results = []
for call in tool_calls:
result = execute_tool_call(call)
results.append(result)
conversation.append({"role": "assistant", "content": None, "tool_calls": tool_calls})
for result in results:
conversation.append({"role": "tool", "content": json.dumps(result["result"]), "tool_name": result["tool"]})
all_tool_results.extend(results)
break
return {"conversation": conversation, "tool_results": all_tool_results, "iterations": iteration + 1 if tool_calls else 0}Bước 5: Kiểm tra Argument
Xây dựng một validator để kiểm tra các argument của tool call theo JSON Schema trước khi thực thi.
def validate_tool_arguments(tool_name, arguments):
if tool_name not in TOOL_REGISTRY:
return [f"Unknown tool: {tool_name}"]
schema = TOOL_REGISTRY[tool_name]["definition"]["function"]["parameters"]
errors = []
if not isinstance(arguments, dict):
return [f"Arguments must be an object, got {type(arguments).__name__}"]
for required_field in schema.get("required", []):
if required_field not in arguments:
errors.append(f"Missing required argument: {required_field}")
properties = schema.get("properties", {})
for arg_name, arg_value in arguments.items():
if arg_name not in properties:
errors.append(f"Unknown argument: {arg_name}")
continue
prop_schema = properties[arg_name]
expected_type = prop_schema.get("type")
type_checks = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict}
if expected_type in type_checks:
if not isinstance(arg_value, type_checks[expected_type]):
errors.append(f"Argument '{arg_name}': expected {expected_type}, got {type(arg_value).__name__}")
if "enum" in prop_schema and arg_value not in prop_schema["enum"]:
errors.append(f"Argument '{arg_name}': '{arg_value}' not in {prop_schema['enum']}")
return errorsBước 6: Chạy Demo
def run_demo():
register_all_tools()
print("=" * 60)
print(" Function Calling & Tool Use Demo")
print("=" * 60)
print("\n--- Registered Tools ---")
for name, tool in TOOL_REGISTRY.items():
desc = tool["definition"]["function"]["description"][:60]
params = list(tool["definition"]["function"]["parameters"].get("properties", {}).keys())
print(f" {name}: {desc}...")
print(f" params: {params}")
print(f"\n--- Argument Validation ---")
validation_tests = [
("get_weather", {"city": "Tokyo"}, "Valid call"),
("get_weather", {}, "Missing required arg"),
("get_weather", {"city": "Tokyo", "units": "kelvin"}, "Invalid enum value"),
("calculator", {"expression": 123}, "Wrong type (int for string)"),
("unknown_tool", {"x": 1}, "Unknown tool"),
]
for tool_name, args, label in validation_tests:
errors = validate_tool_arguments(tool_name, args)
status = "VALID" if not errors else f"ERRORS: {errors}"
print(f" {label}: {status}")
print(f"\n--- Tool Execution ---")
direct_tests = [
{"name": "calculator", "arguments": {"expression": "(10 + 5) * 3 / 2"}},
{"name": "get_weather", "arguments": {"city": "Tokyo"}},
{"name": "get_weather", "arguments": {"city": "Mars"}},
{"name": "web_search", "arguments": {"query": "python function calling"}},
{"name": "read_file", "arguments": {"path": "data/config.json"}},
{"name": "read_file", "arguments": {"path": "../etc/passwd"}},
{"name": "run_code", "arguments": {"code": "result = sum(range(1, 101))"}},
{"name": "run_code", "arguments": {"code": "import os; os.system('rm -rf /')"}},
]
for call in direct_tests:
result = execute_tool_call(call)
print(f"\n {call['name']}({json.dumps(call['arguments'])})")
print(f" -> {json.dumps(result['result'], indent=None)[:100]}")
print(f" time: {result['execution_time_ms']}ms")
print(f"\n--- Full Function Calling Loop ---")
test_queries = [
"What's the weather in Tokyo?",
"Calculate (100 + 250) * 0.15",
"Search for MCP protocol",
"Read the config file",
"Run some Python code",
"Tell me a joke",
]
for query in test_queries:
print(f"\n User: {query}")
result = run_function_calling_loop(query)
if result["tool_results"]:
for tr in result["tool_results"]:
print(f" Tool: {tr['tool']} ({tr['execution_time_ms']}ms)")
print(f" Result: {json.dumps(tr['result'], indent=None)[:90]}")
else:
print(f" [No tool called -- direct response]")
print(f" Iterations: {result['iterations']}")
print(f"\n--- Parallel Tool Calls ---")
multi_city_query = "What's the weather in tokyo and london?"
print(f" User: {multi_city_query}")
result = run_function_calling_loop(multi_city_query)
print(f" Tool calls made: {len(result['tool_results'])}")
for tr in result["tool_results"]:
city = tr["result"].get("city", "unknown")
temp = tr["result"].get("temp_c", "N/A")
print(f" {city}: {temp}C, {tr['result'].get('condition', 'N/A')}")
print(f"\n--- Security Checks ---")
security_tests = [
("read_file", {"path": "../../etc/passwd"}),
("run_code", {"code": "import subprocess; subprocess.run(['ls'])"}),
("calculator", {"expression": "__import__('os').system('ls')"}),
]
for tool_name, args in security_tests:
result = execute_tool_call({"name": tool_name, "arguments": args})
blocked = result["result"].get("error", False)
print(f" {tool_name}({list(args.values())[0][:40]}): {'BLOCKED' if blocked else 'ALLOWED'}")Dùng thực tế
Function Calling của OpenAI
# from openai import OpenAI
#
# client = OpenAI()
#
# tools = [{
# "type": "function",
# "function": {
# "name": "get_weather",
# "description": "Get current weather for a city",
# "parameters": {
# "type": "object",
# "properties": {
# "city": {"type": "string"},
# "units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
# },
# "required": ["city"]
# }
# }
# }]
#
# response = client.chat.completions.create(
# model="gpt-4o",
# messages=[{"role": "user", "content": "Weather in Tokyo?"}],
# tools=tools,
# tool_choice="auto",
# )
#
# tool_call = response.choices[0].message.tool_calls[0]
# args = json.loads(tool_call.function.arguments)
# result = get_weather(**args)
#
# final = client.chat.completions.create(
# model="gpt-4o",
# messages=[
# {"role": "user", "content": "Weather in Tokyo?"},
# response.choices[0].message,
# {"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result)},
# ],
# )
# print(final.choices[0].message.content)OpenAI trả về các tool call tại response.choices[0].message.tool_calls. Mỗi lời gọi có một id mà bạn phải gửi kèm khi trả kết quả. Model dùng ID này để ghép kết quả với lời gọi. GPT-4o có thể trả về nhiều tool call trong một phản hồi -- hãy duyệt và thực thi tất cả.
Tool Use của Anthropic
# import anthropic
#
# client = anthropic.Anthropic()
#
# response = client.messages.create(
# model="claude-sonnet-5",
# max_tokens=1024,
# tools=[{
# "name": "get_weather",
# "description": "Get current weather for a city",
# "input_schema": {
# "type": "object",
# "properties": {
# "city": {"type": "string"},
# "units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
# },
# "required": ["city"]
# }
# }],
# messages=[{"role": "user", "content": "Weather in Tokyo?"}],
# )
#
# tool_block = next(b for b in response.content if b.type == "tool_use")
# result = get_weather(**tool_block.input)
#
# final = client.messages.create(
# model="claude-sonnet-5",
# max_tokens=1024,
# tools=[...],
# messages=[
# {"role": "user", "content": "Weather in Tokyo?"},
# {"role": "assistant", "content": response.content},
# {"role": "user", "content": [{"type": "tool_result", "tool_use_id": tool_block.id, "content": json.dumps(result)}]},
# ],
# )Anthropic trả về tool call dưới dạng content block có type: "tool_use". Kết quả từ tool nằm trong một tin nhắn của user với type: "tool_result". Lưu ý điểm khác biệt chính: Anthropic dùng input_schema để định nghĩa parameter của tool, còn OpenAI dùng parameters.
Tích hợp MCP
# MCP servers expose tools over a standardized protocol.
# Any MCP-compatible client can discover and call these tools.
#
# Example: connecting to a Postgres MCP server
#
# from mcp import ClientSession, StdioServerParameters
# from mcp.client.stdio import stdio_client
#
# server_params = StdioServerParameters(
# command="npx",
# args=["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"],
# )
#
# async with stdio_client(server_params) as (read, write):
# async with ClientSession(read, write) as session:
# await session.initialize()
# tools = await session.list_tools()
# result = await session.call_tool("query", {"sql": "SELECT count(*) FROM users"})MCP tách việc triển khai tool khỏi việc sử dụng tool. Postgres server hiểu SQL. GitHub server hiểu API. Agent của bạn chỉ cần tìm và gọi tool -- nó không cần code riêng cho từng provider ở mỗi lần tích hợp.
Đưa vào sản phẩm
Bài này tạo ra outputs/prompt-tool-designer.md -- một prompt template có thể tái sử dụng để thiết kế định nghĩa tool. Bạn đưa cho nó mô tả về điều mình muốn tool làm, và nó tạo ra định nghĩa JSON Schema đầy đủ, gồm mô tả, kiểu dữ liệu và các ràng buộc.
Bài này cũng tạo ra outputs/skill-function-calling-patterns.md -- một khung ra quyết định để triển khai function calling trong production, bao gồm thiết kế tool, xử lý lỗi, bảo mật và các pattern riêng cho từng provider.
Bài tập
- Thêm tool thứ 6: truy vấn database. Triển khai một tool SQL mô phỏng với bảng lưu trong memory. Tool nhận tên bảng và các điều kiện lọc (không nhận SQL thô). Kiểm tra tên bảng có trong danh sách được phép và các toán tử lọc chỉ gồm
=,>,<,>=,<=. Trả về những hàng khớp điều kiện dưới dạng JSON. - Triển khai retry với phản hồi lỗi. Khi một tool call thất bại (ví dụ: không tìm thấy thành phố), đưa thông báo lỗi trở lại function quyết định của model để nó sửa argument. Theo dõi số lần thử lại của từng lời gọi. Giới hạn tối đa 3 lần thử lại cho mỗi tool call.
- Xây dựng một agent nhiều bước. Một số câu hỏi cần nối tiếp các tool call: “Đọc file config và cho tôi biết model nào được cấu hình, rồi tìm trên web giá của model đó.” Triển khai một vòng lặp chạy đến khi model quyết định không cần thêm tool nào, đồng thời chuyển các kết quả đã thu thập vào mỗi bước ra quyết định. Giới hạn 10 vòng để ngăn vòng lặp vô hạn.
- Đo độ chính xác khi chọn tool. Tạo 30 câu hỏi thử nghiệm cùng tên tool mong đợi. Chạy function quyết định trên cả 30 câu và đo tỷ lệ chọn đúng tool. Xác định những câu hỏi khiến model dễ nhầm lẫn giữa các tool nhất.
- Triển khai cache cho tool call. Nếu cùng một tool được gọi với những argument giống hệt nhau trong vòng 60 giây, trả về kết quả trong cache thay vì thực thi lại. Dùng một dictionary với key là
(tool_name, frozenset(args.items())). Đo tỷ lệ cache hit trong một cuộc hội thoại có 20 câu hỏi.
Thuật ngữ chính
| Thuật ngữ | Người ta hay nói | Nghĩa thật sự |
|---|---|---|
| Function calling | “Dùng tool” | Model xuất JSON có cấu trúc, mô tả function cần gọi cùng các argument cụ thể -- code của bạn thực thi function đó, không phải model |
| Tool definition | “Schema của function” | Một JSON Schema object mô tả tên, mục đích, parameter và kiểu dữ liệu của tool -- model đọc nó để quyết định khi nào và dùng tool ra sao |
| Tool choice | “Chế độ gọi” | Kiểm soát việc model phải gọi tool (required), có thể gọi tool (auto), hoặc phải gọi một tool cụ thể (named) |
| Parallel calling | “Nhiều tool” | Model xuất nhiều tool call trong một lượt, giúp giảm số lượt trao đổi -- cả GPT-4o và Claude đều hỗ trợ |
| Tool result | “Output của function” | Giá trị trả về khi thực thi tool, được gửi lại cho model dưới dạng tin nhắn để nó dùng dữ liệu thực trong câu trả lời |
| Argument validation | “Kiểm tra input” | Xác minh các argument do model tạo có đúng kiểu dữ liệu, phạm vi và ràng buộc mong đợi trước khi thực thi tool |
| MCP | “Protocol cho tool” | Model Context Protocol -- tiêu chuẩn mở của Anthropic để cung cấp tool qua server, cho phép mọi client tương thích tìm thấy và gọi tool |
| Agent loop | “Vòng lặp ReAct” | Chu trình lặp: model chọn tool, code thực thi tool, kết quả được đưa trở lại, cho đến khi model có đủ thông tin để trả lời |
| Tool poisoning | “Prompt injection qua tool” | Một kiểu tấn công đưa chỉ dẫn vào kết quả từ tool để thao túng hành vi của model -- hãy lọc mọi output từ tool |
| Rate limiting | “Ngân sách lời gọi” | Đặt số tool call tối đa cho mỗi cuộc hội thoại để ngăn vòng lặp vô hạn và chi phí API tăng mất kiểm soát |
Đọc thêm
- Hướng dẫn Function Calling của OpenAI -- tài liệu tham khảo đầy đủ về cách dùng tool với GPT-4o, gồm gọi song song, bắt buộc gọi và argument có cấu trúc
- Hướng dẫn Tool Use của Anthropic -- cách Claude triển khai tool use với input_schema, phản hồi gồm nhiều tool và cấu hình tool_choice
- Đặc tả Model Context Protocol -- tiêu chuẩn mở giúp tool hoạt động giữa các ứng dụng AI, với kiến trúc server/client
- Schick và cộng sự, 2023 -- “Toolformer: Language Models Can Teach Themselves to Use Tools” -- paper nền tảng về training LLM để quyết định khi nào và cách gọi tool bên ngoài
- Patil và cộng sự, 2023 -- “Gorilla: Large Language Model Connected with Massive APIs” -- fine-tuning LLM để gọi chính xác 1.645 API và giảm Hallucination
- Berkeley Function Calling Leaderboard -- benchmark theo thời gian thực so sánh độ chính xác của function calling giữa GPT-4o, Claude, Gemini và các model mở
- Yao và cộng sự, “ReAct: Synergizing Reasoning and Acting in Language Models” (ICLR 2023) -- vòng lặp Thought-Action-Observation tạo thành vòng lặp agent bên ngoài mỗi tool call; Phase 14 tiếp nối từ điểm bài này kết thúc.
- Anthropic — Xây dựng agent hiệu quả (tháng 12/2024) -- năm pattern có thể kết hợp (prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer) được xây dựng từ một khả năng cơ bản là dùng tool.