LLM Gatewaydocs

SDK Examples

The gateway is wire-compatible with the OpenAI API, so the official openai packages are the recommended SDKs. Point them at https://api.smartapihub.com/v1 with your sk-llm-… key. Nothing else to install.

Setup

bash
export LLM_API_KEY="sk-llm-…"
export LLM_GATEWAY="https://api.smartapihub.com"

Chat completion

bash
curl "$LLM_GATEWAY/v1/chat/completions" \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"openai/gpt-4o-mini","messages":[{"role":"user","content":"Explain SSE in one sentence."}]}'

Streaming with the SDK

typescript
const stream = await client.chat.completions.create({
  model: 'openai/gpt-4o-mini',
  stream: true,
  messages: [{ role: 'user', content: 'Write a haiku about routing.' }],
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
  if (chunk.usage) console.log('\ncost µ$', (chunk.usage as { x_llm_cost_micro?: number }).x_llm_cost_micro);
}

Raw HTTP streaming

Without an SDK, parse the SSE stream yourself. Skip : ping comment lines, stop on [DONE], and check each chunk for an error key.

typescript
const res = await fetch('https://api.smartapihub.com/v1/chat/completions', {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.LLM_API_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ model: 'openai/gpt-4o-mini', stream: true, messages: [{ role: 'user', content: 'Hi' }] }),
});
if (!res.ok) throw new Error(JSON.stringify(await res.json()));

const reader = res.body!.getReader();
const dec = new TextDecoder();
let buf = '';
outer: for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buf += dec.decode(value, { stream: true });
  let i: number;
  while ((i = buf.indexOf('\n\n')) >= 0) {
    const evt = buf.slice(0, i);
    buf = buf.slice(i + 2);
    for (const line of evt.split('\n')) {
      if (!line.startsWith('data: ')) continue;
      const payload = line.slice(6);
      if (payload === '[DONE]') break outer;
      const chunk = JSON.parse(payload);
      if (chunk.error) throw new Error(`${chunk.error.code}: ${chunk.error.message}`);
      process.stdout.write(chunk.choices?.[0]?.delta?.content ?? '');
    }
  }
}

Routing override with the SDK

Extra request fields are passed through by both SDKs:

typescript
await client.chat.completions.create({
  model: 'meta/llama-3.1-70b-instruct',
  messages,
  // @ts-expect-error platform extension not in the OpenAI types
  routing: { strategy: 'fastest', providers: ['groq'] },
});

Images with an idempotency key

typescript
const img = await client.images.generate(
  { model: 'openai/dall-e-3', prompt: 'A lighthouse in a storm', size: '1024x1024', response_format: 'url' },
  { headers: { 'Idempotency-Key': orderId } },
);
console.log(img.data[0].url); // signed URL, expires in ~1 h

Async video job (raw HTTP)

The OpenAI SDKs have no video-jobs client, so use plain HTTP:

typescript
const base = 'https://api.smartapihub.com/v1';
const headers = { Authorization: `Bearer ${process.env.LLM_API_KEY}`, 'Content-Type': 'application/json' };

const submit = await fetch(`${base}/video/generations`, {
  method: 'POST',
  headers: { ...headers, 'Idempotency-Key': crypto.randomUUID() },
  body: JSON.stringify({ model: 'vendor/video-model', prompt: 'Ocean waves at dawn', duration_seconds: 5 }),
});
if (submit.status !== 202) throw new Error(JSON.stringify(await submit.json()));
const { id } = await submit.json();

let job;
for (let delay = 2000; ; delay = Math.min(delay * 1.5, 30000)) {
  job = await (await fetch(`${base}/video/generations/${id}`, { headers })).json();
  if (['succeeded', 'failed', 'canceled', 'expired'].includes(job.status)) break;
  await new Promise((r) => setTimeout(r, delay));
}
if (job.status === 'succeeded') console.log(job.artifacts[0].url);
else console.error(job.status, job.error);

More