Cogitator
Integrations

OpenAI Compatibility

Serve Cogitator agents over the OpenAI Chat Completions and Responses APIs, so any OpenAI client talks to them.

Overview

The @cogitator-ai/openai-compat package runs an OpenAI-compatible server for your Cogitator agents. Register the agents, and every client that speaks the OpenAI API (the official SDKs, Open WebUI, LibreChat, LangChain, the Vercel AI SDK) uses them through POST /v1/chat/completions or POST /v1/responses, with the agent's name as the model.

pnpm add @cogitator-ai/openai-compat @cogitator-ai/core

The Assistants API is deprecated. OpenAI sunset it on 2026-08-26, and current clients use Chat Completions or Responses. The assistants, threads, runs and files endpoints keep working for existing integrations, see Assistants API (deprecated).

Quick Start

import { Agent, Cogitator } from '@cogitator-ai/core';
import { createOpenAIServer } from '@cogitator-ai/openai-compat';

const support = new Agent({
  name: 'support',
  model: 'openai/gpt-6-luna',
  instructions: 'You are the support agent of an online shop.',
  tools: [lookupOrder],
});

const server = createOpenAIServer(new Cogitator(), {
  port: 8080,
  agents: { support },
  apiKeys: ['sk-my-secret-key'],
});

await server.start();

Any OpenAI client then talks to the agent:

import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: 'sk-my-secret-key', baseURL: 'http://localhost:8080/v1' });

const completion = await openai.chat.completions.create({
  model: 'support',
  messages: [{ role: 'user', content: 'Where is order A-1?' }],
});

const response = await openai.responses.create({ model: 'support', input: 'Where is order A-1?' });
console.log(response.output_text);

In Open WebUI or LibreChat, add an OpenAI connection with http://localhost:8080/v1 and the key, and pick the agent from the model list.

Agents as models

agents maps model ids to agents, and GET /v1/models lists them (with the cogitator model of the Assistants API). A model that names no agent answers 404 with code model_not_found.

Each request runs the agent with its own instructions first and the client's system / developer messages (or the Responses instructions) after them, the request's temperature, top_p, token limit, stop and response format, and its own tools plus the functions the client declares. The client's conversation is replayed to the agent (the last user message is the input, the turns before it a transcript), so the APIs stay stateless and nothing is written to the agent's memory. Only the images of the last user message reach the model.

Client functions

Functions the client declares in tools become tools of the turn. When the model calls one, the turn ends with the call (finish_reason: 'tool_calls', or a function_call output item) and the run waits. When the client sends the outputs for every call (tool messages, or function_call_output items), the same run goes on from where it stopped. The call ids are generated by the server, so only the client that got them can answer. A run waits 10 minutes, or until 1000 newer runs wait, and outputs for a run that no longer waits are replayed to the agent as part of the conversation instead.

Agent tools that need an approval nobody gives (guardrails.onToolApproval) are not run, and the model is told so. tool_choice: 'none' runs without tools. required and a named function are passed to the run as its toolChoice, so the model must call a tool (or that function) before it answers, and the run goes back to auto once it has.

Chat Completions

const stream = await openai.chat.completions.create({
  model: 'support',
  messages: [
    { role: 'system', content: 'Answer in one sentence.' },
    { role: 'user', content: 'Where is order A-1?' },
  ],
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta.content ?? '');
}

messages takes system, developer, user (text and image_url parts), assistant (text and tool_calls) and tool messages. Supported parameters: stream and stream_options.include_usage, tools, tool_choice, parallel_tool_calls, temperature, top_p, max_completion_tokens (or max_tokens), stop, response_format (text, json_object, json_schema), and n: 1. Others are ignored.

finish_reason is stop, tool_calls, length when the answer hit the token limit, or content_filter when the provider withheld it, and a refusal comes back in message.refusal. usage includes prompt_tokens_details.cached_tokens and completion_tokens_details.reasoning_tokens. A stream sends the role, the content deltas, the tool calls, the chunk with the finish reason, the usage chunk with include_usage, then [DONE].

Responses

const first = await openai.responses.create({
  model: 'support',
  instructions: 'Answer in one sentence.',
  input: 'Where is order A-1?',
});

const next = await openai.responses.create({
  model: 'support',
  previous_response_id: first.id,
  input: 'And order B-2?',
});

const stream = openai.responses.stream({ model: 'support', input: 'Summarize our talk' });
stream.on('response.output_text.delta', (event) => process.stdout.write(event.delta));
const final = await stream.finalResponse();

input is a string or a list of message items (input_text, input_image with image_url, output_text), function_call and function_call_output items. Supported parameters: instructions (for this response only), previous_response_id, function tools, tool_choice, parallel_tool_calls, temperature, top_p, max_output_tokens, text.format (text, json_object, json_schema), store, stream and metadata. Built-in tools, background and file inputs are refused with 400.

A streamed response sends response.created, response.in_progress, the output item events (response.output_item.added, response.content_part.added, response.output_text.delta / .done, response.content_part.done, response.function_call_arguments.delta / .done, response.output_item.done) and ends with response.completed, response.incomplete or response.failed, each event with its sequence_number. A response cut by max_output_tokens is incomplete with incomplete_details.reason: 'max_output_tokens' (content_filter when the provider withheld it).

Responses are kept in memory (maxStoredResponses, default 1000) for previous_response_id, GET /v1/responses/{id}, GET /v1/responses/{id}/input_items and DELETE /v1/responses/{id}, unless store: false. previous_response_id carries the conversation on, not the earlier instructions.

OpenAIServer

The server is built on Fastify:

const server = new OpenAIServer(cogitator, config);
await server.start();

console.log(server.getBaseUrl());
console.log(server.isRunning());

await server.stop();

OpenAIServerConfig

OptionTypeDefaultDescription
portnumber8080Port to listen on
hoststring'127.0.0.1'Host to bind to, a public host needs apiKeys
apiKeysstring[][]API keys for auth, scoping threads and runs (empty = no auth)
allowUnauthenticatedPublicAccessbooleanfalseServe a public host without apiKeys, behind a gateway that authenticates
agentsRecord<string, Agent>{}Agents served by Chat Completions and Responses, by model id
maxRequestBodyBytesnumber20 MBBody limit of /v1/chat/completions and /v1/responses
maxStoredResponsesnumber1000Responses kept for previous_response_id and GET
sseHeartbeatMsnumber5000Heartbeat comment interval on streams, 0 turns it off
toolsTool[][]Cogitator tools available to all Assistants API runs
defaultModelstring-Model the Assistants API uses for the cogitator model id
storageThreadStoragein-memoryAssistants API persistence backend (connect it first)
maxFileSizenumber512 MBUpload limit for POST /v1/files
loggingbooleanfalseEnable request logging via pino (JSON)
cors{ origin, methods }noneOrigins browsers may call from, without it no cross-origin page can

The server binds 127.0.0.1 unless told otherwise. Without apiKeys anyone who reaches it can run the agents (and create assistants that run the server's tools), so start() refuses a public host (0.0.0.0, ::, an external address) unless apiKeys are set or allowUnauthenticatedPublicAccess: true says a gateway authenticates callers. CORS is off until cors.origin names the origins that may call from a browser.

start() waits for plugin registration, so it can be called right after construction. With port: 0 the OS picks a port and getUrl() / getBaseUrl() report the bound one. /health stays public when apiKeys are set. When a client disconnects, its agent run is aborted.

Authentication and Errors

With apiKeys, every request except GET /health needs Authorization: Bearer <key>, and a missing or unknown key answers 401 with code invalid_api_key.

Threads and runs belong to the key that created them. The server keeps the sha256 digest of the key with each thread (never the key itself) and with each run, and another key gets 404 not_found for that thread, its messages, its runs and their steps, the answer an unknown id gets, so it cannot tell the thread exists. Threads stored before this scoping have no owner and stay reachable by every key, while the runs created on them still belong to their key. Assistants, files and stored responses are shared by every key, and runs carry no userId, so give each tenant its own server (or storage) when those must stay apart too.

Errors use OpenAI's shape, { "error": { "message", "type", "param", "code" } }: invalid_request (400, with the parameter at fault in param), invalid_api_key (401), permission_denied (403), not_found and model_not_found (404), rate_limit_exceeded (429) and otherwise server_error / internal_error. Every 5xx answer says Internal server error and the details are only logged, unless the cause is a CogitatorError. A Chat Completions stream that fails ends with an error object, a Responses stream with response.failed. Requests the Assistants adapter refuses throw InvalidRequestError (exported from the package), which the server answers as 400 invalid_request. A run that fails ends with status: 'failed' and last_error: { code: 'server_error', message }.

Supported Endpoints

MethodEndpointDescription
GET/v1/modelsRegistered agents and the cogitator model
GET/v1/models/:idOne model
POST/v1/chat/completionsChat completion (SSE with stream: true)
POST/v1/responsesCreate a response (SSE with stream: true)
GET/v1/responses/:idGet a stored response
GET/v1/responses/:id/input_itemsInput items of a stored response
DELETE/v1/responses/:idDelete a stored response

Assistants API (deprecated)

The assistants, threads, messages, runs and files endpoints keep working for existing integrations. They run assistants the client creates, not the registered agents: assistant model values are Cogitator model strings (gpt-6.1-sol uses the default provider, ollama/llama3.2 selects one explicitly), and the cogitator id maps to the server's defaultModel.

const assistant = await openai.beta.assistants.create({
  model: 'gpt-6.1-sol',
  name: 'My Assistant',
  instructions: 'You are a helpful assistant with access to tools.',
});

const thread = await openai.beta.threads.create();
await openai.beta.threads.messages.create(thread.id, { role: 'user', content: 'What is 12 * 12?' });

const run = await openai.beta.threads.runs.createAndPoll(thread.id, { assistant_id: assistant.id });
const messages = await openai.beta.threads.messages.list(thread.id); // newest first
MethodEndpointDescription
POST/v1/assistantsCreate assistant
GET/v1/assistantsList assistants
GET/v1/assistants/:idGet assistant
POST/v1/assistants/:idUpdate assistant
DELETE/v1/assistants/:idDelete assistant
POST/v1/threadsCreate thread
POST/v1/threads/runsCreate thread and run
GET/v1/threads/:idGet thread
POST/v1/threads/:idUpdate thread metadata
DELETE/v1/threads/:idDelete thread
POST/v1/threads/:id/messagesAdd message
GET/v1/threads/:id/messagesList messages
GET/v1/threads/:id/messages/:midGet message
POST/v1/threads/:id/runsCreate run
GET/v1/threads/:id/runsList runs
GET/v1/threads/:id/runs/:ridGet run status
POST/v1/threads/:id/runs/:rid/cancelCancel run
POST/v1/threads/:id/runs/:rid/submit_tool_outputsSubmit tool outputs
GET/v1/threads/:id/runs/:rid/stepsList run steps (limit, order, after, before)
GET/v1/threads/:id/runs/:rid/steps/:sidGet run step
POST/v1/filesUpload file
GET/v1/filesList files (?purpose=, limit, order, after)
GET/v1/files/:idGet file metadata
GET/v1/files/:id/contentDownload file
DELETE/v1/files/:idDelete file

GET /v1/files takes limit (1-10 000, default 10 000), order (asc / desc, default desc) and after.

OpenAIAdapter (Assistants API, deprecated)

For in-process usage without a network server, use OpenAIAdapter directly. It provides the same Assistants API as programmatic methods:

import { createOpenAIAdapter } from '@cogitator-ai/openai-compat';

const adapter = createOpenAIAdapter(cog, { tools: [calculator] });

const assistant = await adapter.createAssistant({
  model: 'gpt-6.1-sol',
  name: 'Math Helper',
  instructions: 'Help with math problems.',
});

const thread = await adapter.createThread();

await adapter.addMessage(thread.id, {
  role: 'user',
  content: 'What is 15! (factorial)?',
});

const run = await adapter.createRun(thread.id, {
  assistant_id: assistant.id,
});

Runs see the whole thread (earlier messages are replayed to the agent), are aborted on cancel, and honour additional_instructions, response_format, max_completion_tokens, top_p, tool_choice (none or a specific function), parallel_tool_calls and truncation_strategy. max_prompt_tokens is best-effort (about 4 characters per token, instructions included): the oldest replayed messages are dropped until the prompt fits, and a run whose last user message alone does not fit ends incomplete with incomplete_details.reason: 'max_prompt_tokens'. A run whose answer stopped at the output token limit (max_completion_tokens, or the model's own) ends incomplete with incomplete_details.reason: 'max_completion_tokens', not completed, and its answer is kept as a message with status: 'incomplete' and incomplete_details.reason: 'max_tokens', so a client never takes a cut-off answer for a finished one. A thread can have one active run at a time (a second createRun returns HTTP 400), and cancelling a run that has already finished returns HTTP 400. Messages are listed in insertion order (order: 'desc', the default, returns the newest first). Image parts are passed to the model.

Function Calling

Assistant tools of type function are executed by the API client. When the model calls one, the run moves to requires_action; submit the outputs to resume (runs expire after 10 minutes without outputs). Server-side tools run inside Cogitator and do not need to be declared on the assistant.

let run = await openai.beta.threads.runs.createAndPoll(thread.id, { assistant_id });

if (run.status === 'requires_action') {
  const calls = run.required_action!.submit_tool_outputs.tool_calls;
  run = await openai.beta.threads.runs.submitToolOutputsAndPoll(run.id, {
    thread_id: thread.id,
    tool_outputs: calls.map((call) => ({
      tool_call_id: call.id,
      output: JSON.stringify(myFunctions[call.function.name](JSON.parse(call.function.arguments))),
    })),
  });
}

Server-side tools that need approval (requiresApproval, or the guardrails) come to the client the same way, as calls of functions it never declared: the run waits in requires_action instead of completing without them. The output decides the call: {"approved": true} (or approve) runs it, {"approved": false, "reason": "..."} declines it with the reason, and any other text declines it with that text, so nothing ambiguous runs a server tool. A configured guardrails.onToolApproval decides server tools itself and they never reach the client. While the run waits it is paused rather than running, so the run timeout (limits.defaultTimeout, 120 s by default) does not count the client's time: only expires_at (10 minutes per wait) does.

Run Steps

Each run records its steps like the OpenAI API: a tool_calls step per model turn that called tools (each call with its name, arguments and output), and a message_creation step pointing at each assistant message (message_id). A turn that writes text and then calls a tool stores that text as its own message before the tool_calls step opens, so steps never overlap and the stored messages match the streamed text. Runs with and without stream: true store the same messages and steps. A step whose calls wait on the client stays in_progress during requires_action and completes with the submitted outputs. Steps carry unix-second timestamps and the usage of the model call behind them when the agent run reports it. When a run is cancelled, expires or fails, its open steps end cancelled, expired or failed (with the run's last_error), and a message it had started streaming is kept as incomplete.

const steps = await openai.beta.threads.runs.steps.list(run.id, { thread_id: thread.id });
// in-process: adapter.listRunSteps(thread.id, run.id), adapter.getRunStep(thread.id, run.id, stepId)

Steps live in memory with their run and are dropped with it (maxStoredRuns).

Streaming Runs

Pass stream: true to stream OpenAI-style events (thread.run.*, thread.run.step.*, thread.message.created|delta|completed|incomplete, done). Step events open each step before its message events, and a tool_calls step gets one thread.run.step.delta per call, so SDK helpers such as toolCallCreated work. thread.message.completed goes out once the message is stored, so a client that reads the message on that event finds it, and a run reaches requires_action only once the messages before the pause are stored. A store that fails, or a thread deleted while the run writes to it, fails the run: that message ends incomplete with run_failed and its message_creation step failed. With the SDK use runs.stream(...) / submitToolOutputsStream(...). In-process, iterate the run's event log:

const run = await adapter.createRun(thread.id, {
  assistant_id: assistant.id,
  stream: true,
});

for await (const { event, data } of adapter.streamRunEvents(run.id)) {
  if (event === 'thread.message.delta' && typeof data !== 'string' && 'delta' in data) {
    for (const part of data.delta.content ?? []) {
      if (part.type === 'text') process.stdout.write(part.text?.value ?? '');
    }
  }
}

A stream ends with done when the run finishes or pauses on requires_action.

Thread Storage

By default, threads and messages are stored in memory. For production, plug in Redis or PostgreSQL:

import { RedisThreadStorage, createOpenAIServer } from '@cogitator-ai/openai-compat';

const storage = new RedisThreadStorage({
  url: 'redis://localhost:6379',
  keyPrefix: 'cogitator:',
  ttl: 86400,
});
await storage.connect();

const server = createOpenAIServer(cog, { storage, defaultModel: 'openai/gpt-6.1-sol' });
// or in-process: createOpenAIAdapter(cog, { storage })

Storage is the single source of truth (no per-process cache), so several server instances can share it. Runs are not stored: they live in the process that created them, so with several instances route each thread to the same one (sticky routing). ioredis and pg are optional peer dependencies loaded on connect(); Redis ttl: 0 disables expiry.

Or use the factory function:

import { createThreadStorage } from '@cogitator-ai/openai-compat';

const storage = createThreadStorage({
  type: 'postgres',
  connectionString: 'postgresql://user:pass@localhost/mydb',
  tableName: 'assistant_threads',
});
await storage.connect?.();

Listing threads

The OpenAI API has no route that lists threads, and neither does the server. Operators list them from the storage, a page at a time, newest first, optionally for one key:

import { apiKeyOwner } from '@cogitator-ai/openai-compat';

const page = await storage.listThreads({ owner: apiKeyOwner('sk-key1'), limit: 50 });
const next = await storage.listThreads({ owner: apiKeyOwner('sk-key1'), cursor: page.nextCursor });

owner: null lists the threads stored before key scoping. PostgreSQL filters, orders and limits in SQL on an index it creates on connect(). Redis has no index over its thread keys, so each page reads every thread (SCAN + MGET): keep it for occasional listings.

Storage Options

BackendPackage RequiredConfig
In-memory(none){ type: 'memory' }
Redisioredis{ type: 'redis', url, keyPrefix, ttl }
PostgreSQLpg{ type: 'postgres', connectionString }

Full Example: Migration from OpenAI

An app built on the OpenAI SDK moves to a Cogitator agent by changing the baseURL and the model:

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.COGITATOR_API_KEY,
  baseURL: process.env.COGITATOR_URL + '/v1',
});

const completion = await openai.chat.completions.create({
  model: 'sentiment',
  messages: [
    {
      role: 'user',
      content: 'Analyze the sentiment of this review: "Absolutely loved this product!"',
    },
  ],
});

console.log(completion.choices[0].message.content);

The sentiment agent keeps its instructions, model and tools on the server, the client only names it.

On this page