OpenAI Integration Guide

Technology: open-ai · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/open-ai

Insight:

OpenAI is codeAmani's secondary provider — reach for it when structured output, fast classification, or function calling matters, while Claude stays primary for reasoning. The current family is GPT-6 (gpt-6-astra flagship, gpt-6.1-sol balanced, gpt-6-luna cheap); GPT-4o is deprecated and shuts down 2027-01-14, with gpt-6-luna as OpenAI's named replacement. Build on the Responses API — GPT-6 tool calling requires it, and the Assistants API shut down 2026-08-26. In openai v7, never pass { body } as create()'s second argument: it replaces the whole request body.

 ██████╗ ██████╗ ███████╗███╗   ██╗ █████╗ ██╗
██╔═══██╗██╔══██╗██╔════╝████╗  ██║██╔══██╗██║
██║   ██║██████╔╝█████╗  ██╔██╗ ██║███████║██║
██║   ██║██╔═══╝ ██╔══╝  ██║╚██╗██║██╔══██║██║
╚██████╔╝██║     ███████╗██║ ╚████║██║  ██║██║
 ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝

OpenAI Integration Guide

Focus: Using OpenAI as codeAmani's secondary AI provider — GPT-6 models on the Responses API, Structured Outputs, the Decisions API for routing, built-in tools and remote MCP, webhooks, and the Agents SDK — alongside Claude in Claude Code workflows.

Overview

Claude Code and OpenAI are complementary. OpenAI's current models — the GPT-6 family (gpt-6-astra, gpt-6.1-sol, gpt-6-sol, gpt-6-luna), with GPT-5.6 (gpt-5.6-sol / -terra / -luna) still fully supported — are called through the openai SDK or the Vercel AI SDK. New work targets the Responses API (client.responses). OpenAI's wording: "While Chat Completions remains supported, Responses is recommended for all new projects." For GPT-6 it is more than a recommendation: tool calling with reasoning only works on Responses.

Here is where OpenAI sits as the secondary provider: reach for it when structured output, fast classification, or function calling matters, while Claude stays primary for reasoning.

flowchart TD
  A["Task in a codeAmani app or Claude Code session"] --> Q1{"What kind of task?"}
  Q1 -->|"classify / route / score"| D["OpenAI Decisions API<br/>gpt-6-luna"]
  Q1 -->|"extract to a schema<br/>or call functions"| B["OpenAI Responses API<br/>gpt-6-luna, step up to gpt-6.1-sol"]
  Q1 -->|"reasoning, code gen"| C["Claude<br/>primary"]
  B --> E["Typed result back in your code"]
  D --> E
  C --> E

Official Documentation

Resource URL
API reference https://developers.openai.com/api/reference/overview
Models https://developers.openai.com/api/docs/models
Using GPT-6 (migration + prompting) https://developers.openai.com/api/docs/guides/latest-model
Pricing https://developers.openai.com/api/docs/pricing
Deprecations https://developers.openai.com/api/docs/deprecations
Changelog https://developers.openai.com/api/docs/changelog
Responses vs. Chat Completions https://developers.openai.com/api/docs/guides/migrate-to-responses
Conversation state / Conversations API https://developers.openai.com/api/docs/guides/conversation-state
Remote MCP + connectors https://developers.openai.com/api/docs/guides/tools-connectors-mcp
Webhooks https://developers.openai.com/api/docs/guides/webhooks
Data controls (ZDR, retention, residency) https://developers.openai.com/api/docs/guides/your-data
Agents (SDK vs Agents API) https://developers.openai.com/api/docs/guides/agents
Node SDK https://github.com/openai/openai-node
Python SDK https://github.com/openai/openai-python

Docs domain note: platform.openai.com/docs/* links still resolve, but the canonical docs live on developers.openai.com. Every docs page has a Markdown version: append .md to its URL. Codex docs under developers.openai.com/codex/* now redirect to learn.chatgpt.com/docs/*.


Models at a glance (verified 2026-10-20)

Standard pricing per 1M tokens, short context (≤272K input tokens). Long-context requests cost more; Batch and Flex halve the rates; Fast mode doubles them. Full table: reference/pricing-snapshot.md.

Tier Model id Input / cached / output Use it for
Flagship gpt-6-astra $10.00 / $1.00 / $50.00 Hardest end-to-end work. Claude is codeAmani's primary here.
Balanced gpt-6.1-sol $2.00 / $0.10 / $10.00 Complex extraction and agentic work at lower cost ("near-Astra").
Coding/agentic gpt-6-sol $2.00 / $0.20 / $10.00 Superseded for most work by gpt-6.1-sol.
Budget gpt-6-luna $0.10 / $0.01 / $0.50 codeAmani default for structured output, extraction, routing. The only Decisions API model.
Previous family gpt-5.6-sol (alias gpt-5.6), gpt-5.6-terra, gpt-5.6-luna $4/$20, $2/$12, $0.20/$1.20 Still supported. Sol's promotional price runs "at least through November 21, 2026".
Embeddings text-embedding-3-small (1536), text-embedding-3-large (3072) $0.02, $0.13 RAG / semantic search. Unchanged.
Images gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2 token-priced Flare for everyday generation, Sunburst for precise edits.
Voice gpt-realtime-2.1, gpt-realtime-2.1-mini, gpt-live-1 see pricing Speech-to-speech agents; GPT-Live is $0.05/min plus backend usage.
Transcription gpt-transcribe, gpt-live-transcribe $0.0045/min, $0.017/min Replace whisper-1 and gpt-4o-*-transcribe (shut down 2027-02-26).

All GPT-6 models have a 1,050,000-token context window and 128,000 max output tokens. They accept text and image input and support Structured Outputs and function calling.

GPT-6 differences that break old code (from the "Using GPT-6" guide):

Deprecations you will hit (from the deprecations page)

Shutdown What Replacement
Already gone Assistants API (2026-08-26), Sora 2 + Videos API (2026-09-24), Realtime API beta header (2026-05-12), DALL·E 2/3 (2026-05-12) Responses + Conversations; no video replacement; Realtime GA; GPT Image
2026-10-23 o4-mini, o3-mini, o1, gpt-4.1-nano, gpt-4-turbo, gpt-3.5-turbo, gpt-4o-2024-05-13, gpt-image-1 gpt-5.6-terra / gpt-5.6-sol / gpt-5.6-luna / GPT Image 2.5
2026-11-30 Reusable prompts (v1/prompts), Evals platform, Agent Builder Prompts in your code; Promptfoo; Agents SDK
2026-12-01 gpt-image-1-mini, gpt-image-1.5, chatgpt-image-latest gpt-image-2.5-flare / -sunburst
2026-12-11 gpt-5-2025-08-07 (+ mini/nano/pro), o3, o3-pro GPT-5.6 Sol / Terra / Luna
2027-01-14 gpt-4o (2024-08-06, 2024-11-20), gpt-4o-mini, gpt-4.1, gpt-4.1-mini gpt-6-luna
2027-01-06 New fine-tuning jobs for existing customers (closed to new orgs since 2026-05-07); tts-1, tts-1-hd, gpt-4o-mini-tts Prompting + Structured Outputs; gpt-realtime-2.1-mini
2027-04-01 gpt-5.1, gpt-5.3-codex, gpt-5.4-nano gpt-6-sol / gpt-6-luna

To monitor shutdowns in code, GET /v1/models returns an optional shutdown_date per model.


OpenAI SDK Integration

Here is how a Responses call travels from your app through the SDK to the model and back.

sequenceDiagram
  participant App as "Your server code"
  participant SDK as "openai SDK v7"
  participant API as "OpenAI Responses API"
  App->>SDK: "client.responses.create - gpt-6-luna"
  SDK->>API: "POST /v1/responses with OPENAI_API_KEY"
  API->>API: "run model and any built-in tools"
  API-->>SDK: "response with output items"
  SDK-->>App: "response.output_text or output_parsed"

Node.js / TypeScript

npm install openai   # 7.39.0 verified 2026-10-20 — requires Node >= 22; zod ^3.25 || ^4 for helpers
import OpenAI from "openai";

const client = new OpenAI(); // reads OPENAI_API_KEY; server-side only

const response = await client.responses.create({
  model: "gpt-6-luna",
  reasoning: { effort: "low" },
  instructions: "You are a TypeScript expert.",
  input: "Convert this class to use composition over inheritance.",
});

console.log(response.output_text);

v7 gotcha — the second argument is RequestOptions, not extra params. The SDK builds the request as { body, ...options }, so client.responses.create(params, { body: { foo: 1 } }) sends only { foo: 1 } and drops your model, input and tools. Put extra or undocumented fields in the first argument (with // @ts-expect-error if the types don't know them yet); use the second for headers, timeout, maxRetries, signal, and idempotencyKey.

Chat Completions still works, without tools on GPT-6 reasoning models:

const completion = await client.chat.completions.create({
  model: "gpt-6-luna",
  reasoning_effort: "low",
  messages: [
    { role: "system", content: "You are a TypeScript expert." },
    { role: "user", content: "Convert this class to use composition over inheritance." },
  ],
});
console.log(completion.choices[0]?.message.content);

Python

pip install openai   # 3.35.1 verified 2026-10-20 — requires Python >= 3.10
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

response = client.responses.create(
    model="gpt-6-luna",
    input="Generate unit tests for this function.",
)
print(response.output_text)

CLI

OpenAI now ships an official CLI (brew install openai/tools/openai) for shell workflows:

openai responses create --model "gpt-6-luna" --input "Summarise this diff" --raw-output \
  --transform 'output.#(type=="message").content.0.text'

On Windows or in CI, a curl to https://api.openai.com/v1/responses with Authorization: Bearer $OPENAI_API_KEY works anywhere; read .output_text from the JSON.


Structured output & function calling

This is the main reason OpenAI is codeAmani's secondary provider. With a strict JSON schema the model is guaranteed to emit JSON that matches it, and the SDK hands you a typed object. Structured Outputs work on every current model (GPT-4o 2024-08-06 and later, all GPT-5.x and GPT-6).

flowchart TD
  A["Zod schema in your app"] --> B["zodTextFormat<br/>(Responses API)"]
  B --> C["Strict JSON schema<br/>sent to model"]
  C --> D["Model constrained<br/>to schema"]
  D --> E["response.output_parsed<br/>typed object"]

(a) Structured output — Responses API

import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod";

const client = new OpenAI();

// Extract order data from a free-text payment SMS (Kenya-targeted projects only;
// US projects get the same pattern for Stripe receipts or invoices).
const OrderExtraction = z.object({
  amount_kes: z.number().int(),       // Daraja amounts are integer KES
  phone: z.string(),                   // normalise to 254XXXXXXXXX downstream
  reference: z.string(),
  confidence: z.enum(["high", "medium", "low"]),
});

const response = await client.responses.parse({
  model: "gpt-6-luna",
  reasoning: { effort: "low" },
  store: false,
  input: [
    { role: "system", content: "Extract the payment fields from the message." },
    { role: "user", content: "Got KES 1500 from 0712345678 ref INV-204" },
  ],
  text: { format: zodTextFormat(OrderExtraction, "order_extraction") },
});

const order = response.output_parsed; // typed, or null on refusal
if (order) console.log(order.amount_kes, order.phone, order.confidence);

(b) Function calling — Responses API

Function tools use the flat shape (type: "function" at the top level, strict: true). Calls come back as function_call items in response.output, with name, call_id, and arguments as a JSON string. Validate the arguments with Zod before you act on them. See examples/structured-output.ts.

GPT-6 adds async tool calling (async: true on a function tool lets the model keep working while your code runs it) and Programmatic Tool Calling (the model writes JavaScript that orchestrates several tool calls). Both are Responses-only.

Strict-schema gotcha: every property must be listed in required. Model an optional field as z.union([T, z.null()]), not .optional(), and keep additionalProperties: false.

(c) Classify or route? Use the Decisions API (beta)

For "which team gets this ticket?" or "is this photo damaged?", the Decisions API (client.decisions.create, POST /v1/decisions) returns typed answers "about 10x faster than the Responses API". It has three question types: predicate (a probability), choice (one of 2–255 values), and score (ordered levels). Only gpt-6-luna is supported, and it needs openai ≥ 7.30.0 (JS) or ≥ 3.26.0 (Python). See examples/decisions-routing.ts. Use Structured Outputs when you need to generate an object.

(d) Vercel AI SDK 7

codeAmani apps usually call models through the AI SDK, so switching providers is a one-line model change. With ai 7.0.146 and @ai-sdk/openai 4.0.98 (verified 2026-10-20):

import { openai } from "@ai-sdk/openai";
import { generateText, Output } from "ai";
import { z } from "zod";

const { output } = await generateText({
  model: openai("gpt-6-luna"),            // Responses API by default; openai.chat(...) for Chat Completions
  output: Output.object({ schema: z.object({ intent: z.enum(["demo", "pricing", "support"]) }) }),
  prompt: "Classify: 'Can I get a quote for 50 seats?'",
  providerOptions: { openai: { reasoningEffort: "low", store: false } },
});

generateObject and streamObject are deprecated (AI SDK 6); use generateText / streamText with output. AI SDK 7 removed experimental_output; read result.output. See examples/ai-sdk-structured.ts.


Conversation state

There are three ways to carry context between turns:

Approach How Storage
Manual Resend the message array each turn Nothing stored by OpenAI if store: false
Chaining previous_response_id: prev.id Responses are stored 30 days by default (store: true)
Conversations API const c = await client.conversations.create({}), then responses.create({ conversation: c.id, ... }) Items persist until deleted, with no 30-day TTL. Not ZDR-eligible.

The Assistants API (threads, runs) shut down on 2026-08-26. Migrate threads to the Conversations API using the Assistants migration guide.

For long jobs, set background: true and either poll client.responses.retrieve(id) or subscribe to the response.completed webhook (below).


Built-in tools

Responses API built-in tools (from the tools guide): web search (now with image results), file search, remote MCP servers, skills, shell (hosted container or local), computer use, image generation, tool search, Programmatic Tool Calling, plus Code Interpreter. They bill at the model's token rates plus per-tool fees, e.g. web search at $10 per 1K calls, file search at $2.50 per 1K calls plus $0.10/GB-day storage, and containers from $0.03 per 1 GB per 20-minute session (billed per minute, 5-minute minimum).

Image generation

Use the Image API (client.images.generate({ model: "gpt-image-2.5-flare", prompt }), which returns b64_json) for one-shot images. Use the Responses image_generation tool for multi-turn editing:

const res = await client.responses.create({
  model: "gpt-6-luna",
  input: "A clean product photo of a reusable water bottle on white",
  tools: [{ type: "image_generation", model: "gpt-image-2.5-flare" }],
});
const b64 = res.output.find((o) => o.type === "image_generation_call")?.result;

GPT Image models may require API Organization Verification. Transparent backgrounds (background: "transparent" with png/webp) are in preview for gpt-image-2. There is no video API: Sora 2 and the Videos API shut down 2026-09-24.

Voice: Realtime API and GPT-Live


MCP integration — the Responses API mcp tool

The OpenAI model acts as an MCP client. You give it a remote MCP server URL and it lists and calls that server's tools itself.

import OpenAI from "openai";

const client = new OpenAI();

const resp = await client.responses.create({
  model: "gpt-6.1-sol",
  tools: [
    {
      type: "mcp",
      server_label: "openai_docs",
      server_description: "Search and read the public OpenAI documentation.",
      server_url: "https://developers.openai.com/mcp",
      allowed_tools: ["search_openai_docs"],
      require_approval: "never", // read-only public server; use "always" for anything that writes
    },
  ],
  input: "Find the Responses API streaming docs and return the links.",
});

console.log(resp.output_text);

The other direction: to give Claude Code or Codex your tools, build a standard MCP server (see the repo's MCP guides). Codex itself is an MCP client: codex mcp add <name> --url https://... or [mcp_servers.<name>] in ~/.codex/config.toml. The old codex mcp-server command has been removed; use the Codex app server.


Webhooks (with signature verification)

OpenAI webhooks follow the Standard Webhooks spec, with webhook-id, webhook-timestamp, and webhook-signature headers. Create an endpoint in the dashboard (Project → Webhooks) to get a signing secret. You can only view it once.

Events include response.completed / .failed / .cancelled / .incomplete, batch.*, fine_tuning.job.*, realtime.call.incoming, Agents API session events, and safety alerts.

// app/api/webhooks/openai/route.ts — full version in examples/webhook-route.ts
import OpenAI from "openai";

const client = new OpenAI({ webhookSecret: process.env.OPENAI_WEBHOOK_SECRET });

export async function POST(req: Request): Promise<Response> {
  const raw = await req.text(); // verify the RAW body, never parsed JSON
  try {
    const event = await client.webhooks.unwrap(raw, req.headers);
    if (event.type === "response.completed") {
      // enqueue work keyed on event.data.id; dedupe on the webhook-id header
    }
    return new Response(null, { status: 200 });
  } catch (err) {
    if (err instanceof OpenAI.InvalidWebhookSignatureError) {
      return new Response("Invalid signature", { status: 400 });
    }
    throw err;
  }
}

Return 2xx within a few seconds. Failed or slow deliveries are retried with exponential backoff for up to 72 hours, 3xx redirects are not followed, and duplicate deliveries can happen, so dedupe on webhook-id. client.webhooks.verifySignature(raw, headers) verifies without parsing.


Agents: Agents SDK, Agents API, Codex

You want to Use
Run the agent loop in your app (tools, handoffs, approvals, your storage) Agents SDK: npm install @openai/agents zod (0.20.0, pre-1.0, pin exactly) / pip install openai-agents (0.24.0)
Let OpenAI run a managed Codex harness plus sandbox, with durable sessions Agents API (public beta since 2026-09-10): client.beta.agents.sessions.create(...)
Call models directly and build your own loop Responses API
Drive coding tasks from CI or scripts Codex SDK: npm install @openai/codex-sdk (0.163.0, Node ≥ 18) or the codex CLI
import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";

const orderStatus = tool({
  name: "order_status",
  description: "Look up an order's status by reference.",
  parameters: z.object({ reference: z.string() }),
  async execute({ reference }) { return `Order ${reference}: shipped`; },
});

const agent = new Agent({ name: "Support", instructions: "Answer briefly.", model: "gpt-6-luna", tools: [orderStatus] });
const result = await run(agent, "Where is order INV-9?");
console.log(result.finalOutput);

Agent Builder shuts down 2026-11-30. OpenAI points its users to the Agents SDK. ChatKit remains available.


Data controls (ZDR, retention, residency)

codeAmani default: send store: false for one-shot extraction, and only use Conversations when you need durable chat history.


Environment Variables

Secrets only — keep these server-side:

OPENAI_API_KEY=sk-proj-...
OPENAI_WEBHOOK_SECRET=whsec_...

Optional secret, only for scripts that call the Admin API (usage, costs, key management):

OPENAI_ADMIN_KEY=sk-admin-...

Non-secret settings (the SDK reads them automatically when set):

Variable Purpose Default
OPENAI_ORG_ID Organization for billing attribution account default
OPENAI_PROJECT_ID Project scoping key's project
OPENAI_BASE_URL Override the API host (e.g. a regional host or a gateway) https://api.openai.com/v1

Store secrets in .env.local and the Vercel dashboard (see ENV_MASTER.md). Never ship them to the browser. Project keys can now have expiry dates, and orgs can restrict key creation. Trusted workloads can also use workload identity federation instead of long-lived keys.


Automation Workflows

Dual-provider review hook

Use a Claude Code Stop hook to send a summary to OpenAI for a cross-model review.

.claude/settings.json:

{
  "hooks": {
    "Stop": [
      { "hooks": [{ "type": "command", "command": "node scripts/openai-second-opinion.mjs" }] }
    ]
  }
}

scripts/openai-second-opinion.mjs:

import OpenAI from "openai";
import { readFileSync } from "node:fs";

const client = new OpenAI();
const sessionLog = readFileSync(".claude/session.log", "utf-8");

const result = await client.responses.create({
  model: "gpt-6.1-sol",
  instructions: "Review this Claude Code session for potential issues.",
  input: sessionLog,
  store: false,
});

console.log("GPT-6.1 Sol review:", result.output_text);

CI: OpenAI code-quality gate

# .github/workflows/ai-review.yml
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4   # pin to a commit SHA per the SLSA policy
        with: { fetch-depth: 0 }
      - name: Get diff
        run: git diff origin/${{ github.base_ref }}...HEAD > diff.txt
      - name: OpenAI review
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          pip install "openai==3.35.1"
          python scripts/review.py diff.txt

Common Use Cases

Use case Approach
Structured extraction responses.parse + zodTextFormat on gpt-6-luna (step up to gpt-6.1-sol)
Ticket / lead routing, moderation-style yes/no Decisions API on gpt-6-luna
Vision / OCR input_image parts on any GPT-6 model
Embeddings for search text-embedding-3-small → pgvector
Images gpt-image-2.5-flare via Image API or the Responses tool
Voice agent Realtime API (gpt-realtime-2.1) or GPT-Live
Transcription gpt-transcribe (files) / gpt-live-transcribe (streaming)
Fine-tuning Don't start new work. Fine-tuning is closed to new orgs; use prompting plus Structured Outputs
Cross-model validation Claude drafts, GPT-6.1 Sol validates

Troubleshooting

Issue Fix
401 Unauthorized Check OPENAI_API_KEY, project permissions, key expiry, and the org's IP allowlist
model_not_found / shut-down model Check the deprecations table above; GET /v1/models shows shutdown_date
400 on temperature / top_p GPT-6 with reasoning effort ≠ none rejects them; remove them
400 on reasoning.effort: "none" gpt-6-astra and gpt-6.1-sol don't support none; use low
Tools ignored on Chat Completions Move to the Responses API (GPT-6 tool calling requires it)
Request sent with missing fields You passed { body } as the 2nd arg to create(); it replaced the whole body (v7)
output_parsed is null The model refused; inspect response.output for a refusal item
Strict-schema error Every property in required; nullable unions instead of .optional(); additionalProperties: false
429 slow_down / 503 server_is_overloaded Honour Retry-After, else back off exponentially. A 429 can also mean a hard spend limit was hit
Webhook "Invalid signature" Verify the raw text body (don't let a JSON parser consume it) and check the secret is for the right project
Rate-limit tiers Now three tiers: Build ($5 credit), Launch ($100), Grow ($500). See the rate-limits guide

codeAmani notes

Official docs: