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

# OpenAI Provider

> Create and configure the OpenAI provider for chat, embeddings, and image generation

## Overview

The OpenAI provider gives you access to GPT-5 models, o-series reasoning models, embeddings, and image generation.

By default, `createOpenAI` uses the **Responses API**. For the Chat Completions API, use `createOpenAICompat` from `@core-ai/openai/compat`.

## Installation

```bash theme={null}
npm install @core-ai/openai
```

## createOpenAI()

Create an OpenAI provider instance using the Responses API.

```typescript theme={null}
import { createOpenAI } from '@core-ai/openai';

const openai = createOpenAI({
    apiKey: process.env.OPENAI_API_KEY,
});
```

### Options

<ParamField path="apiKey" type="string" optional>
  Your OpenAI API key. Defaults to `OPENAI_API_KEY` environment variable.
</ParamField>

<ParamField path="baseURL" type="string" optional>
  Custom base URL for API requests. Useful for proxies or OpenAI-compatible
  APIs.
</ParamField>

<ParamField path="client" type="OpenAI" optional>
  Provide your own configured OpenAI client instance.
</ParamField>

### Returns

`OpenAIProvider` with methods `chatModel()`, `embeddingModel()`, and `imageModel()`.

## createOpenAICompat()

Create an OpenAI provider instance using the Chat Completions API.

```typescript theme={null}
import { createOpenAICompat } from '@core-ai/openai/compat';

const openai = createOpenAICompat({
    apiKey: process.env.OPENAI_API_KEY,
});
```

Same options as `createOpenAI`. Returns `OpenAICompatProvider` with the same model factory methods.

Use `createOpenAICompat` when you need Chat Completions API compatibility, for example with third-party OpenAI-compatible endpoints.

## Provider methods

### chatModel()

```typescript theme={null}
const model = openai.chatModel('gpt-5-mini');
```

### embeddingModel()

```typescript theme={null}
const embeddings = openai.embeddingModel('text-embedding-3-large');
```

### imageModel()

```typescript theme={null}
const imageGen = openai.imageModel('gpt-image-1');
```

## Supported models

### Chat models

<AccordionGroup>
  <Accordion title="GPT-5 Series" icon="star">
    <ul>
      <li><strong>gpt-5.6-sol</strong> - Flagship model with max reasoning effort for complex agentic work</li>
      <li><strong>gpt-5.6-terra</strong> - Balanced everyday model with GPT-5.5-class performance at lower cost</li>
      <li><strong>gpt-5.6-luna</strong> - Fast and affordable model for high-volume tasks</li>
      <li><strong>gpt-5.5</strong> - Flagship model for complex reasoning and coding</li>
      <li><strong>gpt-5.5-pro</strong> - Pro model for demanding reasoning tasks</li>
      <li><strong>gpt-5.4</strong> - Frontier model with max reasoning effort</li>
      <li><strong>gpt-5.4-pro</strong> - Pro model with enhanced reasoning</li>
      <li><strong>gpt-5.4-mini</strong> - Efficient GPT-5.4-class model for high-volume workloads</li>
      <li><strong>gpt-5.4-nano</strong> - Lightweight GPT-5.4-class model for simple high-volume tasks</li>
      <li><strong>gpt-5.3-codex</strong> - Agentic coding model</li>
      <li><strong>gpt-5.2</strong> - Flagship with reasoning control</li>
      <li><strong>gpt-5.2-codex</strong> - Optimized for code generation</li>
      <li><strong>gpt-5.2-pro</strong> - Enhanced reasoning capabilities</li>
      <li><strong>gpt-5.1</strong> - Previous generation flagship</li>
      <li><strong>gpt-5</strong> - Balanced performance and cost</li>
      <li><strong>gpt-5-pro</strong> - Pro model with high-only reasoning effort</li>
      <li><strong>gpt-5-mini</strong> - Fast and efficient</li>
      <li><strong>gpt-5-nano</strong> - Lightweight model</li>
    </ul>
  </Accordion>

  <Accordion title="o-Series (Reasoning Models)" icon="brain">
    <ul>
      <li><strong>o4-mini</strong> - Compact reasoning model</li>
      <li><strong>o3-pro</strong> - o3 model with more compute for harder reasoning tasks</li>
      <li><strong>o3</strong> - Advanced reasoning capabilities</li>
      <li><strong>o3-mini</strong> - Efficient reasoning model</li>
      <li><strong>o1</strong> - First-generation reasoning model</li>
      <li><strong>o1-mini</strong> - Compact reasoning model with no effort control</li>
    </ul>
  </Accordion>
</AccordionGroup>

<Note>
  Any valid OpenAI chat model ID is accepted. The models above are the ones
  with explicit capability handling in core-ai.
</Note>

### Embedding models

* **text-embedding-3-large** - 3072 dimensions, highest quality
* **text-embedding-3-small** - 1536 dimensions, faster and cheaper
* **text-embedding-ada-002** - Legacy embedding model

### Image models

* **gpt-image-2** - Image generation model
* **gpt-image-1** - Image generation model used throughout the docs examples

## Examples

### Basic chat

```typescript theme={null}
import { createOpenAI } from '@core-ai/openai';
import { generate } from '@core-ai/core-ai';

const openai = createOpenAI();

const result = await generate({
    model: openai.chatModel('gpt-5-mini'),
    messages: [
        { role: 'user', content: 'Explain quantum computing in simple terms' },
    ],
});

console.log(result.content);
```

### Reasoning with effort control

```typescript theme={null}
const result = await generate({
    model: openai.chatModel('gpt-5.4'),
    messages: [
        { role: 'user', content: 'Solve this complex mathematical proof...' },
    ],
    reasoning: {
        effort: 'max',
    },
});
```

### Embeddings

```typescript theme={null}
import { embed } from '@core-ai/core-ai';

const result = await embed({
    model: openai.embeddingModel('text-embedding-3-large'),
    input: 'Search query text',
});

console.log(result.embeddings[0]);
```

### Image generation

```typescript theme={null}
import { generateImage } from '@core-ai/core-ai';

const result = await generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt: 'A futuristic city at sunset',
    size: '1024x1024',
});

console.log(result.images);
```

### Custom base URL

```typescript theme={null}
const openai = createOpenAI({
    apiKey: 'your-api-key',
    baseURL: 'https://your-proxy.com/v1',
});
```

## Reasoning support

Inspect model capabilities before enabling reasoning:

```typescript theme={null}
import { clampReasoningEffort, generate } from '@core-ai/core-ai';
import { createOpenAI, getOpenAIModelCapabilities } from '@core-ai/openai';

const openai = createOpenAI();
const model = openai.chatModel('gpt-5.2');

if (model.capabilities.reasoning.supported) {
    const effort = clampReasoningEffort(
        'medium',
        model.capabilities.reasoning.supportedEfforts
    );
    const temperature = model.capabilities.reasoning.restrictsSamplingParams
        ? undefined
        : 0.7;

    await generate({
        model,
        messages: [{ role: 'user', content: 'Think carefully.' }],
        reasoning: { effort },
        temperature,
    });
}

// Or look up capabilities without constructing a ChatModel:
const capabilities = getOpenAIModelCapabilities('gpt-5.2');
```

Reasoning support depends on the selected model family:

| Models                                                                                                           | Supported effort levels            |
| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| `gpt-5.6-sol`                                                                                                    | `low`, `medium`, `high`, `max`     |
| `gpt-5.6-terra`                                                                                                  | `low`, `medium`, `high`            |
| `gpt-5.6-luna`                                                                                                   | `minimal`, `low`, `medium`, `high` |
| `gpt-5.5`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-5.3-codex`, `gpt-5.2`, `gpt-5.2-codex`, `gpt-5.2-pro` | `low`, `medium`, `high`, `max`     |
| `gpt-5.5-pro`, `gpt-5.4-pro`                                                                                     | `medium`, `high`, `max`            |
| `gpt-5-pro`                                                                                                      | `high`                             |
| `gpt-5.1`                                                                                                        | `low`, `medium`, `high`            |
| `gpt-5`, `gpt-5-mini`, `gpt-5-nano`                                                                              | `minimal`, `low`, `medium`, `high` |
| `o3-pro`                                                                                                         | `low`, `medium`, `high`, `max`     |
| `o3`, `o3-mini`, `o4-mini`, `o1`                                                                                 | `low`, `medium`, `high`            |
| `o1-mini`                                                                                                        | No effort control                  |

<Warning>
  When `capabilities.reasoning.restrictsSamplingParams` is `true` (GPT-5
  family models), the adapter throws if you set `temperature` or `topP` while
  reasoning is enabled.
</Warning>

### Reasoning metadata

When reasoning is enabled on the Responses API, core-ai automatically requests encrypted reasoning content and exposes it through provider metadata.

```typescript theme={null}
import { generate, getProviderMetadata } from '@core-ai/core-ai';
import type { OpenAIReasoningMetadata } from '@core-ai/openai';

const result = await generate({
    model: openai.chatModel('gpt-5.4'),
    messages: [{ role: 'user', content: 'Think carefully before answering.' }],
    reasoning: { effort: 'high' },
});

for (const part of result.parts) {
    if (part.type !== 'reasoning') continue;

    const metadata = getProviderMetadata<OpenAIReasoningMetadata>(
        part.providerMetadata,
        'openai'
    );

    console.log(metadata?.encryptedContent);
}
```

## Provider-specific options

Options are namespaced under `openai` in `providerOptions` and validated with Zod schemas.

### Generate options (Responses API)

```typescript theme={null}
import { generate } from '@core-ai/core-ai';

const result = await generate({
    model: openai.chatModel('gpt-5-mini'),
    messages: [{ role: 'user', content: 'Hello' }],
    providerOptions: {
        openai: {
            store: true,
            serviceTier: 'auto',
            parallelToolCalls: true,
            user: 'user-123',
        },
    },
});
```

Available fields: `store`, `serviceTier` (`'auto'` | `'default'` | `'flex'` | `'scale'` | `'priority'`), `include`, `parallelToolCalls`, `user`.

<Note>
  Responses requests default to `store: false`. If reasoning is enabled,
  core-ai also ensures `reasoning.encrypted_content` is included
  automatically.
</Note>

### Generate options (Chat Completions API)

When using `createOpenAICompat`, the available options differ:

```typescript theme={null}
import { createOpenAICompat } from '@core-ai/openai/compat';
import { generate } from '@core-ai/core-ai';

const openai = createOpenAICompat();

const result = await generate({
    model: openai.chatModel('gpt-5-mini'),
    messages: [{ role: 'user', content: 'Hello' }],
    providerOptions: {
        openai: {
            store: true,
            serviceTier: 'auto',
            parallelToolCalls: true,
            stopSequences: ['\n\n'],
            frequencyPenalty: 0.5,
            presencePenalty: 0.3,
            seed: 42,
            user: 'user-123',
        },
    },
});
```

<Note>
  Chat Completions uses `reasoning_effort` instead of the Responses API
  reasoning payload shape. The compat options do not support the `include`
  field.
</Note>

### Embed options

```typescript theme={null}
const result = await embed({
    model: openai.embeddingModel('text-embedding-3-small'),
    input: 'text to embed',
    providerOptions: {
        openai: {
            encodingFormat: 'float',
            user: 'user-123',
        },
    },
});
```

### Image options

```typescript theme={null}
const result = await generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt: 'A cat',
    providerOptions: {
        openai: {
            quality: 'hd',
            style: 'vivid',
            responseFormat: 'url',
            background: 'auto',
            outputFormat: 'png',
        },
    },
});
```

Available fields: `background`, `moderation`, `outputCompression`, `outputFormat`, `quality`, `responseFormat`, `style`, `user`.

## Error handling

```typescript theme={null}
import { ProviderError } from '@core-ai/core-ai';

try {
    const result = await generate({
        model: openai.chatModel('gpt-5-mini'),
        messages: [{ role: 'user', content: 'Hello!' }],
    });
} catch (error) {
    if (error instanceof ProviderError) {
        console.error('OpenAI API error:', error.message);
        console.error('Status:', error.statusCode);
    }
}
```

## Related

<CardGroup cols={2}>
  <Card title="Anthropic Provider" icon="message" href="/api/providers/anthropic">
    Claude models with extended thinking
  </Card>

  <Card title="Google GenAI Provider" icon="sparkles" href="/api/providers/google-genai">
    Gemini models with multimodal capabilities
  </Card>

  <Card title="core-ai Functions" icon="function" href="/api/core/generate">
    Learn about generate, stream, and more
  </Card>
</CardGroup>
