### Install the required packages Source: https://loginwithchatgpt.dev/docs/quickstart Install the core SDK components and AI dependencies. ```bash bun add @opencoredev/loginwithchatgpt-server @opencoredev/loginwithchatgpt-react @opencoredev/loginwithchatgpt-ai ai @ai-sdk/openai ``` -------------------------------- ### Install dependencies Source: https://loginwithchatgpt.dev/ Install the required server, React, and AI SDK packages using Bun. ```bash bun add @opencoredev/loginwithchatgpt-server \ @opencoredev/loginwithchatgpt-react @opencoredev/loginwithchatgpt-ai ``` -------------------------------- ### Install packages Source: https://loginwithchatgpt.dev/llms.mdx/docs/quickstart/content.md Install the core server, React, and AI SDK packages required for the integration. ```bash bun add @opencoredev/loginwithchatgpt-server @opencoredev/loginwithchatgpt-react @opencoredev/loginwithchatgpt-ai ai @ai-sdk/openai ``` ```bash npm install @opencoredev/loginwithchatgpt-server @opencoredev/loginwithchatgpt-react @opencoredev/loginwithchatgpt-ai ai @ai-sdk/openai ``` ```bash pnpm add @opencoredev/loginwithchatgpt-server @opencoredev/loginwithchatgpt-react @opencoredev/loginwithchatgpt-ai ai @ai-sdk/openai ``` -------------------------------- ### Install SDK Dependency Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Installs the core package required for realtime voice functionality. ```bash bun add @opencoredev/loginwithchatgpt-core ``` -------------------------------- ### POST /realtime/app-server Source: https://loginwithchatgpt.dev/docs/reference/routes Starts a native GPT Live audio session with desktop-style tool handoffs. ```APIDOC ## POST /realtime/app-server ### Description Starts native GPT Live audio plus desktop-style tool handoffs. ### Method POST ### Endpoint /realtime/app-server ### Request Body - **sdp** (string) - Required - The SDP offer string. - **session** (object) - Required - Configuration object containing voice and model slug. ### Response #### Success Response (201) - **sessionId** (string) - The opaque live session ID. - **sdp** (string) - The SDP answer string. ``` -------------------------------- ### Initiate App-server Session Source: https://loginwithchatgpt.dev/docs/reference/routes Request body and successful response for starting a native GPT Live audio session. ```json { "sdp": "v=0\r\n…", "session": { "voice": "vale", "model": "selected-model-slug" } } ``` ```json { "sessionId": "opaque-live-session-id", "sdp": "v=0\r\n…" } ``` -------------------------------- ### POST /login Source: https://loginwithchatgpt.dev/docs/reference/routes Starts a device login or reuses an existing pending device code. ```APIDOC ## POST /login ### Description Starts a device login, or reuses the session's still-valid pending device code without calling upstream again. Sets the session cookie when none exists. ### Method POST ### Endpoint /login ### Response #### Success Response (200) - **status** (string) - The current status of the login process. - **userCode** (string) - The code to be used for verification. - **verificationUrl** (string) - The URL to visit for verification. - **interval** (number) - Polling interval in seconds. - **expiresAt** (number) - Expiration timestamp. #### Response Example { "status": "pending", "userCode": "7B0J-DPK78", "verificationUrl": "https://auth.openai.com/codex/device", "interval": 5, "expiresAt": 1780000000000 } ``` -------------------------------- ### Configure ChatGPT Handler Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Setup the realtime handler with specific transport and authentication configurations. ```javascript createChatGPTHandler({ enableRealtime: true, realtime: { maxRequestBytes: 256 * 1024, allowedTransports: ["wm"], allowedModes: ["wingman"], sessionDefaults: { transport: "wm", historyAndTrainingDisabled: false }, getAuth: async ({ request }) => getUserBoundWebAuth(request), }, }); ``` -------------------------------- ### Initialize ChatGPT handler Source: https://loginwithchatgpt.dev/docs/reference/server Basic setup for creating a ChatGPT handler instance using the provided options. ```typescript import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; const auth = createChatGPTHandler(options); ``` -------------------------------- ### Configure AGENTS.md for project context Source: https://loginwithchatgpt.dev/docs/ai Add these instructions to your project's AGENTS.md or CLAUDE.md file to guide AI agents on how to interact with the SDK documentation. ```text When working with @opencoredev/loginwithchatgpt-* packages, fetch https:///llms.txt first and follow links from there. Verify option names against /docs/reference/server before writing code. ``` -------------------------------- ### Configure ChatGPT handler for production Source: https://loginwithchatgpt.dev/docs/guides/production Example configuration for the ChatGPT handler, including a persistent session store, restricted models, and a shared rate limit store. ```typescript const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, sessionStore: redisStore, responsesProxy: { allowedModels: ["gpt-5.5", "gpt-5.4-mini"], rateLimit: { limit: 20, windowMs: 60_000, store: redisRateLimitStore }, }, }); ``` -------------------------------- ### GET /status Source: https://loginwithchatgpt.dev/docs/reference/routes Advances the login process and returns the current authentication state. ```APIDOC ## GET /status ### Description Advances the login by at most one upstream poll, then returns public state. While pending it returns the device fields; token refresh also happens here for authenticated sessions near expiry. ### Method GET ### Endpoint /status ### Response #### Success Response (200) - **status** (string) - One of unauthenticated, pending, authenticated, expired, error. - **user** (object) - User account details if authenticated. ``` -------------------------------- ### GET /models Source: https://loginwithchatgpt.dev/docs/reference/routes Lists the account's available model slugs for authenticated sessions. ```APIDOC ## GET /models ### Description Requires an authenticated session; refreshes tokens, then lists the account's model slugs. ### Method GET ### Endpoint /models ### Response #### Success Response (200) - **models** (array) - List of available model slugs. #### Error Response (401) - **error** (string) - "not_authenticated" ``` -------------------------------- ### GET /models Response Source: https://loginwithchatgpt.dev/docs/reference/routes Returns a list of available model slugs for an authenticated session. ```json { "models": ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"] } ``` -------------------------------- ### ChatGPTAuthError Handling Source: https://loginwithchatgpt.dev/docs/reference/errors Example of how to catch and inspect the ChatGPTAuthError class when calling SDK methods. ```APIDOC ## ChatGPTAuthError ### Description The `ChatGPTAuthError` class is thrown by the SDK to represent authentication or upstream request failures. It provides access to the machine-readable error code, the upstream HTTP status, and the upstream response body. ### Usage ```typescript import { ChatGPTAuthError, isRefreshTokenInvalid } from "@opencoredev/loginwithchatgpt-core"; try { await auth.getModels(request); } catch (error) { if (error instanceof ChatGPTAuthError) { error.code; // machine-readable code error.status; // upstream HTTP status error.body; // upstream body snippet } } ``` ### Error Codes | Code | Thrown when | | --- | --- | | `device_code_request_failed` | Upstream refused to issue a device code. | | `device_code_disabled` | The device-code endpoint returned 404, so the flow is unavailable for this issuer/client. | | `authorization_pending` | Polling continued past what the caller allowed. | | `authorization_expired` | The 15-minute device code ran out, or `waitForDeviceTokens()` was aborted. | | `token_exchange_failed` | Exchanging the authorization code for tokens failed. | | `token_refresh_failed` | A refresh failed for a reason other than a dead token (network blip, 5xx). | | `refresh_token_invalid` | OpenAI reported the refresh token as expired, reused, or invalidated. | | `not_authenticated` | An operation needed tokens and none exist. | | `invalid_token` | Tokens lack a usable `accountId`. | | `token_export_disabled` | Raw token export was requested without `dangerouslyAllowTokenExport`. | | `refresh_token_export_disabled` | Refresh-token export was requested without `dangerouslyAllowRefreshTokenExport`. | | `network_error` | The upstream request itself failed (DNS, timeout, offline). | | `models_request_failed` | `GET /models` upstream call failed. | | `responses_request_failed` | The proxied `/responses` upstream call failed. | | `realtime_request_failed` | Realtime signaling failed or returned a non-SDP body. | ``` -------------------------------- ### Run the demo project Source: https://loginwithchatgpt.dev/docs/guides/chat-app Commands to clone and run the full playground repository locally. ```bash git clone https://github.com/loginwithchatgpt/login-with-chatgpt cd login-with-chatgpt bun install bun run demo # http://localhost:3000 ``` -------------------------------- ### GET /realtime/app-server/:id/events Source: https://loginwithchatgpt.dev/docs/reference/routes Streams application/x-ndjson events for a specific live session. ```APIDOC ## GET /realtime/app-server/:id/events ### Description Streams application/x-ndjson events including session lifecycle, tool execution, and error events. ### Method GET ### Endpoint /realtime/app-server/:id/events ### Parameters #### Path Parameters - **id** (string) - Required - The session ID. ``` -------------------------------- ### GET /session Source: https://loginwithchatgpt.dev/docs/reference/routes Retrieves the current session state without polling upstream. ```APIDOC ## GET /session ### Description Returns the same response shape as /status, but never polls upstream, making it a cheap read for initial page loads. ### Method GET ### Endpoint /session ``` -------------------------------- ### Initialize ChatGPT Provider and Client Source: https://loginwithchatgpt.dev/docs/reference/ai Core primitives for creating the ChatGPT proxy provider and client instance. ```javascript createChatGPTProxyProvider(options?) ``` ```javascript createChatGPT(options) ``` -------------------------------- ### Initialize server-side handler Source: https://loginwithchatgpt.dev/ Set up the ChatGPT handler in your Bun server to manage authentication routes. ```typescript const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, }); Bun.serve({ routes: { "/api/chatgpt/*": (req) => auth.handler(req), }, }); ``` -------------------------------- ### Initialize ChatGPT for Headless Servers Source: https://loginwithchatgpt.dev/docs/reference/ai Use this pattern for CLI or headless applications where you manage token custody directly. Ensure credentials are provided as static tokens or a loader function. ```typescript import { createChatGPT } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const chatgpt = createChatGPT({ credentials: tokens }); const result = streamText({ model: chatgpt(), prompt }); ``` -------------------------------- ### createChatGPTProxyProvider(options?) Source: https://loginwithchatgpt.dev/docs/reference/ai Initializes a ChatGPT proxy provider. This function accepts an optional configuration object to customize the base path, fetch implementation, credentials, headers, and default model. ```APIDOC ## createChatGPTProxyProvider(options?) ### Description Initializes the ChatGPT proxy provider for use with the AI SDK. It can be configured for browser-side usage or server-side route handling. ### Parameters - **basePath** (string) - Optional - Handler mount path (default: "/api/chatgpt"). - **fetch** (FetchLike) - Optional - Custom fetch implementation. - **credentials** (RequestCredentials) - Optional - Credentials mode (default: "same-origin"). - **headers** (Record) - Optional - Extra headers for requests. - **defaultModel** (string) - Optional - Default model name (default: "gpt-5.5"). ### Usage Example ```typescript import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const chatgpt = createChatGPTProxyProvider(); const result = streamText({ model: chatgpt("gpt-5.5"), prompt: "Explain cache invalidation in two sentences.", }); ``` ``` -------------------------------- ### GET /status Response Source: https://loginwithchatgpt.dev/docs/reference/routes Returns the current authentication state and user information, potentially triggering an upstream poll or token refresh. ```json { "status": "authenticated", "user": { "accountId": "acct_…", "email": "user@example.com", "plan": "pro" } } ``` -------------------------------- ### Initialize ChatGPT Proxy Provider Source: https://loginwithchatgpt.dev/docs/reference/ai Demonstrates basic client-side initialization and usage with the AI SDK's streamText function. ```typescript import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const chatgpt = createChatGPTProxyProvider(); const result = streamText({ model: chatgpt("gpt-5.5"), prompt: "Explain cache invalidation in two sentences.", }); ``` -------------------------------- ### Discover models and stream Source: https://loginwithchatgpt.dev/llms.mdx/docs/quickstart/content.md Initialize the proxy provider to interact with ChatGPT models through your authenticated handler. ```ts import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const chatgpt = createChatGPTProxyProvider(); ``` -------------------------------- ### Visualize the Login with ChatGPT Authentication Flow Source: https://loginwithchatgpt.dev/docs A diagram illustrating the interaction between the browser, the authentication server, and the streaming proxy. ```text Browser button ──▶ POST /api/chatgpt/login ──▶ user authorizes on auth.openai.com │ Browser polls GET /status ◀── server exchanges the code and stores encrypted tokens │ streamText() ──▶ POST /api/chatgpt/responses ──▶ server injects tokens, streams back ``` -------------------------------- ### Configure App-Server Tools and Handlers Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Define tool schemas and implement the execution and confirmation logic on the server side using createChatGPTHandler. ```typescript import { createChatGPTHandler, type RealtimeDynamicTool, } from "@opencoredev/loginwithchatgpt-server"; const tools: RealtimeDynamicTool[] = [{ type: "function", name: "record_lookup", description: "Read a record owned by the authenticated application user.", inputSchema: { type: "object", properties: { recordId: { type: "string" } }, required: ["recordId"], additionalProperties: false, }, }, { type: "function", name: "record_prepare_change", description: "Prepare a reviewable record change without applying it.", inputSchema: { type: "object", properties: { recordId: { type: "string" }, value: { type: "string" }, }, required: ["recordId", "value"], additionalProperties: false, }, }]; const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, realtime: { appServer: { tools, allowedModels: (model) => allowedExecutionModels.has(model), async executeTool({ request, callId, name, arguments: args }) { const appUser = await requireAppUser(request); const input = validateToolArguments(name, args); if (name === "record_lookup") { return { output: await readOwnedRecord(appUser.id, input.recordId), }; } const change = await createPendingChange(appUser.id, callId, input); return { output: { status: "pending_confirmation", changeId: change.id }, pendingConfirmation: { review: { changeId: change.id, recordId: change.recordId, previousValue: change.previousValue, nextValue: change.nextValue, }, }, }; }, async confirmTool({ request, callId, confirmation, pending }) { const appUser = await requireAppUser(request); const approved = validateConfirmation(confirmation); const result = approved ? await atomicallyApplyOwnedChange(appUser.id, callId, pending) : await keepPendingChange(appUser.id, callId); return { output: result, speech: approved ? "The change was applied." : "I left the change unapplied.", }; }, }, }, }); ``` -------------------------------- ### createChatGPT(options) Source: https://loginwithchatgpt.dev/docs/reference/ai Initializes a ChatGPT provider instance for managing token custody. This is intended for headless or CLI applications where the developer handles token persistence and rotation. ```APIDOC ## createChatGPT(options) ### Description Initializes a ChatGPT provider instance for managing token custody. This is intended for headless or CLI applications where the developer handles token persistence and rotation. ### Parameters - **credentials** (ChatGPTTokens | () => ChatGPTTokens | Promise) - Required - Static tokens or a loader function. - **onRefresh** ((tokens: ChatGPTTokens) => void | Promise) - Optional - Callback to persist rotated tokens. - **headers** (Record) - Optional - Extra headers for upstream requests. - **defaultModel** (string) - Optional - Default model used when calling chatgpt() without arguments (default: "gpt-5.5"). - **CodexResponsesOptions** (object) - Optional - Configuration for instructions, reasoningEffort, reasoningSummary, textVerbosity, and serviceTier. - **ChatGPTConfig** (object) - Optional - Upstream configuration overrides. ### Usage Example ```javascript import { createChatGPT } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const chatgpt = createChatGPT({ credentials: tokens }); const result = streamText({ model: chatgpt(), prompt }); ``` ``` -------------------------------- ### POST /api/chatgpt/realtime Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Initiates a realtime voice session using WebRTC SDP exchange. ```APIDOC ## POST /api/chatgpt/realtime ### Description Initiates a realtime voice session. This endpoint is cookie-authenticated and protected by same-origin checks. ### Method POST ### Endpoint /api/chatgpt/realtime ### Request Body - **sdp** (string) - Required - The WebRTC SDP offer. - **session** (object) - Required - Session configuration. - **voice** (string) - Optional - Voice identifier (e.g., "juniper"). - **transport** (string) - Optional - Transport type (e.g., "wm"). - **language** (string) - Optional - Language code (e.g., "en-US"). ### Request Example { "sdp": "v=0\r\n…", "session": { "voice": "juniper", "transport": "wm", "language": "en-US" } } ### Response #### Success Response (201) - **body** (application/sdp) - The WebRTC answer. #### Error Responses - **400** - invalid_realtime_request - **401** - not_authenticated - **403** - origin_not_allowed, realtime_mode_not_allowed, or realtime_transport_not_allowed - **413** - realtime_request_too_large - **501** - realtime_web_auth_required - **502** - realtime_request_failed ``` -------------------------------- ### POST /realtime Source: https://loginwithchatgpt.dev/docs/reference/routes An experimental endpoint to exchange a browser WebRTC offer through the ChatGPT web transport. ```APIDOC ## POST /realtime ### Description Experimentally exchanges a browser WebRTC offer through an undocumented ChatGPT web transport. The credential remains server-side. ### Method POST ### Endpoint /realtime ### Request Body - **sdp** (string) - Required - The WebRTC SDP offer. - **session** (object) - Required - Configuration including `voice`, `transport`, and `voiceMode`. ### Response #### Success Response (201) - WebRTC answer SDP. #### Error Responses - **400** - Invalid realtime request. - **401** - Not authenticated. - **403** - Realtime mode, transport, or origin not allowed. - **413** - Request too large. - **502** - Upstream request failed. ``` -------------------------------- ### Initiate Device Flow Source: https://loginwithchatgpt.dev/docs/reference/core Initializes the device authorization process by requesting a device code from the configuration. ```typescript import { requestDeviceCode, pollDeviceCode, exchangeDeviceAuthorization, waitForDeviceTokens, resolveConfig, } from "@opencoredev/loginwithchatgpt-core"; const config = resolveConfig(); const device = await requestDeviceCode(config); // { deviceAuthId, userCode, verificationUrl, interval, expiresAt } ``` -------------------------------- ### Implement a complete CLI login flow Source: https://loginwithchatgpt.dev/docs/guides/headless Uses the core primitives to request a device code, wait for user authorization, and stream AI responses. ```typescript import { requestDeviceCode, resolveConfig, waitForDeviceTokens, } from "@opencoredev/loginwithchatgpt-core"; import { createChatGPT } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const config = resolveConfig(); const device = await requestDeviceCode(config); console.log(`Open ${device.verificationUrl} and enter: ${device.userCode}`); const tokens = await waitForDeviceTokens(config, device, { onPoll: (attempt) => console.log(`Waiting for authorization… (${attempt})`), }); const chatgpt = createChatGPT({ credentials: tokens }); const result = streamText({ model: chatgpt(), // defaults to gpt-5.5 prompt: "Say hello from a CLI.", }); for await (const delta of result.textStream) { process.stdout.write(delta); } ``` -------------------------------- ### Mount the server handler Source: https://loginwithchatgpt.dev/docs/quickstart Initialize the Web-standard handler for managing authentication and proxying requests. ```typescript import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; import index from "./index.html"; const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, responsesProxy: { allowedModels: ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"], }, }); Bun.serve({ routes: { "/": index, "/api/chatgpt/*": (req) => auth.handler(req), }, }); ``` -------------------------------- ### Implement the ask function Source: https://loginwithchatgpt.dev/llms.mdx/docs/quickstart/content.md Uses the chatgpt client to list available models and stream text responses based on a provided prompt. ```typescript export async function ask(prompt: string) { const models = await chatgpt.listModels(); // GET /api/chatgpt/models const model = models.includes("gpt-5.5") ? "gpt-5.5" : models[0]; if (!model) throw new Error("No ChatGPT models returned for this account."); return streamText({ model: chatgpt(model), prompt }); } ``` -------------------------------- ### Fetch documentation page via cURL Source: https://loginwithchatgpt.dev/docs/ai Use this command to retrieve the markdown content of a specific documentation page for an AI agent. ```bash curl -s https:///llms.mdx/docs/reference/server/content.md ``` -------------------------------- ### ChatGPTProvider API Usage Source: https://loginwithchatgpt.dev/docs/reference/ai Demonstrates model instantiation, model listing, and image generation using the ChatGPTProvider interface. ```javascript const model = chatgpt("gpt-5.5"); // a responses model const same = chatgpt.responses("gpt-5.5"); // explicit accessor const model2 = chatgpt(); // uses defaultModel ("gpt-5.5") const slugs = await chatgpt.listModels(); // string[] const generated = await chatgpt.images.generate({ prompt, model: slugs[0] }); const edited = await chatgpt.images.edit({ prompt, images, model: slugs[0] }); const openai = chatgpt.openai; // underlying @ai-sdk/openai provider ``` -------------------------------- ### Mount server handler Source: https://loginwithchatgpt.dev/llms.mdx/docs/quickstart/content.md Initialize the ChatGPT handler to manage authentication and proxy requests. ```ts import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; import index from "./index.html"; const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, responsesProxy: { allowedModels: ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"], }, }); Bun.serve({ routes: { "/": index, "/api/chatgpt/*": (req) => auth.handler(req), }, }); ``` ```ts import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, responsesProxy: { allowedModels: ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"], }, }); export const GET = (request: Request) => auth.handler(request); export const POST = (request: Request) => auth.handler(request); ``` -------------------------------- ### Configure ChatGPT Handler with Custom Store Source: https://loginwithchatgpt.dev/docs/concepts/sessions Initialize the handler with a custom KeyValueStore implementation to persist sessions across server restarts. ```typescript import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, sessionStore: redisBackedStore, // any KeyValueStore implementation }); ``` -------------------------------- ### Configure server-side cross-origin settings Source: https://loginwithchatgpt.dev/docs/guides/cross-origin Initialize the ChatGPT handler with allowed origins and permissive cookie settings for cross-site authentication. ```typescript import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, allowedOrigins: ["https://app.example.com"], cookie: { sameSite: "None", secure: true }, }); ``` -------------------------------- ### Initialize useLoginWithChatGPT hook Source: https://loginwithchatgpt.dev/docs/reference/react Basic implementation of the hook within a client component. ```javascript "use client"; import { useLoginWithChatGPT } from "@opencoredev/loginwithchatgpt-react"; const auth = useLoginWithChatGPT({ pollIntervalMs: 2500 }); ``` -------------------------------- ### JWT and PKCE Helpers Source: https://loginwithchatgpt.dev/docs/reference/core Utility functions for parsing user information and supporting the PKCE redirect flow. ```APIDOC ## Utility Methods ### parseUser(idToken) Extracts `ChatGPTUser` information (accountId, email, name, plan) from an ID token. ### decodeJwt(token) / getTokenExpiry(token) / deriveAccountId(token) Decodes JWT payloads without signature verification. Use for claim inspection only. ### generatePkce() / createState() / randomToken(length?) Helper functions to support the loopback redirect flow (PKCE). ``` -------------------------------- ### Discover models and stream responses Source: https://loginwithchatgpt.dev/docs/quickstart Use the proxy provider to list available models and stream text responses. ```typescript import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; const chatgpt = createChatGPTProxyProvider(); export async function ask(prompt: string) { const models = await chatgpt.listModels(); // GET /api/chatgpt/models const model = models.includes("gpt-5.5") ? "gpt-5.5" : models[0]; if (!model) throw new Error("No ChatGPT models returned for this account."); return streamText({ model: chatgpt(model), prompt }); } ``` ```typescript const result = await ask("Explain HTTP cookies in one paragraph."); for await (const delta of result.textStream) { process.stdout.write(delta); } ``` -------------------------------- ### Connect Realtime Voice from Browser Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Initiate a realtime voice session and handle tool confirmation events from the client side. ```typescript import { connectChatGPTRealtimeAppServer, } from "@opencoredev/loginwithchatgpt-core"; let pending: { callId: string; review: unknown } | undefined; const live = await connectChatGPTRealtimeAppServer({ session: { voice: "vale", model: selectedModelSlug, }, onStateChange: renderVoiceState, onBridgeEvent(event) { if (event.type === "tool.pending_confirmation") { pending = { callId: event.callId, review: event.review }; renderConfirmation(event.review); } }, }); // Call only from an explicit application UI action. if (!pending) throw new Error("No action is waiting for confirmation."); await live.resolveConfirmation(pending.callId, { approved: true }); // Releases browser media and closes the server process. live.close(); ``` -------------------------------- ### POST /login Response Source: https://loginwithchatgpt.dev/docs/reference/routes Returns the device login status and verification details when initiating or resuming a login flow. ```json { "status": "pending", "userCode": "7B0J-DPK78", "verificationUrl": "https://auth.openai.com/codex/device", "interval": 5, "expiresAt": 1780000000000 } ``` -------------------------------- ### Implement custom login UI with useLoginWithChatGPT Source: https://loginwithchatgpt.dev/docs/guides/custom-ui Use the hook to manage authentication states including loading, authenticated, pending, and unauthenticated scenarios. ```tsx "use client"; import { useLoginWithChatGPT } from "@opencoredev/loginwithchatgpt-react"; export function ChatGPTLogin() { const auth = useLoginWithChatGPT(); if (auth.status === "loading") { return

Checking ChatGPT session…

; } if (auth.status === "authenticated") { return ( ); } if (auth.status === "pending") { return (

Enter this code in the OpenAI verification window.

{auth.copied ?

Copied.

: null}
); } // unauthenticated, expired, or error: render consent, then login return (

Continue only if you trust this app. It can send AI requests billed to your own ChatGPT plan.

{auth.error ?

{auth.error}

: null}
); } ``` -------------------------------- ### Select a default model Source: https://loginwithchatgpt.dev/docs/concepts/models Implement logic to prefer a specific recommended model while falling back to the first available option. ```typescript const models = await chatgpt.listModels(); const model = models.includes("gpt-5.5") ? "gpt-5.5" : models[0]; if (!model) throw new Error("No ChatGPT models returned for this account."); ``` -------------------------------- ### Configure Barge-In Settings Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Customizes interruption detection thresholds for the voice session. ```javascript bargeIn: { threshold: 0.045, holdMs: 120, cooldownMs: 800 } ``` -------------------------------- ### App-Server Realtime Routes Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Endpoints for managing user-scoped app-server processes for realtime voice. ```APIDOC ## POST /api/chatgpt/realtime/app-server ### Description Create the user-scoped app-server process and exchange SDP. ## GET /api/chatgpt/realtime/app-server/:id/events ### Description Stream bridge events as NDJSON. ## POST /api/chatgpt/realtime/app-server/:id/confirm ### Description Resolve an application-owned pending action. ## DELETE /api/chatgpt/realtime/app-server/:id ### Description Stop and remove the call. ``` -------------------------------- ### Connect and Control Realtime Voice Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Initializes a voice connection and demonstrates usage of call controls and lifecycle management. ```typescript import { CHATGPT_REALTIME_VOICES, connectChatGPTRealtime, } from "@opencoredev/loginwithchatgpt-core"; const call = await connectChatGPTRealtime({ session: { voice: "juniper", transport: "wm", language: "en-US", }, onStateChange: (state) => console.log(state), onTranscript: ({ kind, text }) => { // Render the user's recognized speech and the assistant's live captions. appendTranscript(kind, text); }, }); console.log(CHATGPT_REALTIME_VOICES); // Explicit controls are useful for buttons and push-to-talk. call.stopSpeaking(); call.setInputMuted(true); call.setOutputMuted(false); // Always release the microphone, peer, data channel, and audio graph. call.close(); ``` -------------------------------- ### Implement Server-Side Route Handler Source: https://loginwithchatgpt.dev/docs/reference/ai Shows how to bind the provider to an incoming request using auth.proxyFetch within an API route. ```typescript import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; import { streamText } from "ai"; export async function POST(request: Request) { const chatgpt = createChatGPTProxyProvider({ fetch: auth.proxyFetch(request), }); const { prompt } = await request.json(); const result = streamText({ model: chatgpt(), prompt }); return result.toUIMessageStreamResponse(); } ``` -------------------------------- ### Discover ChatGPT models Source: https://loginwithchatgpt.dev/docs/reference/ai Retrieve available models from the signed-in account before performing image operations. ```javascript const models = await chatgpt.listModels(); const model = models[0]; if (!model) throw new Error("No ChatGPT models were returned for this account."); ``` -------------------------------- ### Render the sign-in button Source: https://loginwithchatgpt.dev/docs/quickstart Implement the React component to trigger the authentication flow. ```tsx "use client"; import { LoginWithChatGPT } from "@opencoredev/loginwithchatgpt-react"; export function SignIn() { return ( console.log("ChatGPT session connected")} /> ); } ``` -------------------------------- ### Configure Fast Tier via SDK Header Source: https://loginwithchatgpt.dev/docs/guides/fast-and-reasoning Use the x-login-with-chatgpt-service-tier header to enable Fast mode in streamText calls. ```typescript import { streamText } from "ai"; const result = streamText({ model: chatgpt("gpt-5.5"), prompt: "Refactor this helper.", headers: { "x-login-with-chatgpt-service-tier": "fast", }, }); ``` -------------------------------- ### createCodexFetch Source: https://loginwithchatgpt.dev/docs/reference/core Creates a fetch-compatible function that handles URL rewriting, authentication headers, and response normalization for Codex-backed backends. ```APIDOC ## createCodexFetch({ config, getAuth, ...CodexResponsesOptions }) ### Description Returns a fetch-compatible function that rewrites URLs onto `codexBaseUrl`, injects the bearer token and `chatgpt-account-id` header, adds `client_version`, and normalizes `/responses` bodies. ``` -------------------------------- ### Configure Reasoning Effort via SDK Header Source: https://loginwithchatgpt.dev/docs/guides/fast-and-reasoning Use the x-login-with-chatgpt-reasoning-effort header to adjust the model's reasoning intensity. ```typescript const result = streamText({ model: chatgpt("gpt-5.5"), prompt: "Review this migration plan.", headers: { "x-login-with-chatgpt-reasoning-effort": "high", }, }); ``` -------------------------------- ### Probe API routes for connectivity Source: https://loginwithchatgpt.dev/docs/reference/troubleshooting Verify the health of the authentication layers by testing the login, session, and model endpoints in sequence. ```bash curl -i -X POST http://localhost:3000/api/chatgpt/login # handler mounted? curl -i http://localhost:3000/api/chatgpt/session # cookie & store? curl -i http://localhost:3000/api/chatgpt/models # tokens & upstream? ``` -------------------------------- ### Configure Server-Side Authentication Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Sets up the ChatGPT handler with a server-only auth callback to exchange web sessions for realtime access, ensuring identity verification. ```typescript import { exchangeChatGPTRealtimeWebSession, resolveConfig, } from "@opencoredev/loginwithchatgpt-core"; import { createChatGPTHandler } from "@opencoredev/loginwithchatgpt-server"; const config = resolveConfig(); const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, realtime: { async getAuth({ request }) { const appUser = await requireAppUser(request); const encrypted = await loadUserRealtimeSession(appUser.id); const stored = await decrypt(encrypted); const live = await exchangeChatGPTRealtimeWebSession({ config, sessionToken: stored.sessionToken, deviceId: stored.deviceId, sessionCookies: stored.sessionCookies, onSessionUpdate: async (next) => { await saveUserRealtimeSession(appUser.id, await encrypt({ ...stored, ...next })); }, }); if (live.email.toLowerCase() !== appUser.email.toLowerCase()) { throw new Error("ChatGPT Live identity does not match the app user"); } return live; }, }, }); ``` -------------------------------- ### Configure client-side credentialed fetches Source: https://loginwithchatgpt.dev/docs/guides/cross-origin Configure the hook and proxy provider to use absolute URLs and include credentials in all requests. ```typescript import { useLoginWithChatGPT } from "@opencoredev/loginwithchatgpt-react"; import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; const basePath = "https://api.example.com/api/chatgpt"; const auth = useLoginWithChatGPT({ basePath, fetch: (input, init) => fetch(input, { ...init, credentials: "include" }), }); const chatgpt = createChatGPTProxyProvider({ basePath, credentials: "include", // used by listModels() fetch: (input, init) => fetch(input, { ...init, credentials: "include" }), // used for streaming }); ``` -------------------------------- ### Pass pre-opened window to login Source: https://loginwithchatgpt.dev/docs/guides/custom-ui Use a pre-opened window for custom consent flows where the verification page should load into that specific window. ```tsx const popup = window.open("", "login-with-chatgpt"); // render your consent into the popup, and on continue: await auth.login({ popup }); ``` -------------------------------- ### Configure ChatGPT Handler Source: https://loginwithchatgpt.dev/docs/concepts/response-proxy Initializes the ChatGPT handler with specific model allowlists and custom rate limiting settings. ```typescript const auth = createChatGPTHandler({ secret: process.env.LWC_SECRET, responsesProxy: { allowedModels: ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"], rateLimit: { limit: 10, windowMs: 60_000 }, }, }); ``` -------------------------------- ### openLoginWithChatGPTConsentPopup() Source: https://loginwithchatgpt.dev/docs/reference/react Opens the built-in consent popup. On continue, it triggers the provided login function to load the verification page in the same window. ```APIDOC ## openLoginWithChatGPTConsentPopup() ### Description Opens the built-in consent popup and, on continue, calls your `login` with that popup so the verification page loads in the same window. ### Parameters - **appName** (string) - Required - The name of the application. - **continueLabel** (string) - Required - The label for the continue button. - **securityHref** (string) - Required - The URL for the security policy. - **login** (function) - Required - The authentication login function to execute. ### Returns - **popup** (object|null) - Returns the popup object or null if the popup was blocked. ``` -------------------------------- ### List models in browser and server Source: https://loginwithchatgpt.dev/docs/concepts/models Fetch available model slugs using the proxy provider in the browser or the auth handler on the server. ```typescript import { createChatGPTProxyProvider } from "@opencoredev/loginwithchatgpt-ai"; const chatgpt = createChatGPTProxyProvider(); const models = await chatgpt.listModels(); // ["gpt-5.5", "gpt-5.4", ...] ``` ```typescript const models = await auth.getModels(request); if (!models) return new Response("Unauthorized", { status: 401 }); ``` -------------------------------- ### Export authentication tokens Source: https://loginwithchatgpt.dev/docs/reference/server Retrieves access tokens for advanced integrations. Requires explicit configuration to enable and should be used with caution. ```javascript const tokens = await auth.dangerouslyGetTokens(request); // { accessToken, accountId, expiresAt } with no refreshToken const exported = await auth.dangerouslyGetTokens(request, { includeRefreshToken: true, }); // Requires dangerouslyAllowRefreshTokenExport: true. Use only for migration/export flows. ``` -------------------------------- ### chatgpt.images.generate Source: https://loginwithchatgpt.dev/docs/reference/ai Generates images based on a text prompt and specified configuration. ```APIDOC ## chatgpt.images.generate ### Description Generates images using a specified model and prompt. Supports configuration for size, quality, format, and partial image previews. ### Parameters - **model** (string) - Required - The mainline model returned by listModels(). - **prompt** (string) - Required - The instruction for image generation. - **size** (string) - Optional - Dimensions like '1024x1024' or 'auto'. - **quality** (string) - Optional - Rendering quality (auto, low, medium, high). - **format** (string) - Optional - Output format (png, jpeg, webp). - **compression** (number) - Optional - Compression level (0-100). - **background** (string) - Optional - Background setting (auto, opaque, transparent). - **n** (number) - Optional - Number of images to generate (1-10). - **partialImages** (number) - Optional - Number of intermediate previews to request. - **onPartialImage** (function) - Optional - Callback for partial image updates. ### Request Example ```javascript const result = await chatgpt.images.generate({ model, prompt: "An editorial photograph of a cobalt chair in a sunlit concrete room", size: "2048x2048", quality: "high", format: "webp" }); ``` ``` -------------------------------- ### buildChatGPTRealtimeSession() Source: https://loginwithchatgpt.dev/docs/guides/realtime-voice Generates the exact wire object required for a Realtime session without initiating a connection. ```APIDOC ## buildChatGPTRealtimeSession() ### Description Constructs the configuration object for a Realtime voice session. This method maps ergonomic SDK options to the required upstream wire format. ### Parameters - **transport** (string) - Optional - Endpoint selection; defaults to "wm". - **voice** (string) - Optional - Voice selection; defaults to "juniper". - **voiceMode** (string) - Optional - Voice mode; defaults to "wingman" for /wm. - **model** (string) - Optional - Model slug for entitlement preservation. - **language** (string) - Optional - BCP 47 language code. - **conversationId** (string) - Optional - ID for an existing conversation. - **timezone** (string) - Optional - Timezone string. - **timezoneOffsetMinutes** (number) - Optional - Timezone offset in minutes. - **historyAndTrainingDisabled** (boolean) - Optional - Disables history and training; defaults to false. - **enableMessageStreaming** (boolean) - Optional - Enables message streaming; defaults to true. ``` -------------------------------- ### POST /realtime/app-server/:id/confirm Source: https://loginwithchatgpt.dev/docs/reference/routes Confirms a pending tool execution for a specific session. ```APIDOC ## POST /realtime/app-server/:id/confirm ### Description Submits a confirmation for a pending tool call. ### Method POST ### Endpoint /realtime/app-server/:id/confirm ### Parameters #### Path Parameters - **id** (string) - Required - The session ID. ### Request Body - **callId** (string) - Required - The tool call ID. - **confirmation** (object) - Required - Application-defined confirmation payload. ``` -------------------------------- ### connectChatGPTRealtimeAppServer Source: https://loginwithchatgpt.dev/docs/reference/core Connects to authenticated app-server routes for real-time voice sessions. ```APIDOC ## connectChatGPTRealtimeAppServer(options?) ### Description Uses the handler's authenticated app-server routes, subscribes to tool lifecycle events, resolves explicit confirmations, and closes the server process with the call. ``` -------------------------------- ### getModels(request) Source: https://loginwithchatgpt.dev/docs/reference/server Retrieves the list of available models. ```APIDOC ### getModels(request) ### Description Fetches the list of models available to the current user session. ### Parameters - **request** (Request) - Required - The request context. ``` -------------------------------- ### createChatGPTHandler Source: https://loginwithchatgpt.dev/docs/reference/server Initializes the ChatGPT handler with the provided configuration options. ```APIDOC ## createChatGPTHandler(options) ### Description Initializes a new ChatGPT handler instance that can be mounted to a web server to manage authentication and proxying. ### Parameters - **options** (Object) - Required - Configuration object for the handler. - **basePath** (string) - Optional - Mount path (default: "/api/chatgpt"). - **secret** (string) - Optional - Secret for signing cookies and encrypting tokens. - **sessionStore** (KeyValueStore) - Optional - Storage implementation for sessions. - **cookieName** (string) - Optional - Name of the session cookie. - **sessionTtlMs** (number) - Optional - Lifetime of sessions in milliseconds. - **defaultModel** (string) - Optional - Default model used when omitted in requests. - **enableResponsesProxy** (boolean) - Optional - Toggle for /responses and /models routes. - **enableRealtime** (boolean) - Optional - Toggle for Realtime routes. - **allowedOrigins** (string[]) - Optional - Origins allowed for cookie-authenticated non-GET routes. ### Returns - **ChatGPTHandler** (Object) - An object containing methods for handling requests, retrieving sessions, and managing models. ``` -------------------------------- ### Persist tokens across runs Source: https://loginwithchatgpt.dev/docs/guides/headless Configures createChatGPT with a credentials loader and refresh callback to maintain sessions across process restarts. ```typescript const chatgpt = createChatGPT({ credentials: () => loadTokensFromDisk(), onRefresh: (next) => saveTokensToDisk(next), }); ```