메인 콘텐츠로 건너뛰기
함수 호출을 이용하면 모델이 애플리케이션이 실행할 수 있는 구조화된 도구 호출을 선택할 수 있습니다. 모델 자체가 함수를 실행하지는 않습니다. 함수 이름과 인수를 반환하면, 여러분의 코드가 함수를 실행하고 그 결과를 모델에 돌려 보냅니다. 모델이 실시간 데이터, 애플리케이션 동작, 데이터베이스 조회 또는 결정적인 계산을 필요로 할 때 함수 호출을 사용하세요.

기본 도구 정의

OpenAI 호환 tools 배열로 도구를 정의합니다:
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["VENICE_API_KEY"],
    base_url="https://api.venice.ai/api/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather in a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and state, such as San Francisco, CA",
                    }
                },
                "required": ["location"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="zai-org-glm-5",
    messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
    tools=tools,
)

print(response.choices[0].message.tool_calls)
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.VENICE_API_KEY,
  baseURL: "https://api.venice.ai/api/v1",
});

const tools = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "Get the current weather in a location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "City and state, such as San Francisco, CA",
          },
        },
        required: ["location"],
      },
    },
  },
];

const response = await client.chat.completions.create({
  model: "zai-org-glm-5",
  messages: [{ role: "user", content: "What is the weather in San Francisco?" }],
  tools,
});

console.log(response.choices[0].message.tool_calls);
curl https://api.venice.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $VENICE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "zai-org-glm-5",
    "messages": [
      {"role": "user", "content": "What is the weather in San Francisco?"}
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get the current weather in a location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "City and state, such as San Francisco, CA"
              }
            },
            "required": ["location"]
          }
        }
      }
    ]
  }'

도구 실행하기

모델이 도구를 선택하면 message.tool_calls를 확인하고 인수를 파싱한 뒤 애플리케이션 함수를 실행하고, 그 결과를 tool 메시지로 다시 전송합니다.
Python
import json

message = response.choices[0].message
tool_call = message.tool_calls[0]
arguments = json.loads(tool_call.function.arguments)

weather = get_weather(arguments["location"])

follow_up = client.chat.completions.create(
    model="zai-org-glm-5",
    messages=[
        {"role": "user", "content": "What is the weather in San Francisco?"},
        message.model_dump(),
        {
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(weather),
        },
    ],
    tools=tools,
)

print(follow_up.choices[0].message.content)

모델 선택

함수 호출 지원은 모델에 따라 다릅니다. supportsFunctionCalling이 지원되는 모델을 찾으려면 텍스트 모델 페이지나 Models API를 이용하세요.
도구 인수는 신뢰할 수 없는 입력으로 간주하세요. 데이터베이스 쿼리, 쉘 명령, 결제 또는 기타 부작용이 있는 작업에 사용하기 전에 인수를 검증하세요.

설계 팁

  • 도구 이름과 설명은 짧고 명확하게 유지하세요.
  • JSON Schema를 사용해 모델이 유효한 인수를 만들기 쉽도록 하세요.
  • 여러 선택적 동작을 가진 하나의 광범위한 도구보다는 입력이 명확한 좁은 도구를 선호하세요.
  • 도구 결과는 간결하게 반환해 최종 답변이 토큰 낭비 없이 충분한 컨텍스트를 갖도록 하세요.

관련 리소스