Skip to content

Node.js & TypeScript

The OpenAI npm package works with NexoAI by setting its baseURL. The same example runs as modern JavaScript or TypeScript.

Install the SDK

bash
npm install openai

Make a request

ts
import OpenAI from 'openai'

const gateway = process.env.OPENAI_BASE_URL ?? 'https://api.nexoai.ma'
const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  baseURL: `${gateway.replace(/\/$/, '')}/v1`
})

const completion = await client.chat.completions.create({
  model: 'gpt-5.4',
  messages: [
    {
      role: 'user',
      content: 'Give me a one-line definition of eventual consistency.'
    }
  ]
})

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

The fallback keeps the documented host visible while the credential remains mandatory. The SDK throws before making a request if OPENAI_API_KEY is missing.

Keep this on the server

Environment variables embedded by frontend build tools can become public. Run this client in Node.js, a serverless function, or another trusted backend—not in browser code.

Stream output

ts
const stream = await client.chat.completions.create({
  model: 'gpt-5.4',
  messages: [{ role: 'user', content: 'Name three useful HTTP headers.' }],
  stream: true
})

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

process.stdout.write('\n')

Fail clearly

ts
try {
  await client.chat.completions.create({
    model: 'gpt-5.4',
    messages: [{ role: 'user', content: 'ping' }]
  })
} catch (error) {
  if (error instanceof OpenAI.APIError) {
    console.error(`NexoAI request failed with status ${error.status}`)
  } else {
    throw error
  }
}

Use bounded retries with backoff for transient failures. Do not retry authentication, invalid-model, depleted-budget, or invalid-request errors in a tight loop; those require a configuration or wallet change.

One client, any catalog model

Change model to claude-opus-4-8, gemini-3-pro-preview, grok-4.5, deepseek-v4-flash, or qwen3-coder-next without changing the SDK setup.

Built for developers across MENA.