Skip to content
Hướng dẫn

Gọi công cụ & Đầu ra có cấu trúc ​

Kết nối các LLM với API nội bộ, cơ sở dữ liệu và quy trình bên ngoài bằng định nghĩa công cụ theo JSON Schema nghiêm ngặt và phản hồi có cấu trúc được đảm bảo.

Vòng lặp gọi hàm / gọi công cụ (Tool Calling Loop) ​

  1. Gửi tin nhắn người dùng kèm theo mảng tools (định nghĩa tham số theo JSON Schema).
  2. Kiểm tra message.tool_calls (hoặc các khối tool_use trong Anthropic Messages).
  3. Thực thi hàm cục bộ trong ứng dụng của bạn và nối thêm kết quả với role: "tool" tham chiếu đúng tool_call_id.
  4. Gửi lại mảng tin nhắn đã cập nhật để nhận câu trả lời cuối cùng dựa trên dữ liệu thực tế.
python
import json, os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["VANIX_API_KEY"],
    base_url="https://api.vanix.io/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_order_status",
            "description": "Retrieve live shipment status by order ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "order_id": {"type": "string", "description": "Order ID such as ORD-9042"}
                },
                "required": ["order_id"],
                "additionalProperties": False,
            },
            "strict": True,
        },
    }
]

resp = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Where is order ORD-9042?"}],
    tools=tools,
    tool_choice="auto",
)

for call in resp.choices[0].message.tool_calls or []:
    print(call.function.name, json.loads(call.function.arguments))

Đầu ra có cấu trúc nghiêm ngặt (json_schema) ​

Đảm bảo JSON tuân thủ đúng lược đồ mà không cần phân tích bằng biểu thức chính quy (regex) dễ lỗi:

bash
curl https://api.vanix.io/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $VANIX_API_KEY" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {"role": "user", "content": "Classify ticket: Billing invoice PDF returns 403 after login."}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "ticket_triage",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "category": {"type": "string", "enum": ["billing", "auth", "api", "other"]},
            "severity": {"type": "string", "enum": ["p1", "p2", "p3"]},
            "summary": {"type": "string"}
          },
          "required": ["category", "severity", "summary"],
          "additionalProperties": false
        }
      }
    }
  }'

Danh mục kiểm tra chế độ Strict

Khi bật "strict": true trên các lược đồ OpenAI, mọi cấp đối tượng đều phải khai báo "additionalProperties": false và liệt kê đầy đủ tất cả các khóa trong "required".

Vanix AI Cổng API Hợp Nhất · https://api.vanix.io