Skip to content

Справочник API

Все эндпоинты относятся к https://api.worken.ru. Каждый запрос должен содержать:

Authorization: Bearer sk-ваш-ключ
Content-Type: application/json   (для POST / PATCH)

Боты

Боты (также называемые виртсами) — это AI-агенты, которые обрабатывают диалоги.

Типы

typescript
type BotStatus = 'active' | 'disabled' | 'error'

type Bot = {
  id: string
  name: string
  description: string | null
  status: BotStatus
  project_id: string
  created_at: string
  updated_at: string
}

type BotSettings = {
  ai: {
    instruction: string
    model: {
      id: string           // например "openai/gpt-4o-mini"
      temperature: number  // 0.0–2.0
      max_tokens: number
      top_p: number
      frequency_penalty: number
      presence_penalty: number
    }
    memory: {
      lastMessages: number
      semanticRecall: boolean
      workingMemory: { enabled: boolean }
      generateTitle: boolean
    }
    formatting: {
      removeEmojis: boolean
      removeMarkdown: boolean
    }
    tools: Record<string, 'user_approve' | 'operator_approve' | 'auto'>
  }
}

Получить список ботов

GET /bots

Возвращает всех ботов текущего проекта.

Ответ 200

typescript
type ListBotsResponse = Bot[]

Создать бота

POST /bots

Тело

typescript
type CreateBotBody = {
  name: string
}

Ответ 200Bot

Пример

sh
curl https://api.worken.ru/bots \
  -X POST \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{"name": "Бот продаж"}'

Получить бота

GET /bots/:bot_id

Ответ 200Bot


Обновить бота

POST /bots/:bot_id

Тело

typescript
type UpdateBotBody = {
  name?: string
  description?: string
}

Ответ 200Bot


Установить статус бота

POST /bots/:bot_id/status

Тело

typescript
type SetBotStatusBody = {
  status: BotStatus
}

Получить настройки бота

GET /bots/:bot_id/settings

Ответ 200BotSettings


Обновить настройки бота

POST /bots/:bot_id/settings

Поддерживается частичное обновление — изменяются только переданные поля.

Тело — частичный BotSettings

Пример — обновить модель и инструкцию

sh
curl https://api.worken.ru/bots/${BOT_ID}/settings \
  -X POST \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{
    "ai": {
      "instruction": "Ты помощник по продажам. Фокусируйся на преимуществах продукта.",
      "model": { "id": "openai/gpt-4o", "temperature": 0.7 }
    }
  }'

Клонировать бота

POST /bots/:bot_id/clone

Создаёт нового бота с идентичными настройками. Полезно для A/B-тестирования конфигураций.

Ответ 200Bot


Удалить бота

POST /bots/:bot_id/delete

Ответ 200


Чаты

Чат — это канал, через который пользователи общаются с ботом: Telegram-группа, виджет на сайте, WhatsApp-входящие и т.д.

Типы

typescript
type ChatStatus = 'active' | 'disabled' | 'error'

type Chat = {
  id: string
  name: string
  bot_id: string
  integration_id: string | null
  status: ChatStatus
  project_id: string
  created_at: string
  updated_at: string
  events_24h: number  // количество событий за последние 24 часа
}

Список чатов

GET /chats

Ответ 200Chat[]


Получить чат

GET /chats/:chat_id

Ответ 200Chat


Список тредов в чате

GET /chats/:chat_id/threads

Ответ 200

typescript
type Thread = {
  id: string
  chat_id: string
  bot_id: string
  mode: 'auto' | 'manual' | 'operator' | 'blocked'
  title: string | null
  last_message_at: string | null
  pending_count: number
  created_at: string
}

type ListThreadsResponse = Thread[]

Стриминг ответа (SSE)

Отправьте сообщение пользователя и получите ответ AI в виде потока Server-Sent Events.

POST /chats/:chat_id/threads/:thread_id/stream

Тело

typescript
type StreamBody = {
  messages: Array<{
    role: 'user'
    content: string
  }>
  scheduledAt?: string  // ISO 8601 — отложенная отправка
}

Ответtext/event-stream (Vercel AI SDK data stream v2)

typescript
// События в процессе стриминга
type StreamEvent =
  | { type: 'text-delta'; textDelta: string }
  | { type: 'tool-call'; toolName: string; args: unknown }
  | { type: 'tool-result'; toolName: string; result: unknown }
  | { type: 'finish'; finishReason: 'stop' | 'tool-calls' | 'length' }

Пример через SDK

typescript
const stream = await worken.chats.threads.stream(chatId, threadId, {
  messages: [{ role: 'user', content: 'Какая у вас политика возврата?' }],
})

for await (const chunk of stream) {
  process.stdout.write(chunk.textDelta ?? '')
}

Получить сообщения треда

GET /chats/:chat_id/threads/:thread_id/messages

Возвращает полную историю из памяти агента.

Ответ 200

typescript
type Message = {
  id: string
  role: 'user' | 'assistant' | 'tool'
  content: string
  created_at: string
}

type GetMessagesResponse = Message[]

Удалить тред

POST /chats/:chat_id/threads/:thread_id/delete

Удаляет тред и его сообщения из памяти.


Установить режим треда

POST /chats/:chat_id/threads/:thread_id/mode

Тело

typescript
type SetThreadModeBody = {
  mode: 'auto' | 'manual' | 'operator' | 'blocked'
}
РежимПоведение
autoAI обрабатывает все ответы
manualОператор отвечает вручную, AI приостановлен
operatorОператор печатает ответ, AI приостановлен
blockedОтветы не отправляются

Треды

Эндпоинт /threads даёт представление по всем чатам проекта.

Список тредов

GET /threads

Параметры запроса

ПараметрТипОписание
chat_idstringФильтр по чату
bot_idstringФильтр по боту
searchstringПолнотекстовый поиск
limitnumberМаксимум результатов (по умолчанию 20)
offsetnumberСмещение для пагинации
cursorstringКурсор для потоковой пагинации

Ответ 200

typescript
type ListThreadsResponse = {
  data: Thread[]
  next_cursor: string | null
}

Получить тред

GET /threads/:thread_id

Ответ 200

typescript
type ThreadDetail = Thread & {
  person: {
    id: string
    name: string | null
    avatar_url: string | null
    external_id: string | null
  } | null
  stats: {
    messages_total: number
    user_messages: number
    bot_messages: number
  }
}

Отправить сообщение оператора

POST /threads/:thread_id/send

Отправляет сообщение от имени оператора. Тред должен быть в режиме manual.

Тело

typescript
type SendMessageBody = {
  text: string
  scheduledAt?: string  // отложенная доставка — ISO 8601
}

Получить рабочую память

GET /threads/:thread_id/memory

Возвращает текущую рабочую память агента для этого треда — факты, извлечённые из диалога.

Ответ 200

typescript
type WorkingMemoryResponse = {
  content: string | null  // блок памяти в формате Markdown
}

События в реальном времени (SSE)

Подпишитесь на обновления по всем тредам проекта:

GET /threads/events

Или по одному треду:

GET /threads/events/:thread_id

Формат события

typescript
type ThreadEvent = {
  thread_id: string
  type: 'pending_count' | 'mode_changed' | 'message_created'
  pending_count?: number
  mode?: string
}

Пример

typescript
const eventSource = new EventSource(
  'https://api.worken.ru/threads/events',
  { headers: { Authorization: `Bearer ${apiKey}` } }
)

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data) as ThreadEvent
  console.log(`Тред ${data.thread_id}: ${data.pending_count} ожидающих сообщений`)
}

Интеграции

Интеграции соединяют ботов с внешними платформами.

Типы

typescript
type IntegrationVendor =
  | 'telegram' | 'whatsapp' | 'vk' | 'ok' | 'max'
  | 'github' | 'google' | 'yandex'
  | 'amocrm' | 'bitrix' | 'avito'
  | 'sber' | 'worken'

type IntegrationStatus = 'active' | 'disabled' | 'error'

type Integration = {
  id: string
  name: string
  vendor: IntegrationVendor
  status: IntegrationStatus
  project_id: string
  created_at: string
  updated_at: string
}

Список интеграций

GET /integrations

Ответ 200Integration[]


Создать интеграцию

POST /integrations

Тело

typescript
type CreateIntegrationBody = {
  name: string
  vendor: IntegrationVendor
  auth_data: Record<string, unknown>  // учётные данные платформы
}

Примеры по платформам

typescript
// Telegram — токен бота
{ vendor: 'telegram', auth_data: { token: '7123456789:AAH...' } }

// amoCRM — OAuth (после получения токенов через /integrations/:id/oauth/start)
{ vendor: 'amocrm', auth_data: { subdomain: 'mycompany' } }

// ВКонтакте — токен сообщества
{ vendor: 'vk', auth_data: { access_token: 'vk1.a...' } }

Получить интеграцию

GET /integrations/:id

Ответ 200Integration


Обновить интеграцию

POST /integrations/:id

Тело

typescript
type UpdateIntegrationBody = {
  name?: string
  status?: IntegrationStatus
  auth_data?: Record<string, unknown>
  settings?: Record<string, unknown>
}

Удалить интеграцию

DELETE /integrations/:id

Получить профиль интеграции

GET /integrations/:id/profile

Проверяет, что сохранённые учётные данные действительны, и возвращает профиль аккаунта.

Ответ 200

typescript
type IntegrationProfile = {
  id: string
  name: string
  username?: string
  avatar_url?: string
}

OAuth-поток

Для интеграций с OAuth (amoCRM, Bitrix24, Google и др.):

POST /integrations/:id/oauth/start

Ответ 200

typescript
type OAuthStartResponse = {
  url: string  // перенаправьте пользователя сюда
}

После авторизации платформа делает редирект обратно, и учётные данные сохраняются автоматически.


Управление чатами интеграции

typescript
// Список чатов интеграции
GET  /integrations/:id/chats

// Создать чат
POST /integrations/:id/chats
// body: { bot_id: string, name: string, settings?: object }

// Обновить чат
POST /integrations/:id/chats/:chat_id

// Активировать / деактивировать
POST /integrations/:id/chats/:chat_id/status
// body: { status: 'active' | 'disabled' }

// Удалить
DELETE /integrations/:id/chats/:chat_id

Биллинг

Типы

typescript
type BillingAccount = {
  tariff: string
  credits: number   // основной баланс в кредитах
  bonus: number     // промо-кредиты
  subscription_until: string | null  // ISO 8601
}

type Transaction = {
  id: string
  type: 'charge' | 'topup' | 'bonus' | 'refund'
  amount: number
  description: string
  created_at: string
}

type Invoice = {
  id: string
  status: 'pending' | 'paid' | 'cancelled'
  amount: number
  payment_url: string | null
  created_at: string
}

Получить биллинговый аккаунт

GET /billing/account

Ответ 200BillingAccount


Получить баланс

GET /billing/balance

Ответ 200

typescript
type BalanceResponse = {
  credits: number
  bonus: number
}

Список транзакций

GET /billing/transactions

Параметрыlimit (по умолчанию 20), offset

Ответ 200

typescript
type ListTransactionsResponse = {
  data: Transaction[]
  total: number
}

Список счетов

GET /billing/invoices

Ответ 200Invoice[]


Создать счёт (пополнить баланс)

POST /billing/invoices

Тело

typescript
type CreateInvoiceBody = {
  offer_id: string
  credits?: number  // произвольная сумма пополнения
}

Ответ 200

typescript
type CreateInvoiceResponse = {
  invoice: Invoice
  payment_url: string
}

Тарифные предложения

GET /billing/offers

Возвращает доступные тарифные планы и разовые пополнения:

typescript
type BillingOffer = {
  id: string
  name: string
  price: number
  credits: number
  description: string
}

type ListOffersResponse = BillingOffer[]

Проекты и API-ключи

Список проектов

GET /projects

Ответ 200

typescript
type Project = {
  id: string
  name: string
  organization_id: string
  avatar_url: string | null
  created_at: string
}

type ListProjectsResponse = Project[]

Создать проект

POST /projects

Тело

typescript
type CreateProjectBody = {
  name: string
  organization_id: string
}

Создать API-ключ

POST /projects/:id/api-keys

Тело

typescript
type CreateApiKeyBody = {
  name: string
}

Ответ 200

typescript
type CreateApiKeyResponse = {
  id: string
  name: string
  key: string  // отображается только один раз — сохраните надёжно
  created_at: string
}

Список API-ключей

GET /projects/:id/api-keys

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

Ответ 200

typescript
type ApiKey = {
  id: string
  name: string
  last_used_at: string | null
  created_at: string
}

type ListApiKeysResponse = ApiKey[]

Удалить API-ключ

DELETE /projects/:id/api-keys/:key_id

Векторные хранилища (Базы знаний)

Worken предоставляет OpenAI-совместимый Vector Store API для подключения документов к агентам.

Типы

typescript
type VectorStore = {
  id: string
  name: string
  file_count: number
  status: 'ready' | 'indexing' | 'error'
  created_at: string
}

type VectorStoreFile = {
  id: string
  filename: string
  status: 'processed' | 'pending' | 'error'
  created_at: string
}

Эндпоинты

typescript
POST   /vector_stores                          // создать
GET    /vector_stores                          // список
GET    /vector_stores/:id                      // получить
POST   /vector_stores/:id                      // обновить
DELETE /vector_stores/:id                      // удалить
POST   /vector_stores/:id/files               // добавить файл
GET    /vector_stores/:id/files               // список файлов
GET    /vector_stores/:id/files/:file_id      // получить файл
DELETE /vector_stores/:id/files/:file_id      // удалить файл

Webhook-эндпоинты

Зарегистрируйте HTTP-эндпоинт для получения событий от Worken в реальном времени.

Типы

typescript
type WebhookEndpoint = {
  id: string
  url: string
  status: 'active' | 'disabled'
  created_at: string
}

type WebhookEvent = {
  id: string
  type: string   // например "thread.message.created"
  created_at: string
  data: Record<string, unknown>
}

Эндпоинты

typescript
GET    /webhook-endpoints         // список
POST   /webhook-endpoints         // создать  { url, secret }
PUT    /webhook-endpoints/:id     // обновить { status?, secret? }
DELETE /webhook-endpoints/:id     // удалить

Типы событий

СобытиеОписание
thread.createdНачался новый диалог
thread.message.createdНовое сообщение в треде
thread.mode.changedТред переключился в ручной / авто режим
integration.auth_lostИстекли учётные данные интеграции
billing.balance.lowБаланс кредитов ниже порогового значения

Проверка подписи

Worken подписывает каждый webhook-запрос с HMAC-SHA256 используя ваш secret:

typescript
import { createHmac } from 'node:crypto'

function verifyWebhook(body: string, signature: string, secret: string): boolean {
  const expected = createHmac('sha256', secret).update(body).digest('hex')
  return expected === signature
}

// В вашем обработчике:
app.post('/webhook', (req, res) => {
  const sig = req.headers['x-worken-signature'] as string
  if (!verifyWebhook(req.rawBody, sig, process.env.WORKEN_WEBHOOK_SECRET)) {
    return res.status(401).send('Неверная подпись')
  }
  // обработка события...
})

Коды ошибок

HTTP статусОшибкаОписание
400Bad RequestОтсутствует или неверное тело запроса
401UnauthorizedAPI-ключ отсутствует или неверен
403ForbiddenКлюч не имеет доступа к ресурсу
404Not FoundРесурс не существует
409ConflictРесурс уже существует (например, дублирующийся чат)
422Unprocessable EntityОшибка валидации — подробности в поле message
429Too Many RequestsПревышен лимит запросов — см. заголовок Retry-After
500Internal Server ErrorСерверная ошибка — обратитесь в поддержку

Руководство пользователя Worken AI