A Vercel AI SDK v5 provider for accessing GPT-5 models through ChatGPT OAuth authentication. This provider enables you to use ChatGPT Plus, Pro, or Teams subscriptions with the AI SDK.
- 🚀 GPT-5 Access - Use the latest gpt-5 models via ChatGPT OAuth
- 🔐 OAuth Support - Automatic token management and refresh
- 🔄 Full Streaming - Real-time streaming responses with SSE
- 🛠️ Codex-Style Tools - Shell command and task planning tools
- 📦 AI SDK v5 Compatible - Works seamlessly with Vercel AI SDK v5
- 🔥 TypeScript Ready - Full TypeScript support with type definitions
- 📊 Usage Tracking - Accurate token usage and telemetry
- 📝 JSON Generation - Generate structured JSON through prompt engineering (see examples)
⚠️ Important: This provider has significant differences from standard OpenAI API. See limitations for details.
📚 Documentation:
- Examples - Working code examples
- Limitations - API constraints and workarounds
- Authentication - All authentication options
- Tool Calling - How to use tools
- Reasoning - Control reasoning depth
- JSON Formatting - Generate structured output
- Tool System - Understanding the architecture
npm install ai-sdk-provider-chatgpt-oauth
# or
yarn add ai-sdk-provider-chatgpt-oauth
# or
pnpm add ai-sdk-provider-chatgpt-oauthInstall and authenticate with OpenAI's Codex CLI:
npm install -g @openai/codex
codex loginThis will create OAuth credentials at ~/.codex/auth.json that the provider can use automatically.
See the complete OAuth implementation example that demonstrates how to implement the full OAuth flow without Codex CLI, including PKCE, token refresh, and a working CLI.
Set the following environment variables:
export CHATGPT_OAUTH_ACCESS_TOKEN="your-access-token"
export CHATGPT_OAUTH_ACCOUNT_ID="your-account-id"
export CHATGPT_OAUTH_REFRESH_TOKEN="your-refresh-token" # Optional, for auto-refreshPass credentials directly to the provider (see usage examples below).
import { generateText } from 'ai';
import { createChatGPTOAuth } from 'ai-sdk-provider-chatgpt-oauth';
const provider = createChatGPTOAuth();
const result = await generateText({
model: provider('gpt-5'),
prompt: 'Write a haiku about TypeScript',
});
console.log(result.text);import { generateText } from 'ai';
import { createChatGPTOAuth } from 'ai-sdk-provider-chatgpt-oauth';
const provider = createChatGPTOAuth({
autoRefresh: true, // Enable automatic token refresh
});
const result = await generateText({
model: provider('gpt-5'),
prompt: 'Explain quantum computing',
temperature: 0.7,
maxTokens: 500,
});import { streamText } from 'ai';
import { createChatGPTOAuth } from 'ai-sdk-provider-chatgpt-oauth';
const provider = createChatGPTOAuth();
const result = await streamText({
model: provider('gpt-5'),
prompt: 'Write a story about a robot',
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}Control the depth of reasoning for gpt-5 models:
const provider = createChatGPTOAuth({
reasoningEffort: 'high', // 'low' | 'medium' | 'high'
});
// Or per-model call
const result = await generateText({
model: provider('gpt-5', { reasoningEffort: 'high' }),
prompt: 'Solve this complex problem...',
});See Reasoning Documentation for detailed configuration and compatibility.
ChatGPT OAuth supports only two predefined tools:
shell- Execute command-line tools (maps from:bash,shell,command,execute)update_plan- Task planning (maps from:TodoWrite,update_plan,plan,todo)
import { generateText, tool } from 'ai';
import { z } from 'zod';
const result = await generateText({
model: provider('gpt-5'),
prompt: 'List files in current directory',
tools: {
bash: tool({
description: 'Execute shell commands',
parameters: z.object({ command: z.array(z.string()) }),
execute: async ({ command }) => {
// Execute command (implement with proper sandboxing)
return executeCommand(command);
},
}),
},
});Note: Custom functionality must be implemented as CLI tools. See Tool Calling Guide for details.
| Option | Type | Description |
|---|---|---|
baseURL |
string |
Override the API base URL (default: https://chatgpt.com/backend-api) |
headers |
Record<string, string> |
Additional headers to send with requests |
fetch |
FetchFunction |
Custom fetch implementation |
credentials |
ChatGPTOAuthCredentials |
Direct credentials object |
credentialsPath |
string |
Path to credentials file (default: ~/.codex/auth.json) |
authProvider |
AuthProvider |
Custom authentication provider |
autoRefresh |
boolean |
Enable automatic token refresh (default: true) |
gpt-5- Latest GPT-5 model with reasoning support (200k context, 100k output)gpt-5-codex- Codex CLI tuned GPT-5 variant with identical limits and reasoning defaultscodex-mini-latest- Experimental model with local shell understanding (200k context, 100k output)
The ChatGPT OAuth API at https://chatgpt.com/backend-api/codex/responses currently supports only these three models. While Codex CLI internally supports additional models (o3, o4-mini, gpt-4.1, gpt-4o, etc.), they return "Unsupported model" errors when accessed through the OAuth API.
Any other model ID string will be passed through to the API, allowing for future model support without code changes.
Note: generateObject() and streamObject() are not supported. Use prompt engineering:
const result = await generateText({
model: provider('gpt-5'),
prompt: 'Generate user profile.\nOUTPUT ONLY JSON: {"name": "string", "age": number}',
});
const data = JSON.parse(result.text);See JSON examples and JSON documentation for patterns.
import { ChatGPTOAuthError } from 'ai-sdk-provider-chatgpt-oauth';
try {
const result = await generateText({
model: provider('gpt-5'),
prompt: 'Hello',
});
} catch (error) {
if (error instanceof ChatGPTOAuthError) {
console.error('ChatGPT OAuth error:', error.message);
console.error('Status code:', error.statusCode);
}
}npm run buildnpm test# Check authentication
npm run example:auth
# Basic usage
npm run example:basic
# Streaming
npm run example:streaming
# Tool calling
npm run example:toolsEnsure you have either:
- Authenticated with Codex CLI:
codex login - Set environment variables
- Passed credentials directly
Enable autoRefresh or provide a refresh token:
const provider = createChatGPTOAuth({
autoRefresh: true,
});The provider includes automatic retry logic for rate limits. You can also implement custom retry logic in your application.
MIT
Contributions are welcome! Please feel free to submit a Pull Request.
For issues and questions, please use the GitHub Issues page.