> ## Documentation Index
> Fetch the complete documentation index at: https://www.edenai.co/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use the OpenAI TS/JS SDK with Eden AI

> Call Eden AI with the official OpenAI TypeScript SDK: set the base URL, stream chat completions, send images and files, and handle API errors.

**Use the OpenAI TS/JS SDK with Eden AI**

Call Eden AI with the official OpenAI TypeScript SDK: set the base URL, stream chat completions, send images and files, and handle API errors.

Eden AI's V3 chat endpoint accepts OpenAI SDK requests unchanged. Your code changes in three places: `baseURL`, the API key and the model id.

## Overview

Point the OpenAI TypeScript SDK at Eden AI and it can call any of the 500+ models.

## Installation

Install the OpenAI SDK for Node.js. The Environment Variables section below also uses `dotenv`, which you install the same way (`npm install dotenv`):

```bash npm theme={null}
npm install openai
```

```bash yarn theme={null}
yarn add openai
```

```bash pnpm theme={null}
pnpm add openai
```

## Quick Start

Configure the client to use Eden AI:

```typescript TypeScript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://api.edenai.run/v3',
});

async function main() {
  const stream = await client.chat.completions.create({
    model: 'openai/gpt-latest',
    messages: [{ role: 'user', content: 'Hello! How are you?' }],
    stream: true,
  });

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

main();
```

```javascript JavaScript (ESM) theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://api.edenai.run/v3',
});

const stream = await client.chat.completions.create({
  model: 'vertex/gemini-flash-latest',
  messages: [{ role: 'user', content: 'Hello!' }],
  stream: true,
});

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

```javascript JavaScript (CommonJS) theme={null}
const OpenAI = require('openai');

const client = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://api.edenai.run/v3',
});

async function main() {
  const stream = await client.chat.completions.create({
    model: 'openai/gpt-latest',
    messages: [{ role: 'user', content: 'Hello!' }],
    stream: true,
  });

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

main();
```

## Model naming

Models use the `provider/model` format, for example `openai/gpt-latest`, `anthropic/claude-sonnet-latest` or `vertex/gemini-flash-latest`. See [Listing Models](https://www.edenai.co/docs/v3/llms/listing-models.md) for the full catalog.

## Multi-Turn Conversations

Build stateful chat applications:

```typescript TypeScript theme={null}
import OpenAI from 'openai';
import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';

const client = new OpenAI({
  apiKey: process.env.EDEN_AI_API_KEY!,
  baseURL: 'https://api.edenai.run/v3',
});

async function chat() {
  const messages: ChatCompletionMessageParam[] = [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'What is the capital of France?' },
  ];

  // First interaction
  const stream1 = await client.chat.completions.create({
    model: 'vertex/gemini-flash-latest',
    messages,
    stream: true,
  });

  let assistantResponse = '';
  for await (const chunk of stream1) {
    const content = chunk.choices[0]?.delta?.content;
    if (content) {
      process.stdout.write(content);
      assistantResponse += content;
    }
  }

  // Add to conversation history
  messages.push({ role: 'assistant', content: assistantResponse });
  messages.push({ role: 'user', content: "What's the population?" });

  // Continue conversation
  const stream2 = await client.chat.completions.create({
    model: 'vertex/gemini-flash-latest',
    messages,
    stream: true,
  });

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

chat();
```

## Advanced Parameters

Control model behavior:

```typescript TypeScript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.EDEN_AI_API_KEY!,
  baseURL: 'https://api.edenai.run/v3',
});

const stream = await client.chat.completions.create({
  model: 'openai/gpt-latest',
  messages: [
    { role: 'user', content: 'Write a creative story about AI.' },
  ],
  temperature: 0.9,        // Higher = more creative (0-2)
  max_tokens: 500,         // Limit response length
  top_p: 0.9,              // Nucleus sampling
  stream: true,
});

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

## Vision

Send an image as an `image_url` content part, the same shape the OpenAI API uses. The URL can be a public `http(s)` link or a base64 data URL:

```typescript TypeScript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.EDEN_AI_API_KEY!,
  baseURL: 'https://api.edenai.run/v3',
});

const stream = await client.chat.completions.create({
  model: 'openai/gpt-latest',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: "What's in this image?" },
        {
          type: 'image_url',
          image_url: { url: 'https://www.edenai.co/docs/images/hero-light.png' },
        },
      ],
    },
  ],
  stream: true,
});

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

To send a local file inline, encode it as a data URL: `data:image/jpeg;base64,...`.

### Uploaded files

For documents such as PDFs, or to reuse one file across requests, upload it to `/v3/upload` and pass the returned `file_id` in a `file` content part. [File Attachments](https://www.edenai.co/docs/v3/llms/file-upload.md) covers file types, limits and expiry. This sample uses the `fetch`, `FormData` and `Blob` globals of Node 18 and later, so it needs no extra install:

```typescript TypeScript theme={null}
import OpenAI from 'openai';
import { readFile } from 'node:fs/promises';

const client = new OpenAI({
  apiKey: process.env.EDEN_AI_API_KEY!,
  baseURL: 'https://api.edenai.run/v3',
});

async function summarizeDocument() {
  // First, upload the document
  const formData = new FormData();
  formData.append('file', new Blob([await readFile('document.pdf')]), 'document.pdf');

  const uploadResponse = await fetch('https://api.edenai.run/v3/upload', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.EDEN_AI_API_KEY}`,
    },
    body: formData,
  });

  const { file_id } = (await uploadResponse.json()) as { file_id: string };

  // Use file_id in chat
  const stream = await client.chat.completions.create({
    model: 'openai/gpt-latest',
    messages: [
      {
        role: 'user',
        content: [
          { type: 'text', text: 'Summarize this document.' },
          { type: 'file', file: { file_id } },
        ],
      },
    ],
    stream: true,
  });

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

summarizeDocument();
```

## Error Handling

The SDK retries 429 and 5xx responses twice by default (set `maxRetries` on the client to change it), so the 429 branch below runs only after those retries are used up. The SDK has a dedicated error class for some statuses (401, 403, 429) but not for 402 or 451, so branch on `error.status`. Eden AI answers a failed request with these statuses:

* 400: the model id is unknown or inactive (`Model(s) not found or inactive`).
* 401: the key is invalid (`Invalid API key` or `Invalid token`) or has expired (`Custom token has expired.`).
* 402: insufficient credits.
* 403: the account has no organization, a guardrail policy blocks the model, or your organization's [compliance policy](https://www.edenai.co/docs/v3/data-governance/compliance-policies.md) requires zero data retention and no provider of the model qualifies.
* 422: the request body is invalid.
* 429: rate limit.
* 451: no provider of the model runs in a region that the endpoint you called, or your organization's [compliance policy](https://www.edenai.co/docs/v3/data-governance/compliance-policies.md), allows. It also answers when every target of a [routing policy](https://www.edenai.co/docs/v3/llms/routing-policies.md) was dropped for region.

```typescript TypeScript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.EDEN_AI_API_KEY!,
  baseURL: 'https://api.edenai.run/v3',
});

async function safeChat() {
  try {
    const stream = await client.chat.completions.create({
      model: 'openai/gpt-latest',
      messages: [{ role: 'user', content: 'Hello!' }],
      stream: true,
    });

    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content;
      if (content) {
        process.stdout.write(content);
      }
    }
  } catch (error) {
    if (error instanceof OpenAI.APIError) {
      console.error(`API Error (${error.status}):`, error.message);

      if (error.status === 400 || error.status === 422) {
        console.error('Invalid request. Check the model id and the request body.');
      } else if (error.status === 401) {
        console.error('Authentication failed. The key is invalid or has expired.');
      } else if (error.status === 402) {
        console.error('Insufficient credits. Please add credits to your account.');
      } else if (error.status === 403) {
        console.error('Request refused: no organization, a guardrail policy, or a zero-data-retention policy blocks this model.');
      } else if (error.status === 429) {
        console.error('Rate limit exceeded, even after the SDK retries.');
      } else if (error.status === 451) {
        console.error('No provider of this model, or routing policy target, runs in an allowed region.');
      }
    } else {
      console.error('Unexpected error:', error);
    }
  }
}

safeChat();
```

## Environment Variables

Use `.env` files for configuration:

```bash .env theme={null}
EDEN_AI_API_KEY=your_api_key_here
```

```typescript TypeScript theme={null}
import 'dotenv/config';
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.EDEN_AI_API_KEY!,
  baseURL: 'https://api.edenai.run/v3',
});
```

## Next Steps

* [Streaming Responses](https://www.edenai.co/docs/v3/llms/streaming.md) - Handle Server-Sent Events
* [File Attachments](https://www.edenai.co/docs/v3/llms/file-upload.md) - Working with images and documents
* [Listing Models](https://www.edenai.co/docs/v3/llms/listing-models.md) - Browse the model catalog


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.