OpenAI API & SDK — AI Web

Use the Responses API (POST https://api.openai.com/v1/responses), the OpenAI endpoint that, as of October 2026, is recommended for new projects. The request…

Ordering at a central warehouse counter takes a member card. The clerk checks your card first. With a wrong card, the order is refused. If the queue is full, the clerk says "come back in 2 seconds". Every order comes with a receipt listing the quantities, and that receipt is what you're billed on. Calling the OpenAI API is exactly like that:

Behind that counter, the OpenAI API is an ordinary HTTP endpoint: your server sends a POST with JSON, OpenAI answers with JSON. An SDK (Software Development Kit) is the official library that wraps those requests so they're easier to use.

The Responses API: the recommended endpoint

As of October 2026, OpenAI's "Migrate to the Responses API" guide says: Chat Completions (/v1/chat/completions, the older endpoint) is still supported, but Responses is recommended for all new projects. The endpoint is POST https://api.openai.com/v1/responses. The Bookshop assistant uses gpt-6-luna with reasoning: { effort: "none" }, so the model doesn't think before it answers. A stock question doesn't need the model to think at length, and "thinking" tokens are billed too.

Two more fields of the request body you'll use often:

A first request with fetch

This code runs on the Bookshop server. Node 18 and later has fetch built in. The function askModel sends the question to OpenAI, then returns the answer text and usage. When OpenAI answers with an error, the function throws an error that carries the status, the Retry-After header and the error code. The errors section below uses all three.

async function askModel(question) {
  const res = await fetch("https://api.openai.com/v1/responses", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
    },
    body: JSON.stringify({
      model: "gpt-6-luna",
      reasoning: { effort: "none" },
      instructions: "You are the Bookshop assistant. Answer briefly in English.",
      input: question, // plus the stock data, as in the Prompt Engineering lesson
      max_output_tokens: 300,
    }),
    signal: AbortSignal.timeout(30_000), // give up after 30 seconds
  });
  if (!res.ok) {
    const err = new Error(`OpenAI answered ${res.status}`);
    err.status = res.status;
    err.retryAfter = res.headers.get("retry-after");
    err.code = (await res.json().catch(() => ({}))).error?.code; // for example "slow_down"
    throw err;
  }
  const data = await res.json();
  const message = data.output.find((item) => item.type === "message");
  const text = message.content.find((part) => part.type === "output_text").text;
  return { text, usage: data.usage };
}

Before you look at the response, guess: if you write const data = await res.json(); console.log(data.output_text), what gets printed, the model's answer or undefined?

The shape of the response, trimmed from the API reference (the official documentation of each endpoint). The text and usage numbers here are an example:

{
  "id": "resp_...",
  "status": "completed",
  "model": "gpt-6-luna",
  "output": [
    { "type": "message", "role": "assistant",
      "content": [{ "type": "output_text", "text": "The Rainbow Troops is still available, 12 in stock." }] }
  ],
  "usage": { "input_tokens": 400, "output_tokens": 40, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 440 }
}

Calculating the cost from usage

As of October 2026, OpenAI's "Pricing" page lists gpt-6-luna at $0.10 per 1 million input tokens and $0.50 per 1 million output tokens. This function calculates the cost of one request from usage:

const computeCost = (usage) => (usage.input_tokens * 0.10 + usage.output_tokens * 0.50) / 1_000_000;
computeCost({ input_tokens: 400, output_tokens: 40 }); // 0.00006 dollars

One question is $0.00006, so 10,000 questions a day is $0.60. Reasoning tokens (the tokens a model uses to think) are counted inside output_tokens and billed as output. That is why simple tasks get effort: "none".

The official SDK

With the SDK, the same request is shorter:

import OpenAI from "openai"; // npm install openai (version 7.32.0 on npm, October 2026)

const client = new OpenAI({ timeout: 30 * 1000 }); // OPENAI_API_KEY is read from the environment

const response = await client.responses.create({
  model: "gpt-6-luna",
  reasoning: { effort: "none" },
  instructions: "You are the Bookshop assistant. Answer briefly in English.",
  input: "Is The Rainbow Troops still in stock?",
});
console.log(response.output_text); // in the SDK, this property exists
console.log(response.usage.input_tokens, response.usage.output_tokens);

According to the SDK's README (the library's guide file), unless you set it, a request is cancelled after 10 minutes (this code sets 30 seconds). Connection errors, 408, 409, 429 and 5xx (status 500 to 599, an error on the server) are retried 2 times automatically, with growing waits. The maxRetries setting changes the number of retries. Errors come as classes: OpenAI.AuthenticationError for 401, OpenAI.RateLimitError for 429, OpenAI.APIConnectionTimeoutError for a timeout.

The key on the server, the browser through your route

An API key must never reach the browser. VITE_... variables (environment variables that Vite, a frontend build tool, reads) used in frontend code are put into the bundle, the JavaScript file sent to the browser. Anyone can read a bundle. OpenAI's SDK even refuses to run in a browser unless you write dangerouslyAllowBrowser: true. So the browser calls a Bookshop route, and that route calls OpenAI:

app.post("/api/assistant", async (req, res) => {
  const question = String(req.body.question ?? "").slice(0, 500);
  try {
    const { text } = await withRetry(() => askModel(question));
    res.json({ answer: text });
  } catch (err) {
    console.error(err); // the full log stays on the server, not in the browser
    res.status(err.name === "TimeoutError" ? 504 : 502).json({ error: "The assistant can't answer right now" });
  }
});

This route cuts the question to 500 characters, then calls askModel through withRetry (the retrying function in the errors section below). If it still fails, the browser gets 504 when OpenAI took too long to answer, or 502 for any other error.

Laravel works the same way: Http::withToken(config('services.openai.key'))->timeout(30)->post('https://api.openai.com/v1/responses', [...]) in a controller, with the key in .env.

Errors: 401, 429 and timeouts

Status Meaning What to do
401 The API key is wrong or revoked Check the key. Don't retry.
429 (slow_down, rate limit) Requests are coming too fast Wait at least what Retry-After says (seconds), then retry a few times only
429 (credit_balance_exhausted and the other spend-limit codes) Credit is used up or a spending limit is reached Add credit or raise the limit. Retrying won't help.
503 (server_is_overloaded) The model is busy Follow Retry-After, then retry
TimeoutError No answer within 30 seconds Send the user a "running slow" message

withRetry follows the rules of that table. It retries only a 429 that isn't about used-up credit or a spending limit (the QUOTA_EXHAUSTED list), and 5xx. Before each retry it waits as long as Retry-After says. Without that header it waits 2 seconds, then 4. After maxTries attempts (3 by default), it throws the error. So the 8-second wait in the code comment happens only when maxTries is more than 3:

const QUOTA_EXHAUSTED = ["credit_balance_exhausted", "organization_spend_limit_exceeded", "project_spend_limit_exceeded", "organization_usage_limit_exceeded"];

async function withRetry(task, maxTries = 3) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await task();
    } catch (err) {
      const retryable = (err.status === 429 && !QUOTA_EXHAUSTED.includes(err.code)) || err.status >= 500;
      if (!retryable || attempt === maxTries) throw err;
      const seconds = Number(err.retryAfter) || 2 ** attempt; // without Retry-After: 2, 4, 8 seconds
      await new Promise((r) => setTimeout(r, seconds * 1000));
    }
  }
}

How it runs in the Lab, for a stock question that hits 429 once:

Time Event
0 ms Attempt 1: POST /v1/responses
120 ms 429, header Retry-After: 2
2,120 ms Attempt 2 after waiting 2,000 ms
3,020 ms 200 OK, usage 400 + 40 tokens, cost $0.00006

⚠️ The missing answer, double retries and leaked keys

TL;DR: Use the Responses API (POST https://api.openai.com/v1/responses), the OpenAI endpoint that, as of October 2026, is recommended for new projects. The request body holds model, instructions, input, reasoning and max_output_tokens (the limit on the answer's length in tokens). temperature (0 to 2) sets how random the answer is, and for gpt-6-luna it's only allowed with effort none (the model doesn't think first). With plain fetch, the text is in the output item of type message, then the content part of type output_text. A ready-made output_text exists only in the SDK (OpenAI's official library). Cost comes from usage (the token counts in the response): gpt-6-luna is $0.10 per 1 million input tokens and $0.50 per 1 million output tokens, so 400 input + 40 output tokens = $0.00006. Reasoning tokens (the tokens a model uses to think) are billed as output. The SDK (npm install openai) gives client.responses.create, a 10-minute default timeout and 2 automatic retries (repeated attempts). The API key stays on the server; the browser calls your route. Don't retry 401 (a wrong key). On 429 (too fast), wait as long as the Retry-After header says. For timeouts, use AbortSignal.timeout.

⚡ One request through the SDK

Write:

const response = await client.responses.create({
  model: "gpt-6-luna",
  reasoning: { effort: "none" },
  instructions: "You are the Bookshop assistant. Answer briefly in English.",
  input: "Is The Rainbow Troops still in stock?",
});
console.log(response.output_text); // in the SDK, this property exists

Meaning: client is an object from OpenAI's official SDK (the openai library). client.responses.create sends a request to the Responses API (POST /v1/responses), which OpenAI recommends for new projects. A stock question doesn't need the model to think at length, so the effort is none. In the SDK, response.output_text holds the answer text directly.

⚡ Tokens, the unit you pay for

Meaning: A token is a piece of text the model processes, a word or part of a word. max_output_tokens limits the answer's length in tokens, and the cost is counted per token too.

⚡ output_text with plain fetch

Guess first: with plain fetch, data is the JSON from the response. Does console.log(data.output_text) print the model's answer or undefined?

undefined. That property exists only in the SDK, not in the raw JSON from the API.

Meaning: The text is in the output array: find the item of type message, then the output_text part of its content. Don't just take output[0]: a reasoning model can put a reasoning item first.

⚡ Cost from usage

Write:

const computeCost = (usage) => (usage.input_tokens * 0.10 + usage.output_tokens * 0.50) / 1_000_000;
computeCost({ input_tokens: 400, output_tokens: 40 }); // 0.00006 dollars

Meaning: usage in the response gives the number of input and output tokens. At the gpt-6-luna prices ($0.10 per 1 million input tokens, $0.50 per 1 million output tokens), 400 + 40 tokens cost $0.00006. Reasoning tokens (the tokens a model uses to think) are counted inside output_tokens and billed as output. The API key stays on the server, and a 401 (a wrong key) is never retried.

What you will learn