Function Calling: Responses API và Chat Completions
So sánh Function Definition, Call ID, result, streaming arguments, authorization, idempotency và tương thích route.
Responses và Chat Completions đều có thể yêu cầu ứng dụng chạy một hàm, nhưng biểu diễn Tool Loop khác nhau. Chat Completions định nghĩa hàm dưới tools[].function, trả về message.tool_calls và nhận kết quả bằng message role: "tool". Responses dùng function definition phẳng, typed function_call output item và function_call_output liên kết bằng call_id.
Mô hình không tự chạy hàm ứng dụng. Code phải validate arguments, authorize thao tác, execute chính xác, trả kết quả và ngăn side effect trùng khi request được retry.
Tool Loop có bốn bước
1. Khai báo hàm được phép và Argument Schema
2. Nhận một hoặc nhiều Function Call do mô hình đề xuất
3. Validate, authorize và execute trong ứng dụng
4. Trả từng result bằng Correlation ID của Call
Chỉ sau bước bốn mô hình mới tạo câu trả lời dựa trên Tool Result. Tool tiếp theo bắt đầu vòng mới với Call ID mới. Hướng dẫn OpenAI Function Calling cũng mô tả đây là trao đổi nhiều bước.
So sánh Wire Contract
| Khía cạnh | Responses API | Chat Completions |
|---|---|---|
| Definition | Item phẳng trong tools[] |
Field dưới tools[].function |
| Call từ mô hình | function_call output item |
Assistant tool_calls[] |
| Correlation | call_id |
id, result dùng tool_call_id |
| Tên | function_call.name |
tool_calls[].function.name |
| Arguments | JSON string function_call.arguments |
JSON string tool_calls[].function.arguments |
| Result | function_call_output |
Message role: "tool" |
| Streaming | Typed argument events | Fragment delta.tool_calls[] |
| Final text | Output items / helper | choices[0].message.content |
Không correlate theo vị trí Array. Parallel Call và chunk có thể kết thúc theo thứ tự khác. Call ID rõ ràng là join key ổn định.
Định nghĩa Function Schema strict
{
"type": "object",
"properties": {
"order_id": { "type": "string", "pattern": "^ORDER-[0-9]{4}$" }
},
"required": ["order_id"],
"additionalProperties": false
}
strict: true yêu cầu mô hình tuân thủ Schema, nhưng ứng dụng vẫn phải parse và validate. pattern cùng keyword khác có thể khác theo provider; hãy dùng cùng compatibility gate như Structured Outputs.
Triển khai với Responses API
const tools = [{
type: "function",
name: "get_delivery_status",
description: "Return the current delivery status for one order.",
parameters: {
type: "object",
properties: { order_id: { type: "string", pattern: "^ORDER-[0-9]{4}$" } },
required: ["order_id"], additionalProperties: false,
},
strict: true,
}];
const first = await client.responses.create({
model, input: "Where is ORDER-1001?", tools, parallel_tool_calls: false,
});
const calls = first.output.filter(item => item.type === "function_call");
const outputs = calls.map(call => ({
type: "function_call_output",
call_id: call.call_id,
output: JSON.stringify(executeTool(call.name, call.arguments)),
}));
const final = await client.responses.create({
model, input: [...first.output, ...outputs], tools, parallel_tool_calls: false,
});
call.call_id phải khớp call_id của result. Với exchange stateless, gửi lại output item trước cùng result. Không giả định mọi route OpenAI-compatible đều lưu Response State.
Triển khai với Chat Completions
const tools = [{
type: "function",
function: {
name: "get_delivery_status",
description: "Return the current delivery status for one order.",
parameters: {
type: "object",
properties: { order_id: { type: "string", pattern: "^ORDER-[0-9]{4}$" } },
required: ["order_id"], additionalProperties: false,
},
strict: true,
},
}];
const first = await client.chat.completions.create({ model, messages, tools });
const assistant = first.choices[0].message;
messages.push(assistant);
for (const call of assistant.tool_calls ?? []) {
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(executeTool(call.function.name, call.function.arguments)),
});
}
Assistant Message chứa Call phải được thêm trước Tool Result. Thiếu message hoặc tool_call_id không khớp tạo transcript invalid.
Xem Streaming Arguments là fragment
{"order là JSON chưa hoàn tất, không phải invalid. Duy trì buffer theo Call, nối từng delta, chờ Arguments Done hoặc Completed, parse string đầy đủ một lần rồi validate và execute. Responses dùng typed events; Chat Completions dùng choices[].delta.tool_calls[]. Không chạy hàm ở fragment đầu. Xem Hướng dẫn AI API Streaming.
Làm Tool Execution an toàn và idempotent
- chỉ cho phép Function Name đã đăng ký;
- giới hạn kích thước và validate Schema đầy đủ;
- authorize User hoặc Workload cho resource;
- tách Read-only Tool khỏi side effect;
- loại secrets khỏi result;
- dùng Deadline và downstream retry có giới hạn;
- lưu Operation Reference an toàn.
Với side effect, tạo Idempotency Key từ stable application request và Call ID. Persist result trước khi trả. Replay phải trả result đã lưu thay vì refund, message, deployment hoặc DB mutation lần hai.
Function Name và Arguments từ mô hình là untrusted input. Schema hợp lệ không cấp quyền và không thay transaction boundary.
Quyết định cách xử lý Multiple Call
parallel_tool_calls: false làm State Machine dễ kiểm tra. Nếu bật parallel, correlate bằng Call ID, giới hạn số Call và concurrency, định nghĩa tác động của lỗi, trả một result cho mỗi Call và serialize side effect phụ thuộc thứ tự. Parallel giảm latency cho read độc lập nhưng tăng độ phức tạp authorization, retry và partial failure.
Hiểu giới hạn tương thích Modelflare
Modelflare giữ strict function definition và map hình dạng được hỗ trợ giữa Responses và Chat Completions trên route OpenAI/Codex phù hợp. Mapping cố ý hẹp hơn toàn bộ Responses Tool Surface.
Application-defined Function có thể biểu diễn trong hai format. Hosted Tool do provider chạy như search hoặc code execution không tương đương. Các họ OpenAI-compatible khác là Raw Chat Completions Pass-through đến khi được xác minh; upstream quyết định tools, strict, parallel call, streaming arguments và tool_choice.
| Kiểm thử | Bằng chứng cần thiết |
|---|---|
| Read-only Call | Tên, arguments, Call ID, result linkage, final text |
| Invalid Arguments | Error rõ ràng, không execute |
| Unknown Function | Allowlist từ chối |
| No Tool | Text bình thường, không Call bịa |
| Streaming | Arguments hoàn chỉnh và ID đúng |
| Repeated Request | Một side effect hoặc cached result |
| Multiple Calls | Correlation không phụ thuộc thứ tự |
| Route Fallback | Cùng model, protocol, Schema và contract |
Dùng Reliable AI API Routing để route change rõ ràng và AI API Key Security để tách Workload cùng permission.
Chọn format theo Application Contract
Dùng Responses khi cần Typed Output Items, Responses Event Model, State Continuation hoặc capability đã xác minh. Dùng Chat Completions khi ứng dụng sở hữu Message Transcript ổn định và Tool Contract của provider đã kiểm thử. Xem Responses API và Chat Completions.
Tiêu chuẩn ở cả hai format giống nhau: Tool Allowlist rõ ràng, Strict Argument Schema, validation trong ứng dụng, authorization trước execute, correlation bằng Call ID, idempotency cho side effect và result đầy đủ cho mô hình. Các control này tạo độ tin cậy, không phải tên endpoint.