CanalAPI
Examples

JavaScript

Use CanalAPI from Node.js with the official OpenAI SDK.

CanalAPI is wire-compatible with the OpenAI HTTP API, so the official openai Node SDK works directly.

Install

npm install openai
# or
pnpm add openai

Hello world

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.CANALAPI_API_KEY,
  baseURL: process.env.CANALAPI_BASE_URL,
});

const r = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Hello' }],
});
console.log(r.choices[0].message.content);

Streaming with async iteration

const stream = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  stream: true,
  messages: [{ role: 'user', content: 'Stream a short poem.' }],
});

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

Robust error handling

import OpenAI, { APIError } from 'openai';

const client = new OpenAI({
  apiKey: process.env.CANALAPI_API_KEY,
  baseURL: process.env.CANALAPI_BASE_URL,
});

async function ask(prompt: string, attempt = 0): Promise<string> {
  try {
    const r = await client.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: prompt }],
    });
    return r.choices[0].message.content ?? '';
  } catch (e) {
    if (e instanceof APIError && [429, 500, 502, 503, 504].includes(e.status ?? 0) && attempt < 4) {
      const delay = Math.min(1000 * 2 ** attempt, 8000) * (0.75 + Math.random() * 0.5);
      await new Promise((r) => setTimeout(r, delay));
      return ask(prompt, attempt + 1);
    }
    throw e;
  }
}

Using in Next.js

Always call CanalAPI from a server route — never from a Client Component. A typical pattern is an App Router Route Handler:

// app/api/chat/route.ts
import OpenAI from 'openai';

export const runtime = 'nodejs';

const client = new OpenAI({
  apiKey: process.env.CANALAPI_API_KEY,
  baseURL: process.env.CANALAPI_BASE_URL,
});

export async function POST(req: Request) {
  const { prompt } = await req.json();
  const r = await client.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: prompt }],
  });
  return Response.json({ text: r.choices[0].message.content });
}

On this page