Bản tiếng Việt được biên soạn riêng để hướng dẫn tự nhiên, dễ theo dõi. Đọc bằng English
THÔNG TIN TƯƠNG THÍCH · Bảng tương thích
Function tools
Với model/provider phù hợp, Chat Completions và Responses có thể trả về function call theo schema tool mà Gateway đã kiểm tra. Khả năng này phụ thuộc model và provider; trong profile hiện tại, chỉ function tools nằm trong phạm vi hỗ trợ. Gateway trả thông tin lời gọi hàm, còn ứng dụng của bạn chịu trách nhiệm chạy hàm đó.
Khai báo tool qua tools và chọn cách gọi bằng tool_choice trong Responses hoặc Chat Completions. Schema tool tuân theo một phần chặt chẽ của Structured Outputs. Khi gửi kết quả về, giữ nguyên ID của tool call để model ghép đúng với yêu cầu ban đầu.
Xử lý tool call
Luồng xử lý ở phía máy chủ gồm hai chặng: gửi request kèm schema hàm; nếu model yêu cầu gọi hàm, kiểm tra tham số rồi thực thi trong ứng dụng và gửi lại assistant tool call cùng kết quả có ID tương ứng ở một request generation mới. Mỗi request generation cần một idempotency key riêng. Đừng chạy tham số chưa tin cậy nếu chưa tự kiểm tra dữ liệu và quyền của người gọi.
Ví dụ Python hoàn chỉnh dưới đây dùng một hàm giả lập chạy trên máy của bạn. Hãy thay bằng logic ứng dụng có kiểm tra quyền; Gateway không chạy hàm này thay bạn.
import json
import os
from uuid import uuid4
from openai import OpenAI
client = OpenAI(
api_key=os.environ["TASKWAY_API_KEY"],
base_url=os.environ["TASKWAY_BASE_URL"],
)
def lookup_order(order_id):
# Replace this local example with an authorized application function.
return {"order_id": order_id, "status": "shipped"}
messages = [{"role": "user", "content": "Check the status of order A-123."}]
first = client.chat.completions.create(
model="auto",
messages=messages,
tools=[{
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by its identifier.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
"additionalProperties": False,
},
},
}],
tool_choice="auto",
extra_headers={"Idempotency-Key": str(uuid4())},
)
assistant_message = first.choices[0].message
messages.append(assistant_message.model_dump(exclude_none=True))
for tool_call in assistant_message.tool_calls or []:
arguments = json.loads(tool_call.function.arguments)
result = lookup_order(**arguments)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result),
})
if assistant_message.tool_calls:
final = client.chat.completions.create(
model="auto",
messages=messages,
extra_headers={"Idempotency-Key": str(uuid4())},
)
print(final.choices[0].message.content)
else:
print(assistant_message.content)
Stream completion
Đặt stream=true rồi đọc các server-sent event do SDK trả về. Request tạo response vẫn cần idempotency key như bình thường.
import os
from uuid import uuid4
from openai import OpenAI
client = OpenAI(
api_key=os.environ["TASKWAY_API_KEY"],
base_url=os.environ["TASKWAY_BASE_URL"],
)
stream = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "Count from one to five."}],
stream=True,
extra_headers={"Idempotency-Key": str(uuid4())},
)
for chunk in stream:
text = chunk.choices[0].delta.content
if text:
print(text, end="", flush=True)
import { randomUUID } from "node:crypto";
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.TASKWAY_API_KEY,
baseURL: process.env.TASKWAY_BASE_URL,
});
const stream = await client.chat.completions.create(
{
model: "auto",
messages: [{ role: "user", content: "Count from one to five." }],
stream: true,
},
{ headers: { "Idempotency-Key": randomUUID() } },
);
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta.content;
if (text) process.stdout.write(text);
}
Các chế độ streaming
Khi streaming tiến độ từ provider đang tắt, Gateway vẫn có thể trả về SSE sau khi quá trình tạo nội dung hoàn tất. Vì vậy, chỉ đặt stream=true chưa đảm bảo nhận token ngay khi provider tạo ra. Muốn stream trực tiếp từ provider, dịch vụ cần bật GATEWAY_OPENAI_REAL_STREAMING_ENABLED=true; mặc định cờ này đang tắt.
Khi bật chế độ trực tiếp, Gateway stream nội dung từ model tạo kết quả cuối. Các bước định tuyến nội bộ và nội dung OCR không được đưa vào luồng. Nếu xảy ra lỗi sau khi SSE header đã gửi, lỗi được chuyển thành event vì HTTP status không thể thay đổi nữa. Request idempotent được phát lại sẽ trả kết quả đã hoàn tất, không tái hiện nhịp từng chunk ban đầu.