Skip to content

Вызов инструментов

Вызов функций и интеграция инструментов с Responses API

Responses API поддерживает комплексные возможности вызова инструментов, позволяя моделям вызывать функции, выполнять инструменты параллельно и обрабатывать сложные многошаговые рабочие процессы.

Базовое определение инструментов

Определите инструменты, используя формат вызова функций OpenAI:

typescript
const weatherTool = {
  type: 'function' as const,
  name: 'get_weather',
  description: 'Получить текущую погоду в местоположении',
  strict: null,
  parameters: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: 'Город и регион, например Москва, Россия',
      },
      unit: {
        type: 'string',
        enum: ['celsius', 'fahrenheit'],
      },
    },
    required: ['location'],
  },
};

const response = await fetch('https://api.aitunnel.ru/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-aitunnel-xxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Какая погода в Санкт-Петербурге?',
          },
        ],
      },
    ],
    tools: [weatherTool],
    tool_choice: 'auto',
    max_output_tokens: 9000,
  }),
});

const result = await response.json();
console.log(result);
python
weather_tool = {
    'type': 'function',
    'name': 'get_weather',
    'description': 'Получить текущую погоду в местоположении',
    'strict': None,
    'parameters': {
        'type': 'object',
        'properties': {
            'location': {
                'type': 'string',
                'description': 'Город и регион, например Москва, Россия',
            },
            'unit': {
                'type': 'string',
                'enum': ['celsius', 'fahrenheit'],
            },
        },
        'required': ['location'],
    },
}

response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={
        'Authorization': 'Bearer sk-aitunnel-xxx',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'gpt-4o',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Какая погода в Санкт-Петербурге?',
                    },
                ],
            },
        ],
        'tools': [weather_tool],
        'tool_choice': 'auto',
        'max_output_tokens': 9000,
    }
)

result = response.json()
print(result)
bash
curl -X POST https://api.aitunnel.ru/v1/responses \
  -H "Authorization: Bearer sk-aitunnel-xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": [
          {
            "type": "input_text",
            "text": "Какая погода в Санкт-Петербурге?"
          }
        ]
      }
    ],
    "tools": [
      {
        "type": "function",
        "name": "get_weather",
        "description": "Получить текущую погоду в местоположении",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "Город и регион"
            }
          },
          "required": ["location"]
        }
      }
    ],
    "tool_choice": "auto"
  }'

Опции выбора инструментов

Контролируйте, когда и как вызываются инструменты:

Выбор инструментаОписание
autoМодель решает, вызывать ли инструменты
noneМодель не будет вызывать никаких инструментов
{type: 'function', name: 'tool_name'}Принудительный вызов конкретного инструмента

Принудительный вызов конкретного инструмента

typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-aitunnel-xxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Привет, как дела?',
          },
        ],
      },
    ],
    tools: [weatherTool],
    tool_choice: { type: 'function', name: 'get_weather' },
    max_output_tokens: 9000,
  }),
});
python
response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={
        'Authorization': 'Bearer sk-aitunnel-xxx',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'gpt-4o',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Привет, как дела?',
                    },
                ],
            },
        ],
        'tools': [weather_tool],
        'tool_choice': {'type': 'function', 'name': 'get_weather'},
        'max_output_tokens': 9000,
    }
)

Отключение вызова инструментов

typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-aitunnel-xxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Какая погода в Париже?',
          },
        ],
      },
    ],
    tools: [weatherTool],
    tool_choice: 'none',
    max_output_tokens: 9000,
  }),
});
python
response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={
        'Authorization': 'Bearer sk-aitunnel-xxx',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'gpt-4o',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Какая погода в Париже?',
                    },
                ],
            },
        ],
        'tools': [weather_tool],
        'tool_choice': 'none',
        'max_output_tokens': 9000,
    }
)

Несколько инструментов

Определите несколько инструментов для сложных рабочих процессов:

typescript
const calculatorTool = {
  type: 'function' as const,
  name: 'calculate',
  description: 'Выполнить математические вычисления',
  strict: null,
  parameters: {
    type: 'object',
    properties: {
      expression: {
        type: 'string',
        description: 'Математическое выражение для вычисления',
      },
    },
    required: ['expression'],
  },
};

const response = await fetch('https://api.aitunnel.ru/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-aitunnel-xxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Какая погода в Москве и сколько будет 15 * 23?',
          },
        ],
      },
    ],
    tools: [weatherTool, calculatorTool],
    tool_choice: 'auto',
    max_output_tokens: 9000,
  }),
});
python
calculator_tool = {
    'type': 'function',
    'name': 'calculate',
    'description': 'Выполнить математические вычисления',
    'strict': None,
    'parameters': {
        'type': 'object',
        'properties': {
            'expression': {
                'type': 'string',
                'description': 'Математическое выражение для вычисления',
            },
        },
        'required': ['expression'],
    },
}

response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={
        'Authorization': 'Bearer sk-aitunnel-xxx',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'gpt-4o',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Какая погода в Москве и сколько будет 15 * 23?',
                    },
                ],
            },
        ],
        'tools': [weather_tool, calculator_tool],
        'tool_choice': 'auto',
        'max_output_tokens': 9000,
    }
)

Параллельные вызовы инструментов

Модели могут вызывать несколько инструментов одновременно:

json
{
  "id": "resp_1234567890",
  "object": "response",
  "created_at": 1234567890,
  "model": "gpt-4o",
  "output": [
    {
      "type": "function_call",
      "id": "fc_1",
      "call_id": "call_weather",
      "name": "get_weather",
      "arguments": "{\"location\": \"Москва, Россия\"}"
    },
    {
      "type": "function_call",
      "id": "fc_2",
      "call_id": "call_calc",
      "name": "calculate",
      "arguments": "{\"expression\": \"15 * 23\"}"
    }
  ],
  "usage": {
    "input_tokens": 45,
    "output_tokens": 25,
    "total_tokens": 70
  },
  "status": "completed"
}

Ответы инструментов в разговоре

Включайте ответы инструментов в последующие запросы:

typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-aitunnel-xxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Какая погода в Бостоне?',
          },
        ],
      },
      {
        type: 'function_call',
        id: 'fc_1',
        call_id: 'call_123',
        name: 'get_weather',
        arguments: JSON.stringify({ location: 'Бостон, США' }),
      },
      {
        type: 'function_call_output',
        id: 'fc_output_1',
        call_id: 'call_123',
        output: JSON.stringify({ temperature: '22°C', condition: 'Солнечно' }),
      },
      {
        type: 'message',
        role: 'assistant',
        id: 'msg_abc123',
        status: 'completed',
        content: [
          {
            type: 'output_text',
            text: 'Погода в Бостоне сейчас 22°C и солнечно. Отличная погода для пикника!',
            annotations: []
          }
        ]
      },
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Хорошая ли это погода для пикника?',
          },
        ],
      },
    ],
    max_output_tokens: 9000,
  }),
});
python
response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={
        'Authorization': 'Bearer sk-aitunnel-xxx',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'gpt-4o',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Какая погода в Бостоне?',
                    },
                ],
            },
            {
                'type': 'function_call',
                'id': 'fc_1',
                'call_id': 'call_123',
                'name': 'get_weather',
                'arguments': '{"location": "Бостон, США"}',
            },
            {
                'type': 'function_call_output',
                'id': 'fc_output_1',
                'call_id': 'call_123',
                'output': '{"temperature": "22°C", "condition": "Солнечно"}',
            },
            {
                'type': 'message',
                'role': 'assistant',
                'id': 'msg_abc123',
                'status': 'completed',
                'content': [
                    {
                        'type': 'output_text',
                        'text': 'Погода в Бостоне сейчас 22°C и солнечно. Отличная погода для пикника!',
                        'annotations': []
                    }
                ]
            },
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Хорошая ли это погода для пикника?',
                    },
                ],
            },
        ],
        'max_output_tokens': 9000,
    }
)

Обязательное поле

Поле id обязательно для объектов function_call_output при включении ответов инструментов в историю разговора.

Стриминговые вызовы инструментов

Отслеживайте вызовы инструментов в реальном времени со стримингом:

typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-aitunnel-xxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Какая погода в Токио, Япония? Пожалуйста, проверь погоду.',
          },
        ],
      },
    ],
    tools: [weatherTool],
    tool_choice: 'auto',
    stream: true,
    max_output_tokens: 9000,
  }),
});

const reader = response.body?.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader!.read();
  if (done) break;

  const chunk = decoder.decode(value);
  const lines = chunk.split('\n');

  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = line.slice(6);
      if (data === '[DONE]') return;

      try {
        const parsed = JSON.parse(data);
        if (parsed.type === 'response.output_item.added' &&
            parsed.item?.type === 'function_call') {
          console.log('Вызов функции:', parsed.item.name);
        }
        if (parsed.type === 'response.function_call_arguments.done') {
          console.log('Аргументы:', parsed.arguments);
        }
      } catch (e) {
        // Пропускаем невалидный JSON
      }
    }
  }
}
python
import requests
import json

response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={
        'Authorization': 'Bearer sk-aitunnel-xxx',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'gpt-4o',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Какая погода в Токио, Япония? Пожалуйста, проверь погоду.',
                    },
                ],
            },
        ],
        'tools': [weather_tool],
        'tool_choice': 'auto',
        'stream': True,
        'max_output_tokens': 9000,
    },
    stream=True
)

for line in response.iter_lines():
    if line:
        line = line.decode('utf-8')
        if line.startswith('data: '):
            data = line[6:]
            if data == '[DONE]':
                break
            
            try:
                parsed = json.loads(data)
                if (parsed.get('type') == 'response.output_item.added' and 
                    parsed.get('item', {}).get('type') == 'function_call'):
                    print('Вызов функции:', parsed['item']['name'])
                if parsed.get('type') == 'response.function_call_arguments.done':
                    print('Аргументы:', parsed.get('arguments'))
            except json.JSONDecodeError:
                continue

Валидация инструментов

Убедитесь, что вызовы инструментов имеют правильную структуру:

json
{
  "type": "function_call",
  "id": "fc_abc123",
  "call_id": "call_xyz789",
  "name": "get_weather",
  "arguments": "{\"location\":\"Сиэтл, США\"}"
}

Обязательные поля

  • type: Всегда "function_call"
  • id: Уникальный идентификатор объекта вызова функции
  • name: Имя функции, соответствующее определению инструмента
  • arguments: Валидная JSON-строка с параметрами функции
  • call_id: Уникальный идентификатор вызова

Структура ответа с инструментами

Когда модель вызывает инструменты, ответ содержит объекты function_call:

json
{
  "id": "resp_1234567890",
  "object": "response",
  "created_at": 1234567890,
  "model": "gpt-4o",
  "output": [
    {
      "type": "function_call",
      "id": "fc_abc123",
      "call_id": "call_weather_1",
      "name": "get_weather",
      "arguments": "{\"location\": \"Москва, Россия\"}"
    }
  ],
  "usage": {
    "input_tokens": 45,
    "output_tokens": 25,
    "total_tokens": 70
  },
  "status": "completed"
}

Примеры использования

Погода и вычисления

python
# Определение инструментов
weather_tool = {
    'type': 'function',
    'name': 'get_weather',
    'description': 'Получить текущую погоду',
    'parameters': {
        'type': 'object',
        'properties': {
            'location': {'type': 'string', 'description': 'Местоположение'}
        },
        'required': ['location']
    }
}

calculator_tool = {
    'type': 'function',
    'name': 'calculate',
    'description': 'Выполнить вычисления',
    'parameters': {
        'type': 'object',
        'properties': {
            'expression': {'type': 'string', 'description': 'Математическое выражение'}
        },
        'required': ['expression']
    }
}

# Использование
response = requests.post(
    'https://api.aitunnel.ru/v1/responses',
    headers={'Authorization': 'Bearer sk-aitunnel-xxx', 'Content-Type': 'application/json'},
    json={
        'model': 'gpt-4o',
        'input': 'Какая погода в Москве и сколько будет 25 + 17?',
        'tools': [weather_tool, calculator_tool],
        'tool_choice': 'auto'
    }
)

Поиск информации

python
search_tool = {
    'type': 'function',
    'name': 'search_database',
    'description': 'Поиск информации в базе данных',
    'parameters': {
        'type': 'object',
        'properties': {
            'query': {'type': 'string', 'description': 'Поисковый запрос'},
            'category': {'type': 'string', 'enum': ['продукты', 'клиенты', 'заказы']}
        },
        'required': ['query']
    }
}

Лучшие практики

  1. Четкие описания: Предоставляйте подробные описания функций и объяснения параметров
  2. Правильные схемы: Используйте валидную JSON Schema для параметров
  3. Обработка ошибок: Обрабатывайте случаи, когда инструменты могут не вызываться
  4. Параллельное выполнение: Разрабатывайте инструменты для независимой работы, когда это возможно
  5. Поток разговора: Включайте ответы инструментов в последующие запросы для контекста

Ограничения

  • Максимум 128 инструментов на запрос
  • Аргументы должны быть валидными JSON-строками
  • Некоторые модели могут не поддерживать все возможности инструментов
  • Параллельные вызовы зависят от возможностей модели

Следующие шаги

AITUNNEL