WorkAI

Responses: /v1/responses

Обновлено

Формат OpenAI Responses в WorkAI API: input строкой и массивом, instructions, функции и цикл function_call, max_output_tokens. Примеры на cURL, Python и TypeScript.

POST /v1/responses принимает запросы в формате OpenAI Responses. Модели, цены и лимиты — те же, что у чата, действуют и его ограничения. Ответы не хранятся: previous_response_id даёт 400, историю присылайте целиком в input.

Базовый запрос

input — строка или массив сообщений, instructions — системный промпт.

cURL

curl https://api.workai.su/v1/responses \
  -H "Authorization: Bearer $WORKAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6.2-sol",
    "instructions": "Отвечай кратко, по-русски.",
    "input": "Чем отличается процесс от потока?"
  }'

Python

import os
from openai import OpenAI
client = OpenAI(base_url="https://api.workai.su/v1", api_key=os.environ["WORKAI_API_KEY"])

response = client.responses.create(
    model="openai/gpt-6.2-sol",
    instructions="Отвечай кратко, по-русски.",
    input="Чем отличается процесс от потока?",
)
print(response.output_text, response.usage)

TypeScript

import OpenAI from 'openai'
const client = new OpenAI({ baseURL: 'https://api.workai.su/v1', apiKey: process.env.WORKAI_API_KEY })

const response = await client.responses.create({
  model: 'openai/gpt-6.2-sol',
  instructions: 'Отвечай кратко, по-русски.',
  input: 'Чем отличается процесс от потока?',
})
console.log(response.output_text, response.usage)

История диалога — массивом: "input": [{"role": "user", "content": "…"}, {"role": "assistant", "content": "…"}, {"role": "user", "content": "…"}]. Сумма списания в рублях — в usage.cost ответа.

Функции

Формат объявления отличается от чата: поля функции лежат на верхнем уровне, без вложенного function. Модель возвращает в output элемент function_call; результат вы отправляете элементом function_call_output с тем же call_id, добавив в input и сам вызов.

Python

import json
tools = [{"type": "function", "name": "get_weather", "description": "Текущая погода в городе",
          "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}]
items = [{"role": "user", "content": "Какая погода в Москве?"}]
response = client.responses.create(model="openai/gpt-6.2-sol", input=items, tools=tools)
for item in response.output:
    if item.type == "function_call":
        result = {"city": json.loads(item.arguments)["city"], "temp_c": 3}  # здесь ваша функция
        items.append({"type": "function_call", "call_id": item.call_id, "name": item.name, "arguments": item.arguments})
        items.append({"type": "function_call_output", "call_id": item.call_id, "output": json.dumps(result, ensure_ascii=False)})
final = client.responses.create(model="openai/gpt-6.2-sol", input=items, tools=tools)
print(final.output_text)

TypeScript

const tools: OpenAI.Responses.Tool[] = [{ type: 'function', name: 'get_weather', description: 'Текущая погода в городе',
  parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }, strict: false }]
const items: OpenAI.Responses.ResponseInputItem[] = [{ role: 'user', content: 'Какая погода в Москве?' }]
const response = await client.responses.create({ model: 'openai/gpt-6.2-sol', input: items, tools })
for (const item of response.output) {
  if (item.type !== 'function_call') continue
  items.push({ type: 'function_call', call_id: item.call_id, name: item.name, arguments: item.arguments })
  const result = { city: JSON.parse(item.arguments).city, temp_c: 3 } // здесь ваша функция
  items.push({ type: 'function_call_output', call_id: item.call_id, output: JSON.stringify(result) })
}
const final = await client.responses.create({ model: 'openai/gpt-6.2-sol', input: items, tools })
console.log(final.output_text)

cURL — второй запрос:

curl https://api.workai.su/v1/responses \
  -H "Authorization: Bearer $WORKAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6.2-sol",
    "input": [
      {"role": "user", "content": "Какая погода в Москве?"},
      {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{\"city\":\"Москва\"}"},
      {"type": "function_call_output", "call_id": "call_1", "output": "{\"temp_c\":3}"}
    ],
    "tools": [{"type": "function", "name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}]
  }'

Работают инструменты function и custom. Встроенные инструменты OpenAI (web_search, file_search и другие) отбрасываются: модель их не видит.

Лимит длины ответа

max_output_tokens ограничивает ответ, минимум — 16 токенов. Оборванный по лимиту ответ приходит со status: "incomplete":

{"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}}

Поток

С "stream": true ответ приходит событиями: response.created в начале, response.output_text.delta с частями текста, response.function_call_arguments.delta с частями аргументов функции и response.completed в конце — в нём usage со стоимостью usage.cost.

Ограничения

400 на previous_response_id, conversation, prompt, background: true и store: true. JSON-режим (text.format) и остальные параметры зависят от модели — см. Ограничения по моделям и полный список в разделе Responses обзора.

Что дальше