OpenAI-Compatible API

medium10 minopenai-compat.ts

Existing code uses the OpenAI SDK, or a chat UI such as Open WebUI. You want it to talk to your Cogitator agent without rewriting it.

What it shows

  • Register the agent with createOpenAIServer({ agents }): its name becomes the model
  • Point the official openai client at it and use Chat Completions or Responses

The code

openai-compat.ts
import { Agent, Cogitator, tool } from '@cogitator-ai/core';
import { createOpenAIServer } from '@cogitator-ai/openai-compat';
import OpenAI from 'openai';
import { z } from 'zod';

const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');

const multiply = tool({
  name: 'multiply',
  description: 'Multiply two numbers',
  parameters: z.object({ a: z.number(), b: z.number() }),
  execute: async ({ a, b }) => ({ product: a * b }),
});

const mathHelper = new Agent({
  name: 'math-helper',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are a math helper. Use the multiply tool for products. Be concise.',
  tools: [multiply],
});

const cog = new Cogitator({ llm: { providers: { google: { apiKey } } } });
const server = createOpenAIServer(cog, { port: 8080, agents: { 'math-helper': mathHelper } });
await server.start();

const openai = new OpenAI({ baseURL: 'http://localhost:8080/v1', apiKey: 'not-needed' });

try {
  const completion = await openai.chat.completions.create({
    model: 'math-helper',
    messages: [{ role: 'user', content: 'What is 42 * 17?' }],
  });
  console.log(completion.choices[0].message.content);

  const response = await openai.responses.create({ model: 'math-helper', input: 'And 12 * 12?' });
  console.log(response.output_text);
} finally {
  await server.stop();
  await cog.close();
}

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/openai-compat openai zod
EnvironmentGOOGLE_API_KEY
run · bash
GOOGLE_API_KEY=your-key npx tsx openai-compat.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/integrations/06-openai-compat.ts

Learn more