SpyBara
Go Premium

Documentation 2026-11-19 22:59 UTC to 2026-11-20 23:59 UTC

32 files changed +2,541 −411. View all changes and history on the product overview
2026
Thu 26 22:58 Wed 25 23:57 Tue 24 23:00 Mon 23 23:58 Sat 21 23:57 Fri 20 23:59 Thu 19 22:59 Wed 18 22:59 Tue 17 22:57 Mon 16 23:00 Fri 13 23:58 Thu 12 22:57 Wed 11 23:57 Tue 10 23:02 Mon 9 23:02 Sun 8 22:59 Sat 7 22:59 Fri 6 23:00 Thu 5 23:00 Wed 4 22:58 Tue 3 22:58 Mon 2 23:58 Sun 1 23:00
Details

54 54 

55 55 

56 56 

57The Go examples use the third-party `github.com/tiktoken-go/tokenizer` package, version `v0.10.0`. Install it in your Go module before running either complete example.57The Go examples use the third-party `github.com/tiktoken-go/tokenizer` package. Install it in your Go module before running either complete example.

58 

59 

60 

61 

62 

63 

64 

65The TypeScript counters use `js-tiktoken`. Install it in your project. Save the counter definition and the example messages below together as `counter.ts`, then run `node --experimental-strip-types counter.ts`. The counting rules apply to the historical model snapshot named in the code.

58 66 

59 67 

60 68 

61 69 

62Count chat message tokens70Count chat message tokens

63 71 

72```typescript

73import { getEncoding } from "js-tiktoken";

74 

75// Estimate this historical model's framing; other models and tools differ.

76function numTokensFromMessages(

77 messages: Record<string, string>[],

78 model = "gpt-3.5-turbo-0613"

79): number {

80 if (model !== "gpt-3.5-turbo-0613") {

81 throw new Error(`Unsupported token-counting model: ${model}`);

82 }

83 const encoding = getEncoding("cl100k_base");

84 let total = 3;

85 for (const message of messages) {

86 total += 3;

87 for (const [key, value] of Object.entries(message)) {

88 total += encoding.encode(value).length;

89 if (key === "name") total += 1;

90 }

91 }

92 return total;

93}

94```

95 

64```python96```python

65import tiktoken97import tiktoken

66 98 


148 180 

149Count tokens in an example prompt181Count tokens in an example prompt

150 182 

183```typescript

184const messages: Record<string, string>[] = [

185 {

186 role: "system",

187 content:

188 "You are a helpful, pattern-following assistant that translates corporate jargon into plain English.",

189 },

190 {

191 role: "system",

192 name: "example_user",

193 content: "New synergies will help drive top-line growth.",

194 },

195 {

196 role: "system",

197 name: "example_assistant",

198 content: "Things working well together will increase revenue.",

199 },

200 {

201 role: "system",

202 name: "example_user",

203 content:

204 "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage.",

205 },

206 {

207 role: "system",

208 name: "example_assistant",

209 content: "Let's talk later when we're less busy about how to do better.",

210 },

211 {

212 role: "user",

213 content:

214 "This late pivot means we don't have time to boil the ocean for the client deliverable.",

215 },

216];

217const model = "gpt-3.5-turbo-0613";

218console.log(`${numTokensFromMessages(messages, model)} prompt tokens counted.`);

219```

220 

151```python221```python

152messages = [222messages = [

153 {223 {


398 468 

399Set frequency and presence penalties469Set frequency and presence penalties

400 470 

471```typescript

472mu[j] =

473 mu[j] - counts[j] * alphaFrequency - (counts[j] > 0 ? alphaPresence : 0);

474```

475 

401```python476```python

402mu[j] = mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence477mu[j] = mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence

403```478```

Details

83 83 

84Find and download an artifact84Find and download an artifact

85 85 

86```typescript

87import { writeFile } from "node:fs/promises";

88import OpenAI from "openai";

89 

90const client = new OpenAI();

91 

92async function downloadArtifact(

93 sessionID: string,

94 turnID: string,

95 path: string,

96 destination: string

97): Promise<void> {

98 for await (const artifact of client.beta.agents.sessions.artifacts.list(

99 sessionID

100 )) {

101 if (artifact.turn_id !== turnID || artifact.path !== path) continue;

102 const content = await client.beta.agents.sessions.artifacts.content(

103 artifact.id,

104 { session_id: sessionID }

105 );

106 await writeFile(destination, Buffer.from(await content.arrayBuffer()));

107 return;

108 }

109 throw new Error(`No artifact for ${path} in turn ${turnID}`);

110}

111 

112await downloadArtifact(

113 "sess_123",

114 "turn_123",

115 "/workspace/outputs/report.pdf",

116 "report.pdf"

117);

118```

119 

86```python120```python

87# Pass the saved session ID, completed turn ID, artifact path, and local destination.121# Pass the saved session ID, completed turn ID, artifact path, and local destination.

88def download_artifact(client, session_id, turn_id, path, destination):122def download_artifact(client, session_id, turn_id, path, destination):

Details

114 114 

115 115 

116 116 

117For Ruby, install the `mcp` gem at version `1.10.0` and save the Ruby server as `/workspace/lookup_mcp.rb`. The Ruby example is tested with Ruby 3.3.117For Ruby, install the `mcp` gem and save the Ruby server as `/workspace/lookup_mcp.rb`.

118 

119 

120 

121 

122 

123 

124 

125In `/workspace`, install `@modelcontextprotocol/sdk` and `zod`, then save the TypeScript server as `/workspace/lookup_mcp.ts`. In the configuration below, set `transport.command` to the absolute path of your Node executable and `transport.args` to `["--experimental-strip-types", "/workspace/lookup_mcp.ts"]`. This server uses stdio without a transport argument.

118 126 

119 127 

120 128 

121 129 

122Run a customer lookup MCP server130Run a customer lookup MCP server

123 131 

132```typescript

133import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

134import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

135import { z } from "zod";

136 

137const server = new McpServer({ name: "customer-lookup", version: "1.0.0" });

138server.registerTool(

139 "get_customer",

140 {

141 description: "Look up a customer in the example data.",

142 inputSchema: { customer_id: z.string() },

143 },

144 async ({ customer_id }) => {

145 const customers = new Map([

146 ["123", { name: "Example Customer", plan: "pro" }],

147 ]);

148 const result = { customer: customers.get(customer_id) ?? null };

149 return { content: [{ type: "text", text: JSON.stringify(result) }] };

150 }

151);

152 

153await server.connect(new StdioServerTransport());

154```

155 

124```python156```python

125import sys157import sys

126 158 

Details

186 186 

187 187 

188 188 

189 

190 

191 

192Install `openai` and `jszip` in your project. Set `OPENAI_API_KEY`, then call `uploadPlugin` with your client and plugin directory. The helper returns the created session; retain its ID and delete the session when your application finishes using it.

193 

194 

195 

196 

189Upload a plugin folder197Upload a plugin folder

190 198 

199```typescript

200import {

201 mkdtemp,

202 mkdir,

203 readFile,

204 readdir,

205 rm,

206 writeFile,

207} from "node:fs/promises";

208import { tmpdir } from "node:os";

209import path from "node:path";

210import JSZip from "jszip";

211import OpenAI from "openai";

212 

213async function uploadPlugin(client: OpenAI, directory: string) {

214 directory = path.resolve(directory);

215 const manifest = JSON.parse(

216 await readFile(path.join(directory, ".codex-plugin/plugin.json"), "utf8")

217 );

218 if (

219 typeof manifest.name !== "string" ||

220 !manifest.name ||

221 typeof manifest.description !== "string" ||

222 !manifest.description

223 ) {

224 throw new Error("Plugin manifest requires a name and description");

225 }

226 const archive = new JSZip();

227 async function addDirectory(relative: string): Promise<void> {

228 for (const entry of await readdir(path.join(directory, relative), {

229 withFileTypes: true,

230 })) {

231 const member = path.join(relative, entry.name);

232 if (entry.isDirectory()) await addDirectory(member);

233 else if (entry.isFile()) {

234 const name = [path.basename(directory), ...member.split(path.sep)].join(

235 "/"

236 );

237 archive.file(name, await readFile(path.join(directory, member)));

238 } else

239 throw new Error(`Plugin archive requires regular files: ${member}`);

240 }

241 }

242 await addDirectory("");

243 return client.beta.agents.sessions.create({

244 agent: { model: "gpt-6-astra" },

245 environment: {

246 type: "openai_hosted",

247 plugins: [

248 {

249 type: "inline",

250 name: manifest.name,

251 description: manifest.description,

252 source: {

253 type: "base64",

254 media_type: "application/zip",

255 data: await archive.generateAsync({ type: "base64" }),

256 },

257 },

258 ],

259 },

260 });

261}

262```

263 

191```python264```python

192import base64265import base64

193import json266import json

Details

10 10 

11Actions can be triggered by attaching an `ActionConfig` to any widget node that supports it. For example, you can respond to click events on Buttons. When a user clicks on this button, the action will be sent to your server where you can update the widget, run inference, stream new thread items, etc.11Actions can be triggered by attaching an `ActionConfig` to any widget node that supports it. For example, you can respond to click events on Buttons. When a user clicks on this button, the action will be sent to your server where you can update the widget, run inference, stream new thread items, etc.

12 12 

13 

14 

15 

16The TypeScript widget uses the `Widgets.Button` type from `@openai/chatkit`. Install that package in your TypeScript project to type-check the widget payload. This example defines the button payload; your ChatKit integration renders the button and supplies its server-side action handler.

17 

18 

19 

20 

21```typescript

22import type { Widgets } from "@openai/chatkit";

23 

24const button: Widgets.Button = {

25 type: "Button",

26 label: "Example",

27 onClickAction: {

28 type: "example",

29 payload: { id: 123 },

30 },

31};

32```

33 

13```python34```python

14button = Button(35button = Button(

15 label="Example",36 label="Example",

Details

57 57 

58If your existing Global project already supports per-request data residency, you can continue using its API keys.58If your existing Global project already supports per-request data residency, you can continue using its API keys.

59 59 

60The following example reuses one client and an API key from a Global project for global, US, and EU requests:60The following example uses a Global project key for global and US requests and a separate EU project key for the EU request:

61 

62 

63 

64 

65Install `openai`. Set `OPENAI_API_KEY` for the global and US calls and `OPENAI_EU_API_KEY` for an EU-region project. Save the complete source as `per-request-regional-processing.ts` and run `node --experimental-strip-types per-request-regional-processing.ts`. The EU client clears the global project and organization headers.

66 

67 

68 

69 

70```typescript

71import OpenAI from "openai";

72 

73const euKey = process.env.OPENAI_EU_API_KEY;

74if (!euKey) throw new Error("Set OPENAI_EU_API_KEY to an EU-project API key");

75 

76const client = new OpenAI();

77console.log(

78 (

79 await client.responses.create({

80 model: "gpt-6.1-terra",

81 input: "Reply with OK.",

82 })

83 ).output_text

84);

85 

86console.log(

87 (

88 await client.withOptions({ dataResidency: "us" }).responses.create({

89 model: "gpt-6.1-terra",

90 input: "Reply with OK.",

91 })

92 ).output_text

93);

94 

95// EU processing requires a key from an EU-region project.

96console.log(

97 (

98 await client

99 .withOptions({

100 dataResidency: "eu",

101 apiKey: euKey,

102 organization: null,

103 project: null,

104 })

105 .responses.create({

106 model: "gpt-6.1-terra",

107 input: "Reply with OK.",

108 })

109 ).output_text

110);

111```

61 112 

62```python113```python

63import os114import os

Details

1849The TypeScript sample uses `npm install openai@^7.10.0 ws`.1849The TypeScript sample uses `npm install openai@^7.10.0 ws`.

1850The Ruby sample uses `gem install openai async-websocket`.1850The Ruby sample uses `gem install openai async-websocket`.

1851 1851 

1852For Go, run `go get github.com/openai/openai-go/v3@v3.103.0`.1852For Go, run `go get github.com/openai/openai-go/v3@v3.104.0`.

1853For Java, add the Maven dependency `com.openai:openai-java:4.105.0`.1853For Java, add the Maven dependency `com.openai:openai-java:4.105.0`.

1854These Go and Java SDK versions provide native Responses WebSocket support.1854These Go and Java SDK versions provide native Responses WebSocket support.

1855 1855 

Details

204 204 

205 205 

206 206 

207 

208 

209 

210Download and extract the [TypeScript samples and locked dependencies](https://developers.openai.com/api/docs/samples/typescript.tar.gz), including OpenAI and the CSV parser and writer. Save the review dataset as `data/fine_food_reviews_1k.csv` and set `OPENAI_API_KEY`. Keep `Summary`, `Text`, `Score`, `UserId`, and `ProductId`; the producer preserves these columns in its output for the analysis programs. Use a dataset with at least four rows for the four-cluster example.

211 

212 

213 

214 

207Create review embeddings215Create review embeddings

208 216 

209```typescript217```typescript

210import { mkdir, writeFile } from "node:fs/promises";218import { mkdir, readFile, writeFile } from "node:fs/promises";

219import { parse } from "csv-parse/sync";

220import { stringify } from "csv-stringify/sync";

211import OpenAI from "openai";221import OpenAI from "openai";

212 222 

223const reviews: Record<string, string>[] = parse(

224 await readFile("data/fine_food_reviews_1k.csv", "utf8"),

225 { columns: true, skip_empty_lines: true }

226);

227if (!reviews.length) throw new Error("No reviews in the input CSV");

228for (const review of reviews) {

229 for (const column of ["Summary", "Text", "Score", "UserId", "ProductId"]) {

230 if (typeof review[column] !== "string" || !review[column].trim())

231 throw new Error(`Review is missing ${column}`);

232 }

233 const score = Number(review.Score);

234 if (!Number.isInteger(score) || score < 1 || score > 5)

235 throw new Error("Score must be an integer from 1 to 5");

236}

237const combined = reviews.map((review) =>

238 `${review.Summary} ${review.Text}`.replaceAll("\n", " ")

239);

213const client = new OpenAI();240const client = new OpenAI();

214const reviews = ["A rich cup of coffee.", "A bright herbal tea."];

215 

216const response = await client.embeddings.create({241const response = await client.embeddings.create({

217 model: "text-embedding-3-small",242 model: "text-embedding-3-small",

218 input: reviews.map((review) => review.replaceAll("\n", " ")),243 input: combined,

244});

245const embeddings = [...response.data].sort((a, b) => a.index - b.index);

246if (embeddings.length !== reviews.length)

247 throw new Error("Embedding response did not include every review");

248const rows = reviews.map((review, index) => {

249 if (embeddings[index].index !== index)

250 throw new Error("Embedding response has invalid review indices");

251 return {

252 ...review,

253 combined: combined[index],

254 ada_embedding: JSON.stringify(embeddings[index].embedding),

255 };

219});256});

220 

221const csvField = (value: string) => `"${value.replaceAll('"', '""')}"`;

222const rows = response.data.map(({ embedding }, index) =>

223 [csvField(reviews[index]), csvField(JSON.stringify(embedding))].join(",")

224);

225 

226await mkdir("output", { recursive: true });257await mkdir("output", { recursive: true });

227await writeFile(258await writeFile(

228 "output/embedded_1k_reviews.csv",259 "output/embedded_1k_reviews.csv",

229 ["combined,ada_embedding", ...rows].join("\n") + "\n"260 stringify(rows, { header: true })

230);261);

231```262```

232 263 


442 473 

443 474 

444 475 

445For Ruby, use Ruby 3.3 and install the [sample project dependencies](https://github.com/openai/developers-website/blob/main/src/content/platform/ruby-examples/Gemfile). Append the loading and analysis snippets to the same Ruby file; run the split before either forest example. The metrics below come from the linked Python notebooks and depend on the dataset and implementation.476For Ruby, install the [sample project dependencies](https://developers.openai.com/api/docs/samples/ruby-Gemfile). Append the loading and analysis snippets to the same Ruby file; run the split before either forest example. The metrics below come from the linked Python notebooks and depend on the dataset and implementation.

477 

478 

479 

480 

481 

482 

483 

484Download and extract the [TypeScript samples and locked dependencies](https://developers.openai.com/api/docs/samples/typescript.tar.gz). From the extracted `typescript-examples` directory, install with `pnpm install --ignore-workspace --frozen-lockfile`. Run each complete analysis program separately with `node --experimental-strip-types embeddings/<filename>.ts` from that directory.

485 

486The programs read `output/embedded_1k_reviews.csv` with JSON arrays in `ada_embedding` and numeric review ratings in `Score`. Grouped averages also require `UserId` and `ProductId`. Each program loads its own input; do not concatenate the excerpts. The linked Python notebooks supply the metrics below. Results from the TypeScript algorithms can differ from those metrics, and t-SNE coordinates can vary between runs.

446 487 

447 488 

448 489 


451 492 

452Load saved embeddings493Load saved embeddings

453 494 

495```typescript

496import { readFile } from "node:fs/promises";

497import { parse } from "csv-parse/sync";

498 

499const records: { Score: string; ada_embedding: string }[] = parse(

500 await readFile("output/embedded_1k_reviews.csv", "utf8"),

501 { columns: true, skip_empty_lines: true }

502);

503const rows = records.map((row) => ({

504 score: Number(row.Score),

505 embedding: JSON.parse(row.ada_embedding) as number[],

506}));

507if (!rows.length) throw new Error("No embeddings");

508const dimensions = rows[0].embedding.length;

509for (const row of rows) {

510 if (

511 !Number.isFinite(row.score) ||

512 !Array.isArray(row.embedding) ||

513 !dimensions ||

514 row.embedding.length !== dimensions ||

515 !row.embedding.every(Number.isFinite)

516 ) {

517 throw new Error(

518 "Expected finite scores and embeddings with consistent dimensions"

519 );

520 }

521}

522console.log(rows);

523```

524 

454```python525```python

455from ast import literal_eval526from ast import literal_eval

456import pandas as pd527import pandas as pd


1734 1805 

1735 1806 

1736 1807 

1737The Go plotting example uses `github.com/danaugrs/go-tsne/tsne` at `v0.0.0-20220306155740-2250969e057f`, `gonum.org/v1/gonum` at `v0.16.0`, and `gonum.org/v1/plot` at `v0.16.0`. It writes `local-plot.png` and prints the transformed coordinates and rating-color indices.1808The Go plotting example uses `github.com/danaugrs/go-tsne/tsne`, `gonum.org/v1/gonum`, and `gonum.org/v1/plot`. It writes `local-plot.png` and prints the transformed coordinates and rating-color indices.

1738 1809 

1739 1810 

1740 1811 

1741 1812 

1742Visualize embeddings with t-SNE1813Visualize embeddings with t-SNE

1743 1814 

1815```typescript

1816import { readFile } from "node:fs/promises";

1817import { parse } from "csv-parse/sync";

1818 

1819const records: {

1820 Score: string;

1821 ada_embedding: string;

1822 UserId: string;

1823 ProductId: string;

1824}[] = parse(await readFile("output/embedded_1k_reviews.csv", "utf8"), {

1825 columns: true,

1826 skip_empty_lines: true,

1827});

1828const rows = records.map((row) => ({

1829 score: Number(row.Score),

1830 embedding: JSON.parse(row.ada_embedding) as number[],

1831 userID: row.UserId,

1832 productID: row.ProductId,

1833}));

1834if (!rows.length) throw new Error("No reviews");

1835const dimensions = rows[0].embedding.length;

1836for (const row of rows) {

1837 if (

1838 !Number.isFinite(row.score) ||

1839 !Array.isArray(row.embedding) ||

1840 !dimensions ||

1841 row.embedding.length !== dimensions ||

1842 !row.embedding.every(Number.isFinite)

1843 ) {

1844 throw new Error(

1845 "Expected finite scores and embeddings with consistent dimensions"

1846 );

1847 }

1848}

1849 

1850import TSNE from "tsne-js";

1851import { createCanvas } from "@napi-rs/canvas";

1852import { writeFile } from "node:fs/promises";

1853 

1854const model = new TSNE({

1855 dim: 2,

1856 perplexity: 15,

1857 learningRate: 200,

1858 nIter: 1000,

1859 metric: "euclidean",

1860});

1861model.init({ data: rows.map((row) => row.embedding), type: "dense" });

1862model.run();

1863const points = model.getOutput();

1864const colors = ["red", "darkorange", "gold", "turquoise", "darkgreen"];

1865const colorIndices = rows.map((row) => row.score - 1);

1866const canvas = createCanvas(800, 600);

1867const context = canvas.getContext("2d");

1868context.fillStyle = "white";

1869context.fillRect(0, 0, 800, 600);

1870context.fillStyle = "black";

1871context.font = "20px sans-serif";

1872context.fillText("Amazon ratings visualized using t-SNE", 40, 30);

1873const xs = points.map((point) => point[0]);

1874const ys = points.map((point) => point[1]);

1875const minX = Math.min(...xs),

1876 maxX = Math.max(...xs);

1877const minY = Math.min(...ys),

1878 maxY = Math.max(...ys);

1879const plotted: number[][] = [];

1880for (const [index, point] of points.entries()) {

1881 if (point.length !== 2 || !point.every(Number.isFinite))

1882 throw new Error("Invalid t-SNE point");

1883 const x = 40 + ((point[0] - minX) / (maxX - minX || 1)) * 720;

1884 const y = 560 - ((point[1] - minY) / (maxY - minY || 1)) * 500;

1885 context.fillStyle = colors[colorIndices[index]];

1886 context.globalAlpha = 0.3;

1887 context.beginPath();

1888 context.arc(x, y, 6, 0, Math.PI * 2);

1889 context.fill();

1890 plotted.push(point);

1891}

1892await writeFile("local-plot.png", await canvas.encode("png"));

1893```

1894 

1744```python1895```python

1745from ast import literal_eval1896from ast import literal_eval

1746import numpy as np1897import numpy as np


1969 2120 

1970Split the dataset for training and testing2121Split the dataset for training and testing

1971 2122 

2123```typescript

2124import { readFile } from "node:fs/promises";

2125import { parse } from "csv-parse/sync";

2126 

2127const records: {

2128 Score: string;

2129 ada_embedding: string;

2130 UserId: string;

2131 ProductId: string;

2132}[] = parse(await readFile("output/embedded_1k_reviews.csv", "utf8"), {

2133 columns: true,

2134 skip_empty_lines: true,

2135});

2136const rows = records.map((row) => ({

2137 score: Number(row.Score),

2138 embedding: JSON.parse(row.ada_embedding) as number[],

2139 userID: row.UserId,

2140 productID: row.ProductId,

2141}));

2142if (!rows.length) throw new Error("No reviews");

2143const dimensions = rows[0].embedding.length;

2144for (const row of rows) {

2145 if (

2146 !Number.isFinite(row.score) ||

2147 !Array.isArray(row.embedding) ||

2148 !dimensions ||

2149 row.embedding.length !== dimensions ||

2150 !row.embedding.every(Number.isFinite)

2151 ) {

2152 throw new Error(

2153 "Expected finite scores and embeddings with consistent dimensions"

2154 );

2155 }

2156}

2157 

2158// Shuffle whole rows so labels stay paired with their embedding vectors.

2159const shuffled = [...rows];

2160let seed = 42;

2161for (let i = shuffled.length - 1; i > 0; i--) {

2162 seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;

2163 const j = Math.floor((seed / 2 ** 32) * (i + 1));

2164 [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];

2165}

2166const testSize = Math.ceil(shuffled.length * 0.2);

2167const testRows = shuffled.slice(0, testSize);

2168const trainRows = shuffled.slice(testSize);

2169const trainVectors = trainRows.map((row) => row.embedding);

2170const trainScores = trainRows.map((row) => row.score);

2171const testVectors = testRows.map((row) => row.embedding);

2172const testScores = testRows.map((row) => row.score);

2173```

2174 

1972```python2175```python

1973from sklearn.model_selection import train_test_split2176from sklearn.model_selection import train_test_split

1974 2177 


2111 2314 

2112 2315 

2113 2316 

2114The Go example uses `github.com/wlattner/rf/forest` from module version `v0.0.0-20150304005020-e98c6ca28b25`. It fits 100 trees on the training partition and predicts the held-out rows. Install the pinned module version before running the program.2317The Go example uses `github.com/wlattner/rf/forest`. It fits 100 trees on the training partition and predicts the held-out rows. Install the module before running the program.

2115 2318 

2116 2319 

2117 2320 

2118 2321 

2119Predict review scores2322Predict review scores

2120 2323 

2324```typescript

2325import { readFile } from "node:fs/promises";

2326import { parse } from "csv-parse/sync";

2327 

2328const records: {

2329 Score: string;

2330 ada_embedding: string;

2331 UserId: string;

2332 ProductId: string;

2333}[] = parse(await readFile("output/embedded_1k_reviews.csv", "utf8"), {

2334 columns: true,

2335 skip_empty_lines: true,

2336});

2337const rows = records.map((row) => ({

2338 score: Number(row.Score),

2339 embedding: JSON.parse(row.ada_embedding) as number[],

2340 userID: row.UserId,

2341 productID: row.ProductId,

2342}));

2343if (!rows.length) throw new Error("No reviews");

2344const dimensions = rows[0].embedding.length;

2345for (const row of rows) {

2346 if (

2347 !Number.isFinite(row.score) ||

2348 !Array.isArray(row.embedding) ||

2349 !dimensions ||

2350 row.embedding.length !== dimensions ||

2351 !row.embedding.every(Number.isFinite)

2352 ) {

2353 throw new Error(

2354 "Expected finite scores and embeddings with consistent dimensions"

2355 );

2356 }

2357}

2358 

2359// Shuffle whole rows so labels stay paired with their embedding vectors.

2360const shuffled = [...rows];

2361let seed = 42;

2362for (let i = shuffled.length - 1; i > 0; i--) {

2363 seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;

2364 const j = Math.floor((seed / 2 ** 32) * (i + 1));

2365 [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];

2366}

2367const testSize = Math.ceil(shuffled.length * 0.2);

2368const testRows = shuffled.slice(0, testSize);

2369const trainRows = shuffled.slice(testSize);

2370const trainVectors = trainRows.map((row) => row.embedding);

2371const trainScores = trainRows.map((row) => row.score);

2372const testVectors = testRows.map((row) => row.embedding);

2373const testScores = testRows.map((row) => row.score);

2374 

2375import { RandomForestRegression } from "ml-random-forest";

2376const forest = new RandomForestRegression({

2377 nEstimators: 100,

2378 seed: 42,

2379 maxFeatures: trainVectors[0].length,

2380 // Evaluate on the held-out test rows instead of out-of-bag samples.

2381 noOOB: true,

2382});

2383forest.train(trainVectors, trainScores);

2384const predictions = forest.predict(testVectors);

2385console.log(predictions);

2386```

2387 

2121```python2388```python

2122from sklearn.ensemble import RandomForestRegressor2389from sklearn.ensemble import RandomForestRegressor

2123 2390 


2283 2550 

2284 2551 

2285 2552 

2286The Go example uses `github.com/wlattner/rf/forest` from module version `v0.0.0-20150304005020-e98c6ca28b25`. It fits 100 trees on the training partition and predicts the held-out rows. Install the pinned module version before running the program.2553The Go example uses `github.com/wlattner/rf/forest`. It fits 100 trees on the training partition and predicts the held-out rows. Install the module before running the program.

2287 2554 

2288 2555 

2289 2556 

2290 2557 

2291Classify review scores2558Classify review scores

2292 2559 

2560```typescript

2561import { readFile } from "node:fs/promises";

2562import { parse } from "csv-parse/sync";

2563 

2564const records: {

2565 Score: string;

2566 ada_embedding: string;

2567 UserId: string;

2568 ProductId: string;

2569}[] = parse(await readFile("output/embedded_1k_reviews.csv", "utf8"), {

2570 columns: true,

2571 skip_empty_lines: true,

2572});

2573const rows = records.map((row) => ({

2574 score: Number(row.Score),

2575 embedding: JSON.parse(row.ada_embedding) as number[],

2576 userID: row.UserId,

2577 productID: row.ProductId,

2578}));

2579if (!rows.length) throw new Error("No reviews");

2580const dimensions = rows[0].embedding.length;

2581for (const row of rows) {

2582 if (

2583 !Number.isFinite(row.score) ||

2584 !Array.isArray(row.embedding) ||

2585 !dimensions ||

2586 row.embedding.length !== dimensions ||

2587 !row.embedding.every(Number.isFinite)

2588 ) {

2589 throw new Error(

2590 "Expected finite scores and embeddings with consistent dimensions"

2591 );

2592 }

2593}

2594 

2595// Shuffle whole rows so labels stay paired with their embedding vectors.

2596const shuffled = [...rows];

2597let seed = 42;

2598for (let i = shuffled.length - 1; i > 0; i--) {

2599 seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;

2600 const j = Math.floor((seed / 2 ** 32) * (i + 1));

2601 [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];

2602}

2603const testSize = Math.ceil(shuffled.length * 0.2);

2604const testRows = shuffled.slice(0, testSize);

2605const trainRows = shuffled.slice(testSize);

2606const trainVectors = trainRows.map((row) => row.embedding);

2607const trainScores = trainRows.map((row) => row.score);

2608const testVectors = testRows.map((row) => row.embedding);

2609const testScores = testRows.map((row) => row.score);

2610 

2611import { RandomForestClassifier } from "ml-random-forest";

2612const forest = new RandomForestClassifier({

2613 nEstimators: 100,

2614 seed: 42,

2615 maxFeatures: trainVectors[0].length,

2616});

2617forest.train(trainVectors, trainScores);

2618const predictions = forest.predict(testVectors);

2619console.log(predictions);

2620```

2621 

2293```python2622```python

2294from sklearn.ensemble import RandomForestClassifier2623from sklearn.ensemble import RandomForestClassifier

2295from sklearn.metrics import classification_report, accuracy_score2624from sklearn.metrics import classification_report, accuracy_score


2682 3011 

2683Average user and product embeddings3012Average user and product embeddings

2684 3013 

3014```typescript

3015import { readFile } from "node:fs/promises";

3016import { parse } from "csv-parse/sync";

3017 

3018const records: {

3019 Score: string;

3020 ada_embedding: string;

3021 UserId: string;

3022 ProductId: string;

3023}[] = parse(await readFile("output/embedded_1k_reviews.csv", "utf8"), {

3024 columns: true,

3025 skip_empty_lines: true,

3026});

3027const rows = records.map((row) => ({

3028 score: Number(row.Score),

3029 embedding: JSON.parse(row.ada_embedding) as number[],

3030 userID: row.UserId,

3031 productID: row.ProductId,

3032}));

3033if (!rows.length) throw new Error("No reviews");

3034const dimensions = rows[0].embedding.length;

3035for (const row of rows) {

3036 if (

3037 !Number.isFinite(row.score) ||

3038 !Array.isArray(row.embedding) ||

3039 !dimensions ||

3040 row.embedding.length !== dimensions ||

3041 !row.embedding.every(Number.isFinite)

3042 ) {

3043 throw new Error(

3044 "Expected finite scores and embeddings with consistent dimensions"

3045 );

3046 }

3047}

3048 

3049function averageEmbeddings(

3050 key: "userID" | "productID"

3051): Record<string, number[]> {

3052 const groups = new Map<string, { sum: number[]; count: number }>();

3053 for (const row of rows) {

3054 if (!row[key]) throw new Error(`Missing ${key}`);

3055 const group = groups.get(row[key]) ?? {

3056 sum: Array(dimensions).fill(0),

3057 count: 0,

3058 };

3059 row.embedding.forEach((value, i) => {

3060 group.sum[i] += value;

3061 });

3062 group.count++;

3063 groups.set(row[key], group);

3064 }

3065 return Object.fromEntries(

3066 [...groups].map(([id, group]) => [

3067 id,

3068 group.sum.map((value) => value / group.count),

3069 ])

3070 );

3071}

3072const userEmbeddings = averageEmbeddings("userID");

3073const productEmbeddings = averageEmbeddings("productID");

3074```

3075 

2685```python3076```python

2686user_embeddings = df.groupby("UserId").ada_embedding.apply(np.mean)3077user_embeddings = df.groupby("UserId").ada_embedding.apply(np.mean)

2687prod_embeddings = df.groupby("ProductId").ada_embedding.apply(np.mean)3078prod_embeddings = df.groupby("ProductId").ada_embedding.apply(np.mean)


2851 3242 

2852Cluster embeddings3243Cluster embeddings

2853 3244 

3245```typescript

3246import { readFile } from "node:fs/promises";

3247import { parse } from "csv-parse/sync";

3248 

3249const records: {

3250 Score: string;

3251 ada_embedding: string;

3252 UserId: string;

3253 ProductId: string;

3254}[] = parse(await readFile("output/embedded_1k_reviews.csv", "utf8"), {

3255 columns: true,

3256 skip_empty_lines: true,

3257});

3258const rows = records.map((row) => ({

3259 score: Number(row.Score),

3260 embedding: JSON.parse(row.ada_embedding) as number[],

3261 userID: row.UserId,

3262 productID: row.ProductId,

3263}));

3264if (!rows.length) throw new Error("No reviews");

3265const dimensions = rows[0].embedding.length;

3266for (const row of rows) {

3267 if (

3268 !Number.isFinite(row.score) ||

3269 !Array.isArray(row.embedding) ||

3270 !dimensions ||

3271 row.embedding.length !== dimensions ||

3272 !row.embedding.every(Number.isFinite)

3273 ) {

3274 throw new Error(

3275 "Expected finite scores and embeddings with consistent dimensions"

3276 );

3277 }

3278}

3279 

3280import { kmeans } from "ml-kmeans";

3281 

3282const matrix = rows.map((row) => row.embedding);

3283const clusters = kmeans(matrix, 4, { seed: 42, initialization: "kmeans++" });

3284console.log(clusters.clusters);

3285```

3286 

2854```python3287```python

2855import numpy as np3288import numpy as np

2856from sklearn.cluster import KMeans3289from sklearn.cluster import KMeans


3072 3505 

3073Count tokens before embedding3506Count tokens before embedding

3074 3507 

3508```typescript

3509import { getEncoding } from "js-tiktoken";

3510import type { TiktokenEncoding } from "js-tiktoken";

3511 

3512function numTokensFromString(

3513 text: string,

3514 encodingName: TiktokenEncoding

3515): number {

3516 return getEncoding(encodingName).encode(text).length;

3517}

3518 

3519console.log(numTokensFromString("tiktoken is great!", "cl100k_base"));

3520```

3521 

3075```python3522```python

3076import tiktoken3523import tiktoken

3077 3524 


3126 3573 

3127 3574 

3128 3575 

3129The Go example uses the third-party `github.com/tiktoken-go/tokenizer` package, version `v0.10.0`. Install it in your Go module before running the example.3576The Go example uses the third-party `github.com/tiktoken-go/tokenizer` package. Install it in your Go module before running the example.

3130 3577 

3131 3578 

3132 3579 

Details

169- Reduce your request rate, then increase it gradually.169- Reduce your request rate, then increase it gradually.

170- Keep your traffic pattern steady to reduce the chance of another `slow_down` error.170- Keep your traffic pattern steady to reduce the chance of another `slow_down` error.

171 171 

172Enterprise customers whose pay-as-you-go traffic routinely hits ramp-rate limits can consider [Scale Tier](https://openai.com/api-scale-tier/) for more predictable capacity on eligible models. For GPT-5.6 and later models, see [Reserved Tier](https://openai.com/api-reserved-tier/). These capacity options don't replace the recovery steps above: continue to follow `Retry-After` when it's present and ramp traffic gradually.172Enterprise customers whose pay-as-you-go traffic routinely hits ramp-rate limits can consider [Scale Tier](https://openai.com/api-scale-tier/) for more predictable capacity on eligible models. For GPT-5.6 and later models, see [Reserved Tier](https://developers.openai.com/api/docs/guides/reserved-tier). These capacity options don't replace the recovery steps above: continue to follow `Retry-After` when it's present and ramp traffic gradually.

173 173 

174 174 

175 175 

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Flex processing provides lower costs for [Responses](https://developers.openai.com/api/reference/resources/responses) or [Chat Completions](https://developers.openai.com/api/reference/resources/chat) requests in exchange for slower response times and occasional resource unavailability. It's ideal for non-production or lower priority tasks, such as model evaluations, data enrichment, and asynchronous workloads.5You can continue using Flex processing on [supported models](https://developers.openai.com/api/docs/pricing?latest-pricing=flex) as we wind down the beta. Flex is unavailable on GPT-6.2 Astra and GPT-6.2 Sol, and we won’t be adding it to future models. We’ll share the retirement date and migration guidance here once the date is confirmed.

6 6 

7Tokens are [priced](https://developers.openai.com/api/docs/pricing) at [Batch API rates](https://developers.openai.com/api/docs/guides/batch), with additional discounts from [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).7For workloads that can run asynchronously, [background mode in the Responses API](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows) offers discounted completion windows on supported models. The 2-hour window is 30% below Standard token pricing, and the 8-hour window is 40% below. The discount applies to every eligible request, including follow-ups.

8 8 

9Flex processing is in beta with limited model availability. Supported models9Flex processing provides lower costs for [Responses](https://developers.openai.com/api/reference/resources/responses) or [Chat Completions](https://developers.openai.com/api/reference/resources/chat) requests in exchange for slower response times and occasional resource unavailability.

10 are listed on the [pricing page](https://developers.openai.com/api/docs/pricing?latest-pricing=flex).

11 10 

12For asynchronous Responses API workflows that can wait longer for the initial response, see [discounted background completion windows](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows). These windows use Standard processing.11Tokens are [priced](https://developers.openai.com/api/docs/pricing) at [Batch API rates](https://developers.openai.com/api/docs/guides/batch), with additional discounts from [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching).

13 12 

14## API usage13## API usage

15 14 

Details

343 343 

344Run a Python grader through the API344Run a Python grader through the API

345 345 

346```typescript

347import { readFileSync } from "node:fs";

348import OpenAI from "openai";

349 

350const client = new OpenAI();

351// Save the Python grading function as grader.py before running this program.

352const grader = {

353 type: "python" as const,

354 name: "answer_overlap",

355 source: readFileSync("grader.py", "utf8"),

356};

357 

358console.log(await client.fineTuning.alpha.graders.validate({ grader }));

359console.log(

360 await client.fineTuning.alpha.graders.run({

361 grader,

362 item: { reference_answer: "fuzzy wuzzy had no hair" },

363 model_sample: "fuzzy wuzzy was a bear",

364 })

365);

366```

367 

346```python368```python

347import os369import os

348import requests370import requests


445 467 

446 468 

447**Tip:**469**Tip:**

448If you don't want to manually put your grading function in a string, you can also load it from a Python file using `importlib` and `inspect`. For example, if your grader function is in a file named `grader.py`, you can do:470You can load your grading function from a file named `grader.py` instead of embedding it in a string.

471 

472 

473 

474 

475Python uses `importlib` and `inspect` to load the grading function.

476 

477 

478 

449 479 

450Load a grader from a Python file480Load a grader from a Python file

451 481 

482```typescript

483import { readFileSync } from "node:fs";

484 

485// The service executes Python; TypeScript reads the grader's source file.

486const grader = {

487 type: "python" as const,

488 name: "answer_overlap",

489 source: readFileSync("grader.py", "utf8"),

490};

491```

492 

452```python493```python

453import importlib494import importlib

454import inspect495import inspect

Details

2576 2576 

2577Edit the circled vase with the Image API2577Edit the circled vase with the Image API

2578 2578 

2579```typescript

2580import { createReadStream } from "node:fs";

2581import { writeFile } from "node:fs/promises";

2582import OpenAI, { toFile } from "openai";

2583 

2584const client = new OpenAI();

2585const response = await client.images.edit({

2586 model: "gpt-image-2.6-flare",

2587 image: await toFile(createReadStream("kitchen.webp"), "kitchen.webp", {

2588 type: "image/webp",

2589 }),

2590 markup: await toFile(

2591 createReadStream("markup-vase-overlay-gpt-image-2-6.png"),

2592 "markup-vase-overlay-gpt-image-2-6.png",

2593 { type: "image/png" }

2594 ),

2595 quality: "medium",

2596 prompt:

2597 "Recolor the striped vase inside the red circle to solid cobalt blue ceramic. " +

2598 "Keep its shape, the dried stems, and the rest of the kitchen unchanged. " +

2599 "Remove the red circle from the finished photo.",

2600});

2601const encoded = response.data?.[0]?.b64_json;

2602if (!encoded) throw new Error("Image edit returned no image");

2603await writeFile("vase.png", Buffer.from(encoded, "base64"));

2604```

2605 

2579```python2606```python

2580import base642607import base64

2581from pathlib import Path2608from pathlib import Path


3221 3248 

3222Add an alpha channel to a black and white mask3249Add an alpha channel to a black and white mask

3223 3250 

3251```typescript

3252import { execFileSync } from "node:child_process";

3253 

3254// Requires FFmpeg. Use the grayscale mask as both color and alpha.

3255execFileSync("ffmpeg", [

3256 "-v",

3257 "error",

3258 "-y",

3259 "-i",

3260 "mask.png",

3261 "-i",

3262 "mask.png",

3263 "-filter_complex",

3264 "[0:v]format=rgb24[color];[color][1:v]alphamerge",

3265 "-frames:v",

3266 "1",

3267 "mask_alpha.png",

3268]);

3269```

3270 

3224```python3271```python

3225from PIL import Image3272from PIL import Image

3226from io import BytesIO3273from io import BytesIO

Details

1331 1331 

1332Generate four logo variations and extract a product onto a transparent background with the 2.6 model you want to test.1332Generate four logo variations and extract a product onto a transparent background with the 2.6 model you want to test.

1333 1333 

1334Install the [OpenAI SDK](https://developers.openai.com/api/docs/libraries#install-an-official-sdk) with `pip install openai` for Python or `gem install openai` for Ruby. Set `OPENAI_API_KEY` and save the [product photograph](https://developers.openai.com/images/platform/guides/image-prompting/shampoo.webp) as `input_images/shampoo.webp`.1334Set `OPENAI_API_KEY` and save the [product photograph](https://developers.openai.com/images/platform/guides/image-prompting/shampoo.webp) as `input_images/shampoo.webp`. The program writes four PNG logo files and `extract-product.png`.

1335 

1336 

1337 

1338 

1339Install the [OpenAI SDK](https://developers.openai.com/api/docs/libraries#install-an-official-sdk) with `pip install openai` and save the sample as `demo.py`. Run `python demo.py gpt-image-2.6-flare`, or pass `gpt-image-2.6-sunburst` instead.

1340 

1341 

1342 

1343 

1344 

1345 

1346 

1347Install the [OpenAI SDK](https://developers.openai.com/api/docs/libraries#install-an-official-sdk) with `gem install openai` and save the sample as `demo.rb`. Run `ruby demo.rb gpt-image-2.6-flare`, or pass `gpt-image-2.6-sunburst` instead.

1348 

1349 

1350 

1351 

1352 

1353 

1354 

1355Install `openai` in your project and save the sample as `demo.ts`. Run `node --experimental-strip-types demo.ts gpt-image-2.6-flare`, or pass `gpt-image-2.6-sunburst` instead.

1356 

1357 

1335 1358 

1336Save the sample as `demo.py` or `demo.rb`. To try Flare, run `python demo.py gpt-image-2.6-flare` or `ruby demo.rb gpt-image-2.6-flare`. To try Sunburst, pass `gpt-image-2.6-sunburst` instead. The script writes four logo files in PNG format and `extract-product.png`.

1337 1359 

1338 1360 

1339 1361 


1342 1364 

1343 Generate and edit transparent assets1365 Generate and edit transparent assets

1344 1366 

1367```typescript

1368import { createReadStream } from "node:fs";

1369import { writeFile } from "node:fs/promises";

1370import OpenAI, { toFile } from "openai";

1371 

1372const model = process.argv[2];

1373if (!model)

1374 throw new Error("Usage: node transparent-assets-for-model.ts MODEL_ID");

1375const suffix = ".png";

1376const client = new OpenAI();

1377const logos = await client.images.generate({

1378 model,

1379 prompt:

1380 "Create an original logo for Field & Flour, a local bakery. Use warm, simple shapes on a fully transparent background, with clean alpha edges and no shadow or checkerboard.",

1381 size: "1024x1536",

1382 quality: "medium",

1383 background: "transparent",

1384 output_format: "png",

1385 n: 4,

1386});

1387if (logos.data?.length !== 4) throw new Error("Expected four logo candidates");

1388for (const [index, image] of logos.data.entries()) {

1389 await saveImage(`logo-generation-${index + 1}${suffix}`, image.b64_json);

1390}

1391 

1392const cutout = await client.images.edit({

1393 model,

1394 image: await toFile(

1395 createReadStream("input_images/shampoo.webp"),

1396 "shampoo.webp",

1397 {

1398 type: "image/webp",

1399 }

1400 ),

1401 prompt:

1402 "Extract the product onto a fully transparent background. Preserve its geometry and label, with clean edges and no shadow or restyling.",

1403 size: "1024x1536",

1404 quality: "medium",

1405 background: "transparent",

1406 output_format: "png",

1407});

1408if (cutout.data?.length !== 1) throw new Error("Expected one product cutout");

1409await saveImage(`extract-product${suffix}`, cutout.data[0].b64_json);

1410 

1411async function saveImage(

1412 filename: string,

1413 encoded: string | undefined

1414): Promise<void> {

1415 if (!encoded) throw new Error("No PNG returned");

1416 await writeFile(filename, Buffer.from(encoded, "base64"));

1417}

1418```

1419 

1345```python1420```python

1346import argparse1421import argparse

1347import base641422import base64


2844 2919 

2845## Run a complete example2920## Run a complete example

2846 2921 

2847This runnable example remains pinned to `gpt-image-2`. Use it as a baseline, then choose an available model and its supported request settings for your evaluation.2922This runnable example remains pinned to `gpt-image-2.5-sunburst`. Use it as a baseline, then choose an available model and its supported request settings for your evaluation.

2923 

2924The examples below generate four logo variations and extract a product onto a transparent background. Set `OPENAI_API_KEY` and save the [product photograph](https://developers.openai.com/images/platform/guides/image-prompting/shampoo.webp) as `input_images/shampoo.webp`. Live requests incur API usage charges.

2925 

2926 

2927 

2928 

2929Install the [OpenAI SDK](https://developers.openai.com/api/docs/libraries#install-an-official-sdk) with `pip install openai` for Python.

2930 

2931 

2932 

2933 

2934 

2935 

2936 

2937Install the [OpenAI SDK](https://developers.openai.com/api/docs/libraries#install-an-official-sdk) with `gem install openai` for Ruby.

2938 

2939 

2940 

2941 

2942 

2943 

2944 

2945Install `openai` in your project and save the complete TypeScript sample as `demo.ts`. With the image file saved and the API key set, run `node --experimental-strip-types demo.ts`.

2946 

2947 

2848 2948 

2849The examples below generate four logo variations and extract a product onto a transparent background. Install the [OpenAI SDK](https://developers.openai.com/api/docs/libraries#install-an-official-sdk) with `pip install openai` for Python or `gem install openai` for Ruby. Set `OPENAI_API_KEY` and save the [product photograph](https://developers.openai.com/images/platform/guides/image-prompting/shampoo.webp) as `input_images/shampoo.webp`. Live requests incur API usage charges.

2850 2949 

2851 2950 

2852 2951 


2855 2954 

2856 Generate and edit transparent assets2955 Generate and edit transparent assets

2857 2956 

2957```typescript

2958import { createReadStream } from "node:fs";

2959import { writeFile } from "node:fs/promises";

2960import OpenAI, { toFile } from "openai";

2961 

2962const model = "gpt-image-2.5-sunburst";

2963const suffix = `-${model}.png`;

2964const client = new OpenAI();

2965const logos = await client.images.generate({

2966 model,

2967 prompt:

2968 "Create an original logo for Field & Flour, a local bakery. Use warm, simple shapes on a fully transparent background, with clean alpha edges and no shadow or checkerboard.",

2969 size: "1024x1536",

2970 quality: "medium",

2971 background: "transparent",

2972 output_format: "png",

2973 n: 4,

2974});

2975if (logos.data?.length !== 4) throw new Error("Expected four logo candidates");

2976for (const [index, image] of logos.data.entries()) {

2977 await saveImage(`logo-generation-${index + 1}${suffix}`, image.b64_json);

2978}

2979 

2980const cutout = await client.images.edit({

2981 model,

2982 image: await toFile(

2983 createReadStream("input_images/shampoo.webp"),

2984 "shampoo.webp",

2985 {

2986 type: "image/webp",

2987 }

2988 ),

2989 prompt:

2990 "Extract the product onto a fully transparent background. Preserve its geometry and label, with clean edges and no shadow or restyling.",

2991 size: "1024x1536",

2992 quality: "medium",

2993 background: "transparent",

2994 output_format: "png",

2995});

2996if (cutout.data?.length !== 1) throw new Error("Expected one product cutout");

2997await saveImage(`extract-product${suffix}`, cutout.data[0].b64_json);

2998 

2999async function saveImage(

3000 filename: string,

3001 encoded: string | undefined

3002): Promise<void> {

3003 if (!encoded) throw new Error("No PNG returned");

3004 await writeFile(filename, Buffer.from(encoded, "base64"));

3005}

3006```

3007 

2858```python3008```python

2859import base643009import base64

2860from pathlib import Path3010from pathlib import Path

Details

64 64 

65 Chat Completions API65 Chat Completions API

66 66 

67```typescript

68import OpenAI from "openai";

69 

70const client = new OpenAI();

71const completion = await client.chat.completions.create({

72 model: "gpt-6.2-astra",

73 messages: [

74 {

75 role: "user",

76 content: "Write a one-sentence bedtime story about a unicorn.",

77 },

78 ],

79});

80console.log(completion.choices[0].message.content);

81```

82 

67```python83```python

68from openai import OpenAI84from openai import OpenAI

69 85 


125 141 

126 Responses API142 Responses API

127 143 

144```typescript

145import OpenAI from "openai";

146 

147const client = new OpenAI();

148const response = await client.responses.create({

149 model: "gpt-6.2-astra",

150 input: "Write a one-sentence bedtime story about a unicorn.",

151});

152console.log(response.output_text);

153```

154 

128```python155```python

129from openai import OpenAI156from openai import OpenAI

130 157 

Details

210 210 

211 211 

212 212 

213Connect your own AWS S3 bucket, Azure Blob container, Google Cloud Storage bucket, or Oracle Cloud Infrastructure (OCI) Object Storage bucket to an OpenAI project. For a direct connection, follow the setup steps for your cloud, then register and validate the connection. You can also register a custom HTTPS endpoint to route records to customer storage. This option takes more work than a direct cloud connection because you must build and operate a service that verifies signed requests, stores records, and returns them for review.213Connect your own AWS S3 bucket, Azure Blob container, Google Cloud Storage bucket, or Oracle Cloud Infrastructure (OCI) Object Storage bucket to an OpenAI project. Follow the setup steps for your cloud, then register and validate the connection.

214 214 

215ZDR with PSP is enabled per project. Once enabled, the PSP policy applies to all API traffic in that project, including requests to models that do not otherwise require PSP. To use ZDR without PSP for eligible models, send those requests through a separate project configured for ZDR without PSP.215ZDR with PSP is enabled per project. Once enabled, the PSP policy applies to all API traffic in that project, including requests to models that do not otherwise require PSP. To use ZDR without PSP for eligible models, send those requests through a separate project configured for ZDR without PSP.

216 216 


219- Organizations already approved for Zero Data Retention can set up ZDR with PSP directly in the API console. If your organization isn't approved for ZDR, see the [eligibility and approval requirements](https://developers.openai.com/api/docs/guides/your-data#data-retention-controls-for-abuse-monitoring).219- Organizations already approved for Zero Data Retention can set up ZDR with PSP directly in the API console. If your organization isn't approved for ZDR, see the [eligibility and approval requirements](https://developers.openai.com/api/docs/guides/your-data#data-retention-controls-for-abuse-monitoring).

220- You can choose any supported storage region that meets your project's data residency requirements. You need permission to create storage and delegate access in your cloud account.220- You can choose any supported storage region that meets your project's data residency requirements. You need permission to create storage and delegate access in your cloud account.

221- Have an organization administrator register and validate storage in the API console. For the Management API, use an OpenAI organization Admin API key. Project administrators can view guidance and status; a project inference key won't work for the Management API calls.221- Have an organization administrator register and validate storage in the API console. For the Management API, use an OpenAI organization Admin API key. Project administrators can view guidance and status; a project inference key won't work for the Management API calls.

222- If you need to route encrypted safety records by customer or geography, skip to [Option 3: Set up a custom endpoint](#option-3-set-up-a-custom-endpoint). You’ll need an HTTPS endpoint that you operate. This setup can support zero data retention (ZDR) or data isolation commitments you’ve made to your customers.

223 222 

224### Open storage setup in the API console223### Open storage setup in the API console

225 224 


610 609 

611### Register your storage610### Register your storage

612 611 

613Select an eligible base data retention policy for the project. Private Safety Processing can be used with Zero Data Retention or Modified Abuse Monitoring, and the selected policy remains active while Private Safety Processing uses your connected storage. If you completed the cloud setup above, register and validate your storage using the API console (option 1) or the Management API (option 2). If OpenAI will send records to an HTTPS endpoint you operate, follow option 3.612Select an eligible base data retention policy for the project. Private Safety Processing can be used with Zero Data Retention or Modified Abuse Monitoring, and the selected policy remains active while Private Safety Processing uses your connected storage. After completing the cloud setup above, register and validate your storage using the API console (option 1) or the Management API (option 2).

614 613 

615 614 

616 615 


824 823 

825 824 

826 825 

827 

828 

829<a id="option-3-set-up-a-custom-endpoint"></a>

830 

831 

832 

833#### Option 3: Set up a custom endpoint

834 

835 

836 

837If you serve customers with zero data retention requirements or have customer data isolation commitments, you will need to set up a custom endpoint to isolate the encrypted safety record by customer-specific, geography specific buckets. Your application will call the Responses API as usual with a storage key attached. When OpenAI needs to retain a record, it sends the encrypted bytes to an HTTPS endpoint you run.

838 

839 

840 

841 

842![The PSP writer sends an encrypted record and routing key to the custom endpoint, which stores the record in an end-customer-owned bucket and retrieves it by ID for review.](https://developers.openai.com/images/platform/guides/private-safety-processing/custom-endpoint.webp)

843 

844 

845 

846 

847 

848 

849 

850![The PSP writer sends an encrypted record and routing key to the custom endpoint, which stores the record in an end-customer-owned bucket and retrieves it by ID for review.](https://developers.openai.com/images/platform/guides/private-safety-processing/custom-endpoint-dark.webp)

851 

852 

853 

854 

855##### 1. Set the project's base retention policy

856 

857Use an organization Admin API key to set an explicit policy on the project that will send Responses requests. In the path, replace `proj_123` with your project ID. In the JSON body, set `retention_type` to `zero_data_retention` or `modified_abuse_monitoring`. An inherited organization default doesn't satisfy the validation requirement.

858 

859**Your request**

860 

861```http snippet=reference reason="HTTP message format"

862POST /v1/organization/projects/proj_123/data_retention HTTP/1.1

863Host: api.openai.com

864Authorization: Bearer <OPENAI_ADMIN_KEY>

865Content-Type: application/json

866 

867{"retention_type":"zero_data_retention"}

868```

869 

870**OpenAI responds** with `200 OK` and your selected policy. For this example, the response includes:

871 

872```json snippet=reference reason="Example JSON payload"

873{

874 "object": "project.data_retention",

875 "type": "zero_data_retention"

876}

877```

878 

879This sets the base policy. Private Safety Processing becomes active for the project when storage validation succeeds in step 3.

880 

881##### 2. Register your endpoint

882 

883```http snippet=reference reason="HTTP message format"

884POST https://api.openai.com/v1/organization/external_storage

885```

886 

887Use an organization admin API key with `api.external_storage.write`. For a Global project, include the destination geography. For a fixed-region project, you can omit it.

888 

889```json snippet=reference reason="Example JSON payload"

890{

891 "project_id": "proj_123",

892 "provider": {

893 "type": "custom_endpoint",

894 "endpoint_url": "https://storage.example.com/custom-endpoint",

895 "geography": "EU"

896 }

897}

898```

899 

900Response: `200 OK`

901 

902```json snippet=reference reason="Example JSON payload"

903{

904 "object": "organization.external_storage",

905 "id": "extstorage_abc123",

906 "project_id": "proj_123",

907 "provider": {

908 "type": "custom_endpoint",

909 "endpoint_url": "https://storage.example.com/custom-endpoint",

910 "signing_secret": "whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",

911 "signing_secret_hint": "whsec_...AAA="

912 },

913 "geography": "EU",

914 "status": "pending",

915 "created_at": 1793880000

916}

917```

918 

919**Save your signing secret.** Store `provider.signing_secret` in your secret manager. You'll use it to [verify requests from OpenAI](#verify-requests-from-openai). The API returns the full secret only at registration.

920 

921##### 3. Validate your endpoint

922 

923Implement `POST {endpoint_url}/v1/validate` on your server.

924 

925**You request validation.** Send the registration ID from step 2 in the URL. Authenticate with your organization Admin API key and leave the body empty.

926 

927```http snippet=reference reason="HTTP message format"

928POST /v1/organization/external_storage/extstorage_abc123/validate HTTP/1.1

929Host: api.openai.com

930Authorization: Bearer <OPENAI_ADMIN_KEY>

931Content-Length: 0

932```

933 

934**OpenAI sends a signed challenge**

935 

936```http snippet=reference reason="HTTP message format"

937POST /custom-endpoint/v1/validate HTTP/1.1

938Host: storage.example.com

939Content-Type: application/json

940webhook-id: probe_a81f907c2b6d4e13a5709f28c6103eb4

941webhook-timestamp: 1793880000

942webhook-signature: v1,R2MM/gN/BbBWiq51ShHlMTY/D8Qlsd2nuzWyZUNirm4=

943 

944{"challenge": "a81f907c2b6d4e13a5709f28c6103eb4"}

945```

946 

947**You verify the signature and return the challenge.** [Verify the raw request body](#verify-requests-from-openai) with the signing secret from step 2. If verification succeeds, parse the JSON and return the received `challenge` value.

948 

949```http snippet=reference reason="HTTP message format"

950HTTP/1.1 200 OK

951Content-Type: application/json

952 

953{"challenge":"a81f907c2b6d4e13a5709f28c6103eb4"}

954```

955 

956**Check the registration status.** OpenAI responds to your original request with `200 OK` and the updated registration. Look for `"status": "validated"` before sending a Responses request.

957 

958```http snippet=reference reason="HTTP message format"

959HTTP/1.1 200 OK

960Content-Type: application/json

961 

962{

963 "object": "organization.external_storage",

964 "id": "extstorage_abc123",

965 "project_id": "proj_123",

966 "status": "validated",

967 "provider": {

968 "type": "custom_endpoint",

969 "endpoint_url": "https://storage.example.com/custom-endpoint",

970 "signing_secret_hint": "whsec_...AAA="

971 },

972 "geography": "EU",

973 "created_at": 1793880000

974}

975```

976 

977##### 4. Send a request

978 

979```http snippet=reference reason="HTTP message format"

980POST https://api.openai.com/v1/responses

981```

982 

983Use a PSP-enabled project API key with `api.responses.write`. Pick an opaque routing key that your server recognizes, e.g. a customer identifier and geography combination. Your custom endpoint will use this later to route OpenAI’s retention requests.

984 

985```json snippet=reference reason="Example JSON payload"

986{

987 "model": "<model-id>",

988 "input": "Summarize this account update.",

989 "storage_routing": {

990 "routing_key": "customer_1-us"

991 }

992}

993```

994 

995##### 5. Accept the encrypted record

996 

997You implement `POST {endpoint_url}/v1/records` on your server.

998 

999**OpenAI sends the encrypted record.** The signed multipart request includes the encrypted bytes in the `ciphertext` part and a routing key that identifies your end-customer’s storage.

1000 

1001```http snippet=reference reason="HTTP message format"

1002POST /custom-endpoint/v1/records HTTP/1.1

1003Host: storage.example.com

1004Content-Type: multipart/form-data; boundary=custom-endpoint-example

1005webhook-id: cobj_456

1006webhook-timestamp: 1793880060

1007webhook-signature: v1,MLAK7AYd/cYh1U8Yqo28Lx2SEds5nLb/IYulCiTFXJA=

1008 

1009Content-Disposition: form-data; name="type"

1010 

1011record.write

1012Content-Disposition: form-data; name="id"

1013 

1014cobj_456

1015Content-Disposition: form-data; name="storage_routing[routing_key]"

1016 

1017customer_1-us

1018Content-Disposition: form-data; name="expires_at"

1019 

10201796472000

1021Content-Disposition: form-data; name="ciphertext"; filename="record.bin"

1022Content-Type: application/octet-stream

1023 

1024<raw encrypted bytes>

1025```

1026 

1027**You return `202 Accepted` with the record ID.** [Verify the request signature](#verify-requests-from-openai) before parsing the multipart body. Once your server accepts the write, return the `id` from that request.

1028 

1029```http snippet=reference reason="HTTP message format"

1030HTTP/1.1 202 Accepted

1031Content-Type: application/json

1032 

1033{ "id": "cobj_456" }

1034```

1035 

1036You can finish storing the bytes asynchronously. OpenAI retries unacknowledged writes with backoff, so use the ID to recognize duplicates. Keep the ID with the storage location and delete the record at `expires_at` (Unix seconds).

1037 

1038##### 6. Return the record for review

1039 

1040You implement `GET {endpoint_url}/v1/records/{id}/content` on your server. During a safety review, OpenAI calls this endpoint to retrieve an unexpired record.

1041 

1042**OpenAI sends a signed GET request**

1043 

1044```http snippet=reference reason="HTTP message format"

1045GET /custom-endpoint/v1/records/cobj_456/content HTTP/1.1

1046Host: storage.example.com

1047webhook-id: cobj_456

1048webhook-timestamp: 1793883600

1049webhook-signature: v1,PYSp9wJfLMP9tl+6O476HMV+8wuFZ/q6X/gPirSbdBQ=

1050```

1051 

1052**You return the encrypted record.** [Verify the request signature](#verify-requests-from-openai) and apply your access policy. If the request is authorized, look up the record by ID and return the original encrypted bytes. Send those bytes directly in the response body, without gzip compression, additional encryption, or any other encoding.

1053 

1054```http snippet=reference reason="HTTP message format"

1055HTTP/1.1 200 OK

1056Content-Type: application/octet-stream

1057 

1058<the same encrypted bytes accepted for cobj_456>

1059```

1060 

1061OpenAI decrypts the record for review.

1062 

1063##### Verify requests from OpenAI

1064 

1065Verify each callback with the signing secret for its registration. If verification fails, return `401` before echoing a challenge, accepting a write, or returning a record.

1066 

1067The verifier reads the signed bytes from the incoming request. The examples use a Fetch API `Request` in Node.js and a FastAPI `Request` in Python.

1068 

1069- **POST:** Use the exact request body. Read it before parsing JSON or multipart data so that whitespace, multipart boundaries, and binary data are preserved.

1070- **GET:** Use the bytes of `GET`, one space, and the original public request path, including the registered path prefix. For the example above, the signed content is `GET /custom-endpoint/v1/records/cobj_456/content`.

1071 

1072Verify a callback signature

1073 

1074```typescript

1075import { createHmac, timingSafeEqual } from "node:crypto";

1076 

1077async function verifyCallback(request: Request, secret: string) {

1078 const headers = request.headers;

1079 const id = headers.get("webhook-id");

1080 const timestamp = headers.get("webhook-timestamp");

1081 const signatures = headers.get("webhook-signature");

1082 if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp))

1083 return false;

1084 

1085 // A short time window limits how long someone can replay a signed request.

1086 if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;

1087 

1088 // The whsec_ prefix identifies the secret. The rest encodes the HMAC key.

1089 if (!secret.startsWith("whsec_")) throw new Error("Invalid signing secret");

1090 const key = Buffer.from(secret.slice("whsec_".length), "base64");

1091 if (key.length !== 32) throw new Error("Invalid signing secret");

1092 // GET signs the public path. POST signs the body before any parsing.

1093 let signedContent: string | Uint8Array;

1094 if (request.method === "GET") {

1095 signedContent = "GET " + new URL(request.url).pathname;

1096 } else if (request.method === "POST") {

1097 signedContent = new Uint8Array(await request.clone().arrayBuffer());

1098 } else {

1099 return false;

1100 }

1101 const digest = createHmac("sha256", key)

1102 .update(`${id}.${timestamp}.`)

1103 .update(signedContent)

1104 .digest("base64");

1105 

1106 // Accept any matching v1 signature using a constant-time comparison.

1107 const expected = Buffer.from(`v1,${digest}`);

1108 return signatures.split(/\s+/).some((value) => {

1109 const candidate = Buffer.from(value);

1110 return (

1111 candidate.length === expected.length &&

1112 timingSafeEqual(candidate, expected)

1113 );

1114 });

1115}

1116```

1117 

1118```python

1119import base64

1120import hashlib

1121import hmac

1122import time

1123 

1124from fastapi import Request

1125 

1126 

1127async def verify_callback(request: Request, secret: str) -> bool:

1128 headers = request.headers

1129 delivery_id = headers.get("webhook-id")

1130 timestamp = headers.get("webhook-timestamp", "")

1131 signatures = headers.get("webhook-signature")

1132 if (

1133 not delivery_id

1134 or not signatures

1135 or not (timestamp.isascii() and timestamp.isdecimal())

1136 ):

1137 return False

1138 

1139 # A short time window limits how long someone can replay a signed request.

1140 if abs(time.time() - float(timestamp)) > 300:

1141 return False

1142 

1143 # The whsec_ prefix identifies the secret. The rest encodes the HMAC key.

1144 if not secret.startswith("whsec_"):

1145 raise ValueError("Invalid signing secret")

1146 key = base64.b64decode(secret.removeprefix("whsec_"), validate=True)

1147 if len(key) != 32:

1148 raise ValueError("Invalid signing secret")

1149 mac = hmac.new(key, f"{delivery_id}.{timestamp}.".encode(), hashlib.sha256)

1150 # GET signs the encoded public path. POST signs the body before any parsing.

1151 if request.method == "GET":

1152 mac.update(b"GET " + request.scope["raw_path"])

1153 elif request.method == "POST":

1154 mac.update(await request.body())

1155 else:

1156 return False

1157 

1158 # Accept any matching v1 signature using a constant-time comparison.

1159 expected = b"v1," + base64.b64encode(mac.digest())

1160 return any(

1161 hmac.compare_digest(value.encode(), expected) for value in signatures.split()

1162 )

1163```

1164 

1165 

1166 

1167 

1168 

1169 

1170After validating your storage configuration, open **Project Settings > Data retention** and select **Refresh**. Confirm the destination, provider, geography, and **Validated** status, then check that the selected base policy shows Private Safety Processing. The organization Data retention table also shows storage and status for each project.826After validating your storage configuration, open **Project Settings > Data retention** and select **Refresh**. Confirm the destination, provider, geography, and **Validated** status, then check that the selected base policy shows Private Safety Processing. The organization Data retention table also shows storage and status for each project.

1171 827 

1172![OpenAI Project Settings Data retention page showing an AWS S3 external-storage connection with Validated status and the Zero Data Retention with PSP retention policy.](https://developers.openai.com/images/platform/guides/private-safety-processing/setup-05-verify-project-retention.webp)828![OpenAI Project Settings Data retention page showing an AWS S3 external-storage connection with Validated status and the Zero Data Retention with PSP retention policy.](https://developers.openai.com/images/platform/guides/private-safety-processing/setup-05-verify-project-retention.webp)

Details

26 26 

27Compare prompt cache reuse between responses27Compare prompt cache reuse between responses

28 28 

29```typescript

30import { readFile } from "node:fs/promises";

31import OpenAI from "openai";

32 

33const client = new OpenAI();

34const policy = await readFile("support-policy.txt", "utf8"); // At least 1,024 tokens.

35const input = [

36 { role: "developer" as const, content: policy },

37 { role: "user" as const, content: "Reply with exactly OK." },

38];

39const first = await client.responses.create({

40 model: "gpt-6-astra",

41 input,

42 tools: [

43 { type: "function", name: "get_time", parameters: null, strict: null },

44 ],

45});

46const second = await client.responses.create({

47 model: "gpt-6-astra",

48 input,

49 tools: [

50 { type: "function", name: "get_date", parameters: null, strict: null },

51 ],

52 prompt_cache_options: { comparison_response_id: first.id },

53});

54 

55const diagnostics = second.prompt_cache_diagnostics;

56if (diagnostics?.type === "cache_miss") {

57 console.log(diagnostics.reason);

58 console.log(diagnostics.comparison_reusable_tokens ?? "None");

59 console.log(diagnostics.cache_missed_tokens);

60}

61```

62 

29```python63```python

30from pathlib import Path64from pathlib import Path

31 65 

Details

146 146 

147 147 

148 148 

149 

150 

151 

152Download and extract the [TypeScript samples and locked dependencies](https://developers.openai.com/api/docs/samples/typescript.tar.gz). From the extracted `typescript-examples` directory, run `pnpm install --ignore-workspace --frozen-lockfile` to install `canonicalize` and the other dependencies. The [complete recovery source](https://developers.openai.com/api/docs/samples/typescript/psp/recover-record.ts) includes the validation and key-derivation helpers used below. Pass the bundle JSON and public-key PEM as strings, the decrypted capsule as a `Buffer`, and the original key ID as a string. The private RSA key remains in your cloud key-management service. To run the complete file, use `node --experimental-strip-types psp/recover-record.ts bundle.json capsule.bin original-key-id public.pem`. Supply the decrypted capsule as a binary file. The command writes only the recovered text to standard output. It exits with code 1 for validation errors and code 2 for payload authentication errors.

153 

154 

155 

156 

149Pass these inputs to the recovery function:157Pass these inputs to the recovery function:

150 158 

151- `bundle_json`: The inner record bundle as UTF-8 JSON bytes.159- `bundle_json`: The inner record bundle as UTF-8 JSON bytes.


157 165 

158Decrypt a PSP record166Decrypt a PSP record

159 167 

168```typescript

169// Supply the decrypted capsule and trusted original registration. Keep the RSA

170// private key in the cloud. This function returns the exact recovered UTF-8 text.

171function recoverRecord(

172 bundleJSON: string,

173 capsule: Buffer,

174 originalKeyID: string,

175 publicPEM: string

176): string {

177 const bundle = parseBundle(bundleJSON);

178 const record = object(bundle.protected_record);

179 const access = object(bundle.customer_access);

180 if (

181 bundle.bundle_version !== 1 ||

182 record.version !== "v4" ||

183 record.algorithm !==

184 "HPKE-v1-DHKEM_P256_HKDF_SHA256-EXPORT_ONLY-AES256_GCM" ||

185 access.version !== 1 ||

186 access.algorithm !== "RSA-OAEP-256" ||

187 access.customer_key_id !== originalKeyID

188 )

189 throw new Error("Wrong schema or original key");

190 if (

191 !/^\s*-----BEGIN (PUBLIC KEY|RSA PUBLIC KEY)-----[A-Za-z0-9+/=\r\n]+-----END \1-----\s*$/.test(

192 publicPEM

193 )

194 )

195 throw new Error("Expected one RSA public key");

196 const publicKey = createPublicKey(publicPEM);

197 if (

198 publicKey.asymmetricKeyType !== "rsa" ||

199 publicKey.asymmetricKeyDetails?.modulusLength !== 3072

200 )

201 throw new Error("Expected RSA-3072");

202 if (decode64(access.recovery_secret).length !== 384)

203 throw new Error("Wrong RSA ciphertext length");

204 const der = publicKey.export({ type: "spki", format: "der" });

205 if (!equal(decode64(access.customer_public_key_fingerprint), sha256(der)))

206 throw new Error("Wrong key fingerprint");

207 const runtime = decode64(record.safety_review_runtime_public_key);

208 if (runtime.length !== 65 || runtime[0] !== 4)

209 throw new Error("Invalid P-256 encoding");

210 const thumbprint = sha256(

211 canonical({

212 crv: "P-256",

213 kty: "EC",

214 x: runtime.subarray(1, 33).toString("base64url"),

215 y: runtime.subarray(33).toString("base64url"),

216 })

217 ).toString("base64url");

218 if (record.key_thumbprint !== thumbprint)

219 throw new Error("Wrong runtime key");

220 const nonce = decode64(record.nonce);

221 const ciphertext = decode64(record.ciphertext);

222 if (nonce.length !== 12 || ciphertext.length < 16)

223 throw new Error("Invalid AES-GCM parameters");

224 const binding = sha256(

225 canonical({

226 purpose: "OpenAI-PSP-v4/customer-recovery-binding",

227 bundle_version: 1,

228 record,

229 recovery_header: without(access, "recovery_secret"),

230 })

231 );

232 if (

233 capsule.length !== 72 ||

234 !equal(

235 capsule.subarray(0, 8),

236 Buffer.from([0x50, 0x53, 0x50, 0x76, 0x34, 0, 0, 1])

237 ) ||

238 !equal(capsule.subarray(40), binding)

239 )

240 throw new Error("Invalid recovery capsule binding");

241 const ephemeral = createECDH("prime256v1");

242 ephemeral.setPrivateKey(capsule.subarray(8, 40));

243 if (!equal(decode64(record.encrypted_dek), ephemeral.getPublicKey()))

244 throw new Error("Wrong recovered scalar");

245 const aad = canonical(without(record, "ciphertext"));

246 const key = payloadKey(ephemeral, runtime, aad);

247 const decipher = createDecipheriv("aes-256-gcm", key, nonce);

248 decipher.setAAD(aad);

249 decipher.setAuthTag(ciphertext.subarray(-16));

250 let plaintext: Buffer;

251 try {

252 plaintext = Buffer.concat([

253 decipher.update(ciphertext.subarray(0, -16)),

254 decipher.final(),

255 ]);

256 } catch {

257 throw new AuthenticationError("Payload authentication failed");

258 }

259 return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(

260 plaintext

261 );

262}

263```

264 

160```python265```python

161import base64266import base64

162import hashlib267import hashlib

Details

166 166 

167As a rule of thumb, once your traffic reaches 1 million input tokens per minute (TPM), increase it by no more than 50% every 15 minutes. The exact point at which the ramp-rate limit applies can vary by model and traffic conditions.167As a rule of thumb, once your traffic reaches 1 million input tokens per minute (TPM), increase it by no more than 50% every 15 minutes. The exact point at which the ramp-rate limit applies can vary by model and traffic conditions.

168 168 

169Enterprise customers whose pay-as-you-go traffic routinely hits ramp-rate limits can consider [Scale Tier](https://openai.com/api-scale-tier/) for more predictable capacity on eligible models. For GPT-5.6 and later models, see [Reserved Tier](https://openai.com/api-reserved-tier/). Capacity tiers don't change how you should handle a `slow_down` response: follow `Retry-After` when it's present, reduce traffic, and ramp gradually.169Enterprise customers whose pay-as-you-go traffic routinely hits ramp-rate limits can consider [Scale Tier](https://openai.com/api-scale-tier/) for more predictable capacity on eligible models. For GPT-5.6 and later models, see [Reserved Tier](https://developers.openai.com/api/docs/guides/reserved-tier). Capacity tiers don't change how you should handle a `slow_down` response: follow `Retry-After` when it's present, reduce traffic, and ramp gradually.

170 170 

171#### Update existing error handlers171#### Update existing error handlers

172 172 


228 228 

229 229 

230 230 

231The Go example uses [`github.com/avast/retry-go/v4`](https://github.com/avast/retry-go) at version `v4.7.0`. It limits the request to six attempts and honors `Retry-After` within a one-minute delay budget. If a server delay exceeds the one-minute budget or a quota error occurs, the function returns to the caller.231The Go example uses [`github.com/avast/retry-go/v4`](https://github.com/avast/retry-go). It limits the request to six attempts and honors `Retry-After` within a one-minute delay budget. If a server delay exceeds the one-minute budget or a quota error occurs, the function returns to the caller.

232 

233 

234 

235 

236 

237 

238 

239Install `openai` and `p-retry` in your project, save the complete TypeScript program as `retry.ts`, and set `OPENAI_API_KEY`. Run `node --experimental-strip-types retry.ts`. The wrapper disables SDK retries, retries requests that hit transient rate limits, and honors `Retry-After` within its delay budget.

232 240 

233 241 

234 242 

235 243 

236Retry with exponential backoff244Retry with exponential backoff

237 245 

246```typescript

247import OpenAI from "openai";

248import { setTimeout as sleep } from "node:timers/promises";

249 

250// Stop on permanent errors or server delays beyond this example's budget.

251function retryDelay(error: unknown): number | undefined {

252 if (

253 !(error instanceof OpenAI.RateLimitError) ||

254 error.code === "insufficient_quota" ||

255 error.code === "billing_hard_limit_reached"

256 )

257 return undefined;

258 const hint = error.headers?.get("retry-after")?.trim();

259 if (!hint) return 0;

260 let delay = Number(hint) * 1000;

261 if (Number.isNaN(delay)) delay = Date.parse(hint) - Date.now();

262 if (Number.isNaN(delay) || delay < 0) return 0;

263 return delay <= 60000 ? delay : undefined;

264}

265const client = new OpenAI({ maxRetries: 0 });

266const operation = () =>

267 client.responses.create({

268 model: "gpt-6-luna",

269 input: "Say hello in one sentence.",

270 reasoning: { effort: "low" },

271 max_output_tokens: 1024,

272 });

273 

274import pRetry from "p-retry";

275const response = await pRetry(operation, {

276 retries: 5,

277 minTimeout: 1000,

278 maxTimeout: 60000,

279 randomize: true,

280 onFailedAttempt: async ({ error, retriesLeft }) => {

281 const delay = retryDelay(error);

282 if (delay === undefined) throw error;

283 if (retriesLeft && delay) await sleep(delay);

284 },

285});

286if (response.status !== "completed")

287 throw new Error("Response did not complete");

288console.log(response.output_text);

289```

290 

238```python291```python

239from openai import OpenAI, RateLimitError292from openai import OpenAI, RateLimitError

240from tenacity import (293from tenacity import (


375 428 

376 429 

377 430 

378The Go example uses [`github.com/cenkalti/backoff/v5`](https://github.com/cenkalti/backoff/tree/v5.0.3) at version `v5.0.3`. It limits the request to six attempts, honors `Retry-After` within a one-minute delay budget, and returns permanent errors without retrying.431The Go example uses [`github.com/cenkalti/backoff/v5`](https://github.com/cenkalti/backoff). It limits the request to six attempts, honors `Retry-After` within a one-minute delay budget, and returns permanent errors without retrying.

432 

433 

434 

435 

436 

437 

438 

439Install `openai` and `exponential-backoff` in your project, save the complete TypeScript program as `retry.ts`, and set `OPENAI_API_KEY`. Run `node --experimental-strip-types retry.ts`. The wrapper disables SDK retries, retries requests that hit transient rate limits, and honors `Retry-After` within its delay budget.

379 440 

380 441 

381 442 

382 443 

383Retry with a backoff schedule444Retry with a backoff schedule

384 445 

446```typescript

447import OpenAI from "openai";

448import { setTimeout as sleep } from "node:timers/promises";

449 

450// Stop on permanent errors or server delays beyond this example's budget.

451function retryDelay(error: unknown): number | undefined {

452 if (

453 !(error instanceof OpenAI.RateLimitError) ||

454 error.code === "insufficient_quota" ||

455 error.code === "billing_hard_limit_reached"

456 )

457 return undefined;

458 const hint = error.headers?.get("retry-after")?.trim();

459 if (!hint) return 0;

460 let delay = Number(hint) * 1000;

461 if (Number.isNaN(delay)) delay = Date.parse(hint) - Date.now();

462 if (Number.isNaN(delay) || delay < 0) return 0;

463 return delay <= 60000 ? delay : undefined;

464}

465const client = new OpenAI({ maxRetries: 0 });

466const operation = () =>

467 client.responses.create({

468 model: "gpt-6-luna",

469 input: "Say hello in one sentence.",

470 reasoning: { effort: "low" },

471 max_output_tokens: 1024,

472 });

473 

474import { backOff } from "exponential-backoff";

475const response = await backOff(operation, {

476 numOfAttempts: 6,

477 startingDelay: 1000,

478 maxDelay: 60000,

479 jitter: "full",

480 retry: async (error: unknown, attempt: number) => {

481 const delay = retryDelay(error);

482 if (delay === undefined || attempt >= 6) return false;

483 if (delay) await sleep(delay);

484 return true;

485 },

486});

487if (response.status !== "completed")

488 throw new Error("Response did not complete");

489console.log(response.output_text);

490```

491 

385```python492```python

386import backoff493import backoff

387import openai494import openai


513If you don't want to use third-party libraries, you can implement your own backoff logic following this example:620If you don't want to use third-party libraries, you can implement your own backoff logic following this example:

514Using manual backoff implementation621Using manual backoff implementation

515 622 

623```typescript

624import OpenAI from "openai";

625import { setTimeout as sleep } from "node:timers/promises";

626 

627// Stop on permanent errors or server delays beyond this example's budget.

628function retryDelay(error: unknown): number | undefined {

629 if (

630 !(error instanceof OpenAI.RateLimitError) ||

631 error.code === "insufficient_quota" ||

632 error.code === "billing_hard_limit_reached"

633 )

634 return undefined;

635 const hint = error.headers?.get("retry-after")?.trim();

636 if (!hint) return 0;

637 let delay = Number(hint) * 1000;

638 if (Number.isNaN(delay)) delay = Date.parse(hint) - Date.now();

639 if (Number.isNaN(delay) || delay < 0) return 0;

640 return delay <= 60000 ? delay : undefined;

641}

642const client = new OpenAI({ maxRetries: 0 });

643const operation = () =>

644 client.responses.create({

645 model: "gpt-6-luna",

646 input: "Say hello in one sentence.",

647 reasoning: { effort: "low" },

648 max_output_tokens: 1024,

649 });

650 

651async function withExponentialBackoff<T>(

652 request: () => Promise<T>

653): Promise<T> {

654 for (let attempt = 0; ; attempt++) {

655 try {

656 return await request();

657 } catch (error) {

658 const serverDelay = retryDelay(error);

659 if (serverDelay === undefined || attempt >= 10) throw error;

660 const jitteredDelay =

661 Math.random() * Math.min(60000, 1000 * 2 ** attempt);

662 await sleep(Math.max(serverDelay, jitteredDelay));

663 }

664 }

665}

666const response = await withExponentialBackoff(operation);

667if (response.status !== "completed")

668 throw new Error("Response did not complete");

669console.log(response.output_text);

670```

671 

516```python672```python

517# imports673# imports

518import random674import random

Details

108 108 

109Ordering between completion events from different speech turns isn't guaranteed. Use `item_id` to match transcription events to committed input items.109Ordering between completion events from different speech turns isn't guaranteed. Use `item_id` to match transcription events to committed input items.

110 110 

111After configuring a transcription session, use this Go function to send mono PCM16 audio at 24 kHz, commit the turn, and match the final transcript to the committed item:111After configuring a transcription session, use this function to send mono PCM16 audio at 24 kHz, commit the turn, and match the final transcript to the committed item:

112 

113```typescript

114// Use a transcription session configured for 24 kHz mono PCM16 and manual commits.

115function transcribeTurn(

116 connection: OpenAIRealtimeWS,

117 audio: Buffer

118): Promise<string> {

119 if (!audio.length || audio.length % 2)

120 throw new Error("Expected nonempty PCM16 audio");

121 return new Promise((resolve, reject) => {

122 let itemID: string | undefined;

123 const completed = new Map<string, string>();

124 const failed = new Set<string>();

125 const timer = setTimeout(

126 () => finish(new Error("Transcription timed out")),

127 120000

128 );

129 function finish(error?: Error, transcript?: string) {

130 clearTimeout(timer);

131 connection.off("event", onEvent);

132 connection.off("error", onError);

133 connection.socket.off("close", onClose);

134 if (error) reject(error);

135 else resolve(transcript!);

136 }

137 const onError = (error: Error) => finish(error);

138 const onClose = () =>

139 finish(new Error("Connection closed before transcription"));

140 const onEvent = (event: RealtimeServerEvent) => {

141 if (

142 event.type === "conversation.item.input_audio_transcription.delta" &&

143 event.item_id === itemID

144 )

145 console.error(`Partial transcript (${event.item_id}): ${event.delta}`);

146 if (event.type === "input_audio_buffer.committed") itemID = event.item_id;

147 if (

148 event.type === "conversation.item.input_audio_transcription.completed"

149 )

150 completed.set(event.item_id, event.transcript);

151 if (event.type === "conversation.item.input_audio_transcription.failed")

152 failed.add(event.item_id);

153 if (itemID && failed.has(itemID))

154 finish(new Error("Transcription failed"));

155 else if (itemID && completed.has(itemID))

156 finish(undefined, completed.get(itemID));

157 };

158 connection.on("event", onEvent);

159 connection.on("error", onError);

160 connection.socket.on("close", onClose);

161 for (let start = 0; start < audio.length; start += 9600) {

162 connection.send({

163 type: "input_audio_buffer.append",

164 audio: audio.subarray(start, start + 9600).toString("base64"),

165 });

166 }

167 connection.send({ type: "input_audio_buffer.commit" });

168 });

169}

170```

112 171 

113```go172```go

114func transcribeTurn(ctx context.Context, conn *realtime.RealtimeConnection, audio []byte) error {173func transcribeTurn(ctx context.Context, conn *realtime.RealtimeConnection, audio []byte) error {

guides/reserved-tier.md +9 −0 created

Details

1# Reserved Tier

2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 

5Reserved Tier gives Enterprise customers guaranteed API capacity for a specific model, up to the amount they reserve in dollars per minute. When demand for that model is high, OpenAI prioritizes requests within your reservation over pay-as-you-go traffic on the same shared infrastructure. Use Reserved Tier when you need predictable capacity for a production workload or expect a traffic spike during a product launch or special event, such as Black Friday or Cyber Monday.

6 

7Your reservation automatically covers eligible Standard and Fast mode requests for that model. You pay for the capacity you reserve, even when you use less. Usage above your reservation is billed at your usual pay-as-you-go rates and is subject to your usual rate limits.

8 

9Reserved Tier is available on select Astra, Sol, Terra, and Luna models. To get access, [contact sales](https://openai.com/contact-sales/). If your organization already has access, your authorized purchaser can see the models available to reserve by selecting **Add capacity** in [Capacity Management](https://platform.openai.com/settings/organization/capacity-management/overview).

Details

306}306}

307 307 

308while (true) {308while (true) {

309 const outputItems = [];309 let outputItems: OpenAI.Beta.Responses.BetaResponseOutputItem[] = [];

310 const pendingCalls = [];310 let completed = false;

311 const itemAgents = new Map();311 const itemAgents = new Map();

312 312 

313 const stream = await client.beta.responses.create({313 const stream = await client.beta.responses.create({

314 model: "gpt-6.2-sol",314 model: "gpt-6.2-sol",

315 // HTTP tool results arrive in the next request. Waiting for an agent that

316 // needs those results would prevent this response from ending.

317 instructions:

318 "Use separate subagents to look up each proposal. After spawning them, " +

319 "finish your own turn without calling wait_agent so the HTTP caller can " +

320 "supply their get_proposal results. When those results are present in " +

321 "the conversation, compare the subagents' findings and give the final answer.",

315 // Replay Beta output unchanged, including agent metadata. The SDK input322 // Replay Beta output unchanged, including agent metadata. The SDK input

316 // union is narrower than the agent_message content returned by the API.323 // union is narrower than the agent_message content returned by the API.

317 input: history as OpenAI.Beta.Responses.BetaResponseInput,324 input: history as OpenAI.Beta.Responses.BetaResponseInput,


334 destination.write(341 destination.write(

335 agent === ROOT ? event.delta : `[${agent}] ${event.delta}`342 agent === ROOT ? event.delta : `[${agent}] ${event.delta}`

336 );343 );

337 } else if (event.type === "response.output_item.done") {

338 outputItems.push(event.item);

339 if (event.item.type === "function_call") {

340 pendingCalls.push(event.item);

341 }

342 } else if (event.type === "response.completed") {344 } else if (event.type === "response.completed") {

345 // The completed response includes hosted-agent replay items that may not

346 // appear as individual output_item.done events.

347 outputItems = event.response.output;

348 completed = true;

343 console.error("\nUsage:", event.response.usage);349 console.error("\nUsage:", event.response.usage);

344 break;

345 } else if (350 } else if (

346 event.type === "error" ||351 event.type === "error" ||

347 event.type === "response.failed" ||352 event.type === "response.failed" ||


351 }356 }

352 }357 }

353 358 

359 if (!completed) throw new Error("Stream ended before the response completed");

360 const pendingCalls = outputItems.filter(

361 (item) => item.type === "function_call"

362 );

354 history.push(...outputItems);363 history.push(...outputItems);

355 for (const call of pendingCalls) {364 for (const call of pendingCalls) {

356 history.push({365 history.push({

Details

734 734 

735 735 

736 736 

737 

738 

739 

740Install `ffmpeg` and `ffprobe` and ensure both commands are on your `PATH`. Save the [complete TypeScript program](https://developers.openai.com/api/docs/samples/typescript/speech-to-text/longer-inputs.ts) beside `good_morning.wav`. Run `node --experimental-strip-types longer-inputs.ts` to write `good_morning_10.wav` and print both durations in milliseconds.

741 

742 

743 

744 

737Split a long audio file745Split a long audio file

738 746 

747```typescript

748import { execFileSync } from "node:child_process";

749 

750function durationMilliseconds(path: string): number {

751 const result = JSON.parse(

752 execFileSync(

753 "ffprobe",

754 ["-v", "error", "-show_entries", "format=duration", "-of", "json", path],

755 { encoding: "utf8" }

756 )

757 );

758 return Math.round(Number(result.format.duration) * 1000);

759}

760 

761const inputMilliseconds = durationMilliseconds("good_morning.wav");

762// Keep the first ten minutes, preserving the retained PCM samples.

763execFileSync("ffmpeg", [

764 "-v",

765 "error",

766 "-y",

767 "-i",

768 "good_morning.wav",

769 "-t",

770 "600",

771 "-c:a",

772 "pcm_s16le",

773 "-flags:a",

774 "+bitexact",

775 "-fflags",

776 "+bitexact",

777 "-map_metadata",

778 "-1",

779 "good_morning_10.wav",

780]);

781```

782 

739```python783```python

740from pydub import AudioSegment784from pydub import AudioSegment

741 785 

Details

1423 1423 

1424Add sample phrases to a tool description1424Add sample phrases to a tool description

1425 1425 

1426```typescript

1427const tools = [

1428 {

1429 type: "function",

1430 name: "lookup_account",

1431 description:

1432 "Retrieve a customer account using either an email or phone number to enable verification and account-specific actions.\n\nPreamble sample phrases:\n- For security, I’ll pull up your account using the email on file.\n- Let me look up your account by {email} now.\n- I’m fetching the account linked to {phone} to verify access.\n- One moment—I’m opening your account details.",

1433 parameters: {

1434 type: "object",

1435 properties: {

1436 email: {

1437 type: "string",

1438 },

1439 phone: {

1440 type: "string",

1441 },

1442 },

1443 additionalProperties: false,

1444 },

1445 },

1446 {

1447 type: "function",

1448 name: "check_outage",

1449 description:

1450 "Check for network outages affecting a given service address and return status and ETA if applicable.\n\nPreamble sample phrases:\n- I’ll check for any outages at {service_address} right now.\n- Let me look up network status for your area.\n- I’m checking whether there’s an active outage impacting your address.\n- One sec—verifying service status and any posted ETA.",

1451 parameters: {

1452 type: "object",

1453 properties: {

1454 service_address: {

1455 type: "string",

1456 },

1457 },

1458 required: ["service_address"],

1459 additionalProperties: false,

1460 },

1461 },

1462] satisfies Array<{

1463 type: "function";

1464 name: string;

1465 description: string;

1466 parameters: Record<string, unknown>;

1467}>;

1468```

1469 

1426```python1470```python

1427tools = [1471tools = [

1428 {1472 {


2005 2049 

2006Update the conversation state2050Update the conversation state

2007 2051 

2052```typescript

2053type State = "verify" | "resolve";

2054const transitions: Record<State, State[]> = {

2055 verify: ["resolve"],

2056 resolve: [],

2057};

2058const toolsByState = {

2059 verify: [

2060 {

2061 type: "function",

2062 name: "lookup_account",

2063 description: "Fetch account by email or phone.",

2064 parameters: {

2065 type: "object",

2066 properties: {

2067 email_or_phone: {

2068 type: "string",

2069 },

2070 },

2071 required: ["email_or_phone"],

2072 },

2073 },

2074 ],

2075 resolve: [

2076 {

2077 type: "function",

2078 name: "schedule_technician",

2079 description: "Book a technician visit.",

2080 parameters: {

2081 type: "object",

2082 properties: {

2083 account_id: {

2084 type: "string",

2085 },

2086 window: {

2087 type: "string",

2088 enum: ["10-12 ET", "14-16 ET"],

2089 },

2090 },

2091 required: ["account_id", "window"],

2092 },

2093 },

2094 ],

2095} as const;

2096const instructionsByState = {

2097 verify:

2098 "# Role & Objective\nVerify identity to access the account.\n\n# Conversation (Verify)\n- Ask for the email or phone on the account.\n- Read back digits one-by-one (e.g., '4-1-5… Is that correct?').\nExit when: Account ID is returned.\nWhen exit is satisfied: call set_conversation_state(next_state=\"resolve\").",

2099 resolve:

2100 "# Role & Objective\nApply a fix by booking a technician.\n\n# Conversation (Resolve)\n- Offer two windows: '10–12 ET' or '2–4 ET'.\n- Book the chosen window.\nExit when: Appointment is confirmed.\nWhen exit is satisfied: end the call politely.",

2101};

2102function buildSessionUpdate(state: State): RealtimeClientEvent {

2103 const allowed = transitions[state];

2104 if (!allowed) throw new Error("Unknown conversation state");

2105 const readable = allowed.length

2106 ? allowed.join(", ")

2107 : "no further states (terminal)";

2108 return {

2109 type: "session.update",

2110 session: {

2111 type: "realtime",

2112 instructions: instructionsByState[state],

2113 tools: [

2114 ...toolsByState[state],

2115 {

2116 type: "function",

2117 name: "set_conversation_state",

2118 description: `Switch the conversation phase. Current: '${state}'. You may switch only to: ${readable}. Call this AFTER exit criteria are satisfied.`,

2119 parameters: {

2120 type: "object",

2121 properties: { next_state: { type: "string", enum: allowed } },

2122 required: ["next_state"],

2123 },

2124 },

2125 ],

2126 },

2127 };

2128}

2129```

2130 

2008```python2131```python

2009from typing import Literal2132from typing import Literal

2010 2133 

Details

304```304```

305 305 

306 306 

307In Go, pass the call ID to your server-side session update function:307Pass the call ID to your server-side session update function:

308 

309 

310 

311 

312Install `openai` and the `ws` WebSocket package with `npm install openai ws`. Set `OPENAI_API_KEY` for the project that owns the active call. Save the [complete TypeScript program](https://developers.openai.com/api/docs/samples/typescript/realtime/connect-sideband-websocket.ts), then run `node --experimental-strip-types connect-sideband-websocket.ts <call-id>` to update that call's instructions.

313 

314 

315 

316 

317```typescript

318import OpenAI from "openai";

319import { OpenAIRealtimeWS } from "openai/realtime/ws";

320import type {

321 RealtimeServerEvent,

322 RealtimeClientEvent,

323} from "openai/resources/realtime/realtime";

324 

325function waitForEvent(

326 connection: OpenAIRealtimeWS,

327 type: string

328): Promise<RealtimeServerEvent> {

329 return new Promise((resolve, reject) => {

330 const timer = setTimeout(

331 () => finish(new Error(`Timed out waiting for ${type}`)),

332 120000

333 );

334 function finish(error?: Error, event?: RealtimeServerEvent) {

335 clearTimeout(timer);

336 connection.off("event", onEvent);

337 connection.off("error", onError);

338 connection.socket.off("close", onClose);

339 if (error) reject(error);

340 else resolve(event!);

341 }

342 const onEvent = (event: RealtimeServerEvent) => {

343 if (event.type === type) finish(undefined, event);

344 };

345 const onError = (error: Error) => finish(error);

346 const onClose = () => finish(new Error(`Connection closed before ${type}`));

347 connection.on("event", onEvent);

348 connection.on("error", onError);

349 connection.socket.on("close", onClose);

350 });

351}

352 

353// callID comes from the existing call's Location header or SIP webhook.

354async function updateSession(callID: string): Promise<void> {

355 const connection = new OpenAIRealtimeWS({ callID }, new OpenAI());

356 try {

357 await new Promise<void>((resolve, reject) => {

358 const timer = setTimeout(

359 () => finish(new Error("Sideband connection timed out")),

360 30000

361 );

362 const onOpen = () => finish();

363 const onError = (error: Error) => finish(error);

364 const onClose = () => finish(new Error("Sideband closed before opening"));

365 function finish(error?: Error) {

366 clearTimeout(timer);

367 connection.socket.off("open", onOpen);

368 connection.off("error", onError);

369 connection.socket.off("close", onClose);

370 if (error) reject(error);

371 else resolve();

372 }

373 connection.socket.once("open", onOpen);

374 connection.once("error", onError);

375 connection.socket.once("close", onClose);

376 });

377 const updated = waitForEvent(connection, "session.updated");

378 connection.send({

379 type: "session.update",

380 session: { type: "realtime", instructions: "Be extra nice today!" },

381 });

382 const event = await updated;

383 if (

384 event.type !== "session.updated" ||

385 event.session.type !== "realtime" ||

386 event.session.instructions !== "Be extra nice today!"

387 )

388 throw new Error("Session update was not applied");

389 console.log("session.updated");

390 } finally {

391 connection.close();

392 }

393}

394```

308 395 

309```go396```go

310func updateSession(ctx context.Context, client openai.Client, callID string) error {397func updateSession(ctx context.Context, client openai.Client, callID string) error {

Details

236## Overview236## Overview

237 237 

238If you want to connect a phone number to the Realtime API,238If you want to connect a phone number to the Realtime API,

239use a SIP trunking provider (e.g., Twilio). This is a service that converts your phone call239use a SIP trunking provider (for example, Twilio). This is a service that converts your phone call

240to IP traffic. After you purchase a phone number from your SIP trunking240to IP traffic. After you purchase a phone number from your SIP trunking

241provider, follow the instructions below.241provider, follow the instructions below.

242 242 


291approve the inbound call and configure the realtime session that will answer it.291approve the inbound call and configure the realtime session that will answer it.

292Send the same parameters you would send in a292Send the same parameters you would send in a

293[`create client secret`](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets/methods/create)293[`create client secret`](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets/methods/create)

294request, i.e., ensure the realtime model, voice, tools, or instructions are set before bridging the294request. Ensure the realtime model, voice, tools, or instructions are set before bridging the

295call to the model.295call to the model.

296 296 

297```bash297```bash


312endpoint returns `200 OK` once the SIP leg is ringing and the realtime session312endpoint returns `200 OK` once the SIP leg is ringing and the realtime session

313is being established.313is being established.

314 314 

315## Reject the call

316 315 

317Use the [Reject call endpoint](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/reject) to316 

318decline an invite when you do not want to handle the incoming call, (e.g., from317 

319an unsupported country code.) Supply the `call_id` path parameter318## Decline the call

320and an optional SIP `status_code` (e.g., `486` to indicate "busy") in the JSON319 

320Use the [`reject` endpoint](https://developers.openai.com/api/reference/resources/realtime/subresources/calls/methods/reject) to

321decline an invite when you do not want to handle the incoming call (for example, from

322an unsupported country code). Supply the `call_id` path parameter

323and an optional SIP `status_code` (for example, `486` to indicate "busy") in the JSON

321body to control the response sent back to the carrier.324body to control the response sent back to the carrier.

322 325 

323```bash326```bash


437 440 

438## Server examples441## Server examples

439 442 

440The following is an example of a `realtime.call.incoming` handler. It accepts the call and then logs all the events from443These `realtime.call.incoming` handlers accept an incoming call and greet the caller.

441the Realtime API.444 

445 

446 

442 447 

443For the Ruby example, set the `OPENAI_API_KEY` and `OPENAI_WEBHOOK_SECRET`448For the Ruby example, set the `OPENAI_API_KEY` and `OPENAI_WEBHOOK_SECRET`

444environment variables, then install the required dependencies with449environment variables, then install the required dependencies with

445`gem install openai webrick async-websocket`.450`gem install openai webrick async-websocket`.

446 451 

452 

453 

454 

455 

456 

457 

458For TypeScript, install the dependencies with `npm install openai express ws`. Save the complete example below as `sip-realtime-api-webhook.ts` in the directory where you installed the dependencies. Set `OPENAI_API_KEY` and `OPENAI_WEBHOOK_SECRET`, then run `node --experimental-strip-types sip-realtime-api-webhook.ts`. Forward requests from your configured HTTPS webhook endpoint to `http://127.0.0.1:8000/webhook`, preserving the raw request body and signature headers. The example deduplicates accepted call IDs in memory; production deployments need shared, durable deduplication across instances and restarts.

459 

460 

461 

462 

447Handle an incoming SIP call463Handle an incoming SIP call

448 464 

465```typescript

466import express from "express";

467import OpenAI from "openai";

468import { OpenAIRealtimeWS } from "openai/realtime/ws";

469 

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

471if (!process.env.OPENAI_WEBHOOK_SECRET)

472 throw new Error("Set OPENAI_WEBHOOK_SECRET");

473const app = express();

474// Persist accepted call IDs in production for deduplication across restarts.

475const accepted = new Map<string, Promise<void>>();

476 

477async function greetCaller(callID: string) {

478 const connection = new OpenAIRealtimeWS({ callID }, client);

479 try {

480 await new Promise<void>((resolve, reject) => {

481 const timer = setTimeout(

482 () => reject(new Error("Greeting timed out")),

483 120000

484 );

485 const finish = (error?: Error) => {

486 clearTimeout(timer);

487 if (error) reject(error);

488 else resolve();

489 };

490 connection.on("error", () =>

491 finish(new Error("Realtime greeting failed"))

492 );

493 connection.socket.on("close", () =>

494 finish(new Error("Call closed before greeting completed"))

495 );

496 connection.socket.once("open", () => {

497 connection.send({

498 type: "response.create",

499 response: {

500 instructions: "Thank the caller and ask how you can help.",

501 output_modalities: ["audio"],

502 },

503 });

504 });

505 connection.on("response.done", (event) => {

506 if (event.response.status !== "completed")

507 finish(new Error("Greeting did not complete"));

508 else finish();

509 });

510 });

511 console.log("Call greeting completed");

512 } finally {

513 connection.close();

514 }

515}

516 

517app.post(

518 "/webhook",

519 express.text({ type: "application/json", limit: "1mb" }),

520 async (req, res) => {

521 let event;

522 try {

523 if (typeof req.body !== "string") throw new Error("Expected JSON text");

524 const headers = new Headers();

525 for (const [key, value] of Object.entries(req.headers)) {

526 if (value !== undefined)

527 headers.set(key, Array.isArray(value) ? value.join(",") : value);

528 }

529 event = await client.webhooks.unwrap(req.body, headers);

530 } catch {

531 res.status(400).send("Invalid webhook");

532 return;

533 }

534 if (event.type !== "realtime.call.incoming") {

535 res.sendStatus(200);

536 return;

537 }

538 const callID = event.data.call_id;

539 try {

540 let attempt = accepted.get(callID);

541 if (!attempt) {

542 // Bound this demo's in-memory deduplication storage without forgetting calls.

543 if (accepted.size >= 10000) {

544 res.sendStatus(503);

545 return;

546 }

547 attempt = client.realtime.calls

548 .accept(callID, {

549 type: "realtime",

550 model: "gpt-realtime-2.1",

551 instructions: "You are a helpful support agent.",

552 })

553 .then(() => {

554 void greetCaller(callID).catch(() =>

555 console.error("Call greeting failed")

556 );

557 })

558 .catch((error) => {

559 accepted.delete(callID);

560 throw error;

561 });

562 accepted.set(callID, attempt);

563 }

564 await attempt;

565 res.sendStatus(200);

566 } catch {

567 res.status(502).send("Could not accept call");

568 }

569 }

570);

571app.listen(8000, "127.0.0.1", () =>

572 console.log("SIP webhook listening on port 8000")

573);

574```

575 

449```python576```python

450from flask import Flask, request, Response, jsonify, make_response577from flask import Flask, request, Response, jsonify, make_response

451from openai import OpenAI, InvalidWebhookSignatureError578from openai import OpenAI, InvalidWebhookSignatureError

Details

16 16 

17Install the WebSocket dependencies with `pip install "openai[realtime]>=3.8.0"` for Python, `npm install openai@^7.10.0 ws` for JavaScript, or `gem install openai async-websocket` for Ruby.17Install the WebSocket dependencies with `pip install "openai[realtime]>=3.8.0"` for Python, `npm install openai@^7.10.0 ws` for JavaScript, or `gem install openai async-websocket` for Ruby.

18 18 

19For Go, run `go get github.com/openai/openai-go/v3@v3.103.0`.19For Go, run `go get github.com/openai/openai-go/v3@v3.104.0`.

20For Java, add the Maven dependency `com.openai:openai-java:4.105.0` and use Java 17 or later for these examples.20For Java, add the Maven dependency `com.openai:openai-java:4.105.0` and use Java 17 or later for these examples.

21These Go and Java SDK versions provide native Responses WebSocket support.21These Go and Java SDK versions provide native Responses WebSocket support.

22 22 

Details

413gem install openai oci413gem install openai oci

414```414```

415 415 

416 

417 

418 

419For TypeScript, install `openai` and `oci-common`. Save the sample as `oracle-workload-identity-sdk.ts` and run `node --experimental-strip-types oracle-workload-identity-sdk.ts` on the OCI instance.

420 

421 

422 

423 

416Set `OCI_IDENTITY_DOMAIN_URL` to the base URL of the identity domain in the same tenancy as the workload. Set `OPENAI_IDENTITY_PROVIDER_ID` and `OPENAI_SERVICE_ACCOUNT_ID` to the IDs from your OpenAI provider and service account mapping.424Set `OCI_IDENTITY_DOMAIN_URL` to the base URL of the identity domain in the same tenancy as the workload. Set `OPENAI_IDENTITY_PROVIDER_ID` and `OPENAI_SERVICE_ACCOUNT_ID` to the IDs from your OpenAI provider and service account mapping.

417 425 

418The following example signs an Oracle token exchange request with the OCI instance principal, returns the IDCS access token to the OpenAI SDK, and lets the SDK exchange it for a short-lived OpenAI access token when needed:426The following example signs an Oracle token exchange request with the OCI instance principal, returns the IDCS access token to the OpenAI SDK, and lets the SDK exchange it for a short-lived OpenAI access token when needed:

419 427 

420Authenticate with an OCI instance principal428Authenticate with an OCI instance principal

421 429 

430```typescript

431import OpenAI from "openai";

432import type { SubjectTokenProvider } from "openai/auth";

433import {

434 DefaultRequestSigner,

435 InstancePrincipalsAuthenticationDetailsProviderBuilder,

436} from "oci-common";

437import type { HttpRequest } from "oci-common";

438 

439const identityProviderId = process.env.OPENAI_IDENTITY_PROVIDER_ID;

440const serviceAccountId = process.env.OPENAI_SERVICE_ACCOUNT_ID;

441const identityDomain = process.env.OCI_IDENTITY_DOMAIN_URL;

442if (!identityProviderId || !serviceAccountId || !identityDomain) {

443 throw new Error(

444 "Set OPENAI_IDENTITY_PROVIDER_ID, OPENAI_SERVICE_ACCOUNT_ID, and OCI_IDENTITY_DOMAIN_URL"

445 );

446}

447const domain = new URL(identityDomain);

448if (

449 domain.protocol !== "https:" ||

450 domain.username ||

451 domain.password ||

452 domain.pathname !== "/" ||

453 domain.search ||

454 domain.hash

455) {

456 throw new Error(

457 "OCI_IDENTITY_DOMAIN_URL must be an HTTPS identity-domain origin"

458 );

459}

460const provider: SubjectTokenProvider = {

461 tokenType: "jwt",

462 async getToken() {

463 const principal =

464 await new InstancePrincipalsAuthenticationDetailsProviderBuilder().build();

465 const signer = new DefaultRequestSigner(principal);

466 const request: HttpRequest = {

467 uri: new URL("/oauth2/v1/token", domain).href,

468 method: "POST",

469 headers: new Headers({

470 "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",

471 }),

472 body: new URLSearchParams({

473 grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",

474 scope: "urn:opc:idm:__myscopes__",

475 requested_token_type: "urn:ietf:params:oauth:token-type:access_token",

476 }).toString(),

477 };

478 await signer.signHttpRequest(request);

479 const response = await fetch(request.uri, {

480 method: request.method,

481 headers: request.headers,

482 body: request.body,

483 redirect: "error",

484 signal: AbortSignal.timeout(30000),

485 });

486 if (!response.ok)

487 throw new Error(`Oracle token request failed: HTTP ${response.status}`);

488 const token = await response.json();

489 if (typeof token.access_token !== "string" || !token.access_token) {

490 throw new Error("Oracle did not return an access token");

491 }

492 return token.access_token;

493 },

494};

495const client = new OpenAI({

496 apiKey: null,

497 workloadIdentity: { identityProviderId, serviceAccountId, provider },

498});

499console.log(

500 (

501 await client.responses.create({

502 model: "gpt-6.1-terra",

503 input:

504 "Say hello from Oracle Cloud Infrastructure workload identity federation.",

505 })

506 ).output_text

507);

508```

509 

422```python510```python

423import os511import os

424 512 

libraries.md +1 −1

Details

177<dependency>177<dependency>

178 <groupId>com.openai</groupId>178 <groupId>com.openai</groupId>

179 <artifactId>openai-java</artifactId>179 <artifactId>openai-java</artifactId>

180 <version>4.110.0</version>180 <version>4.111.0</version>

181</dependency>181</dependency>

182```182```

183 183 

mcp.md +131 −2

Details

177 177 

178Create a document search MCP server178Create a document search MCP server

179 179 

180```typescript

181import OpenAI from "openai";

182import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

183import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";

184import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";

185import { z } from "zod";

186 

187const client = new OpenAI();

188// Replace this illustrative ID with your existing document store ID.

189const vectorStoreID = "vs_123";

190const citation = (id: string) =>

191 `https://platform.openai.com/storage/files/${encodeURIComponent(id)}`;

192function createServer() {

193 const server = new McpServer(

194 { name: "Sample MCP Server", version: "1.0.0" },

195 {

196 instructions:

197 "Search for relevant documents, then fetch complete content with citations.",

198 }

199 );

200 server.registerTool(

201 "search",

202 {

203 description:

204 "Search documents and return identities, titles, and citation URLs.",

205 inputSchema: { query: z.string() },

206 outputSchema: {

207 results: z.array(

208 z.object({ id: z.string(), title: z.string(), url: z.string() })

209 ),

210 },

211 },

212 async ({ query }) => {

213 const results: { id: string; title: string; url: string }[] = [];

214 if (query.trim()) {

215 const page = await client.vectorStores.search(vectorStoreID, { query });

216 for (const item of page.data)

217 results.push({

218 id: item.file_id,

219 title: item.filename,

220 url: citation(item.file_id),

221 });

222 }

223 const result = { results };

224 return {

225 content: [{ type: "text", text: JSON.stringify(result) }],

226 structuredContent: result,

227 };

228 }

229 );

230 server.registerTool(

231 "fetch",

232 {

233 description:

234 "Retrieve a complete document with its citation and metadata.",

235 inputSchema: { id: z.string().min(1) },

236 outputSchema: {

237 id: z.string(),

238 title: z.string(),

239 text: z.string(),

240 url: z.string(),

241 metadata: z.record(z.string(), z.unknown()),

242 },

243 },

244 async ({ id }) => {

245 const parts: string[] = [];

246 for await (const item of client.vectorStores.files.content(id, {

247 vector_store_id: vectorStoreID,

248 })) {

249 if (typeof item.text !== "string")

250 throw new Error("Document content omitted text");

251 parts.push(item.text);

252 }

253 const attachment = await client.vectorStores.files.retrieve(id, {

254 vector_store_id: vectorStoreID,

255 });

256 const file = await client.files.retrieve(id);

257 const result = {

258 id,

259 title: file.filename,

260 text: parts.join("\n"),

261 url: citation(id),

262 metadata: attachment.attributes ?? {},

263 };

264 return {

265 content: [{ type: "text", text: JSON.stringify(result) }],

266 structuredContent: result,

267 };

268 }

269 );

270 return server;

271}

272// Loopback binding and SDK Host validation protect this local example.

273const app = createMcpExpressApp({ host: "127.0.0.1" });

274app.all("/mcp", async (request, response) => {

275 const server = createServer();

276 const transport = new StreamableHTTPServerTransport({

277 sessionIdGenerator: undefined,

278 enableJsonResponse: true,

279 });

280 response.on("close", () => {

281 void transport.close();

282 void server.close();

283 });

284 try {

285 await server.connect(transport);

286 await transport.handleRequest(request, response, request.body);

287 } catch (error) {

288 console.error("MCP request failed", error);

289 if (!response.headersSent)

290 response.status(500).end("Internal server error");

291 }

292});

293const httpServer = app.listen(8000, "127.0.0.1");

294```

295 

180```python296```python

181# Replace the illustrative IDs and URLs below with your own resource values.297# Replace the illustrative IDs and URLs below with your own resource values.

182"""298"""


670 789 

671 790 

672 791 

673For Ruby, install the `openai`, `mcp` (version 1.10.0), `rackup`, and `webrick` gems, save the Ruby source as `server.rb`, and run `ruby server.rb`. Set `OPENAI_VECTOR_STORE_ID` to your vector store ID and `MCP_HOST` to `0.0.0.0` on Replit. The Ruby server uses Streamable HTTP at `/mcp`; use that path instead of `/sse/` in the connection URL. The Ruby server uses port 8000 by default or the port specified by `PORT`.792 

793 

794 

795For Ruby, install the `openai`, `mcp`, `rackup`, and `webrick` gems, save the Ruby source as `server.rb`, and run `ruby server.rb`. Set `OPENAI_VECTOR_STORE_ID` to your vector store ID and `MCP_HOST` to `0.0.0.0` on Replit. The Ruby server uses Streamable HTTP at `/mcp`; use that path instead of `/sse/` in the connection URL. The Ruby server uses port 8000 by default or the port specified by `PORT`.

796 

797 

798 

799 

800 

801 

802 

803Download and extract the [TypeScript samples and locked dependencies](https://developers.openai.com/api/docs/samples/typescript.tar.gz): OpenAI, the MCP SDK, and Zod. Set `OPENAI_API_KEY` and replace `vs_123` with your vector store ID. From the sample project directory, run `pnpm install --ignore-workspace --frozen-lockfile`, then start the server with `node --experimental-strip-types mcp/mcp-server.ts`.

804 

805The local server uses Streamable HTTP at `http://127.0.0.1:8000/mcp`. For a hosted deployment, change the `app.listen` binding to `0.0.0.0` and set the `createMcpExpressApp` options to `host: "0.0.0.0"` with `allowedHosts` containing your exact deployment hostname. Keep Host validation enabled, configure HTTPS and access controls at your hosting boundary, and use the `/mcp` path in the connection URL. Change the port number if your host requires a different port.

674 806 

675 807 

676 808 


678 810 

679 811 

680 812 

681For Go, use Go 1.26 or later with `github.com/openai/openai-go/v3` and `github.com/modelcontextprotocol/go-sdk@v1.8.0`. Set `OPENAI_API_KEY`, replace the illustrative `vs_123` value with your existing vector store ID, save the source as `main.go` in your module, and run `go run .`. The server uses Streamable HTTP at `/mcp` on port 8000. Edit the `port` literal to use another port and the `host` literal to bind the server to `0.0.0.0` on Replit.813For Go, use `github.com/openai/openai-go/v3` and `github.com/modelcontextprotocol/go-sdk`. Set `OPENAI_API_KEY`, replace the illustrative `vs_123` value with your existing vector store ID, save the source as `main.go` in your module, and run `go run .`. The server uses Streamable HTTP at `/mcp` on port 8000. Edit the `port` literal to use another port and the `host` literal to bind the server to `0.0.0.0` on Replit.

682 814 

683 815 

684 816 

quickstart.md +1 −1

Details

187<dependency>187<dependency>

188 <groupId>com.openai</groupId>188 <groupId>com.openai</groupId>

189 <artifactId>openai-java</artifactId>189 <artifactId>openai-java</artifactId>

190 <version>4.110.0</version>190 <version>4.111.0</version>

191</dependency>191</dependency>

192```192```

193 193 

Details

6 6 

7# Getting started7# Getting started

8 8 

9Some basic knowledge of Python and GitHub is helpful for this tutorial. Before diving in, make sure to [set up an OpenAI API key](https://developers.openai.com/api/reference/overview) and walk through the [quickstart tutorial](https://developers.openai.com/api/docs/quickstart). This will give a good intuition on how to use the API to its full potential.9Before starting, [set up an OpenAI API key](https://developers.openai.com/api/reference/overview) and work through the [quickstart tutorial](https://developers.openai.com/api/docs/quickstart).

10 10 

11Use Python 3.11 or later. Create a virtual environment, install the packages used in the examples, and set `OPENAI_API_KEY` as described in the [quickstart](https://developers.openai.com/api/docs/quickstart).11 

12 

13 

14Create a virtual environment and install the packages:

12 15 

13```bash16```bash

14python -m venv env17python -m venv env


16python -m pip install openai pandas numpy requests beautifulsoup4 tiktoken matplotlib19python -m pip install openai pandas numpy requests beautifulsoup4 tiktoken matplotlib

17```20```

18 21 

22Copy the Python examples into a file or notebook in the order shown.

19 23 

20 24 

21 25 

22The Go examples use `github.com/openai/openai-go/v3` at `v3.98.0`, `github.com/tiktoken-go/tokenizer` at `v0.10.0`, and `golang.org/x/net/html` at `v0.63.0`. Use the complete programs in the [Go tutorial sample directory](https://github.com/openai/developers-website/tree/main/src/content/platform/go-examples/tutorial-crawl-website-embeddings). When running downloaded source files, replace `{{MODEL}}` with the model shown in the rendered example. Run each workflow step separately from the same working directory; don't concatenate their `main` functions. The hyperlink helpers share one program, and context retrieval, answering, and test questions share another.

23 26 

24Replace `https://example.com` with your website's URL in the crawler, hyperlink, and scraped-data programs. Set `OPENAI_API_KEY` before the API steps. The Go crawler follows same-domain redirects and writes files under `text`; subsequent programs read and write `processed/scraped.csv`, `processed/chunks.json`, and `processed/embeddings.csv` in order. The histogram steps write `token-histogram.png` locally.27 

28 

29 

30Download and extract the [TypeScript sample archive](https://developers.openai.com/api/docs/samples/typescript.tar.gz). From the extracted `typescript-examples` directory, run `pnpm install --ignore-workspace --frozen-lockfile`. The lockfile pins OpenAI, Cheerio, CSV, tokenizer, and canvas dependencies. Set `OPENAI_API_KEY` before the API steps.

31 

32Run each complete program separately from the same working directory with `node --experimental-strip-types tutorial-crawl-website-embeddings/<filename>.ts`. Do not concatenate the excerpts: each file includes its own imports and setup. Run `crawl-website`, `build-scraped-dataframe`, `tokenize-scraped-text`, `split-long-text`, `visualize-chunk-token-counts`, `create-embeddings`, and `answer-question` in that order. The hyperlink helpers share one program; context retrieval, answering, and test questions share `answer-question.ts`.

33 

34Replace `https://example.com` with your website's URL in the crawler, hyperlink, and scraped-data programs. Replace `{{MODEL}}` in the downloaded answering program with the model shown below. The crawler saves text under `text`; later stages produce `processed/scraped.csv`, `processed/chunks.json`, and `processed/embeddings.csv`. Run `create-embeddings` before answering questions; the package's synthetic CSV fixtures are only for local analysis tests.

35 

25 36 

26 37 

27 38 

28 39 

29 40 

30 41 

42The Go examples use `github.com/openai/openai-go/v3`, `github.com/tiktoken-go/tokenizer`, and `golang.org/x/net/html`. Use the complete programs in the [Go tutorial sample directory](https://github.com/openai/developers-website/tree/main/src/content/platform/go-examples/tutorial-crawl-website-embeddings). When running downloaded source files, replace `{{MODEL}}` with the model shown in the rendered example. Run each workflow step separately from the same working directory; don't concatenate their `main` functions. The hyperlink helpers share one program, and context retrieval, answering, and test questions share another.

43 

44Replace `https://example.com` with your website's URL in the crawler, hyperlink, and scraped-data programs. Set `OPENAI_API_KEY` before the API steps. The Go crawler follows same-domain redirects and writes files under `text`; subsequent programs read and write `processed/scraped.csv`, `processed/chunks.json`, and `processed/embeddings.csv` in order. The histogram steps write `token-histogram.png` locally.

45 

46 

47 

31 48 

32For Ruby, use Ruby 3.3 with the `openai`, `nokogiri`, `tiktoken_ruby`, and `chunky_png` gems. The [sample dependencies](https://github.com/openai/developers-website/blob/main/src/content/platform/ruby-examples/Gemfile) list tested versions.

33 49 

34 50 

35 51 

52For Ruby, install the `openai`, `nokogiri`, `tiktoken_ruby`, and `chunky_png` gems. The [sample dependencies](https://developers.openai.com/api/docs/samples/ruby-Gemfile) list tested versions.

36 53 

37Set `OPENAI_API_KEY` for either language.

38 54 

39Copy the examples into a file or notebook for the selected language in the order shown.55 

56 

57Set `OPENAI_API_KEY` before running examples in your selected language.

40 58 

41 59 

42 60 


76 94 

77Set up the web crawler95Set up the web crawler

78 96 

97```typescript

98import { load } from "cheerio";

99 

100function getHTMLHyperlinks(html: string): string[] {

101 const document = load(html);

102 return document("a[href]")

103 .map((_, node) => document(node).attr("href")!)

104 .get();

105}

106```

107 

79```python108```python

80import requests109import requests

81import re110import re


190 219 

191Extract links from a page220Extract links from a page

192 221 

222```typescript

223import { load } from "cheerio";

224 

225function parseHTML(html: string): { links: string[]; text: string } {

226 const document = load(html);

227 document("script, style").remove();

228 return {

229 links: document("a[href]")

230 .map((_, node) => document(node).attr("href")!)

231 .get(),

232 text: document.root().text(),

233 };

234}

235 

236function validURL(url: URL): boolean {

237 return (

238 ["http:", "https:"].includes(url.protocol) && !url.username && !url.password

239 );

240}

241 

242async function fetchPage(address: string, domain: string) {

243 let url = new URL(address);

244 const signal = AbortSignal.timeout(10_000);

245 for (let redirects = 0; ; redirects++) {

246 if (!validURL(url) || url.host !== domain) {

247 throw new Error("Expected a same-domain HTTP or HTTPS URL");

248 }

249 url.hash = "";

250 const response = await fetch(url, { redirect: "manual", signal });

251 if ([301, 302, 303, 307, 308].includes(response.status)) {

252 await response.body?.cancel();

253 const location = response.headers.get("location");

254 if (!location) return null;

255 if (redirects >= 5) throw new Error("Too many redirects");

256 url = new URL(location, url);

257 continue;

258 }

259 if (

260 !response.ok ||

261 response.headers

262 .get("content-type")

263 ?.split(";")[0]

264 .trim()

265 .toLowerCase() !== "text/html"

266 ) {

267 await response.body?.cancel();

268 return null;

269 }

270 const reader = response.body?.getReader();

271 if (!reader) return null;

272 const buffers: Uint8Array[] = [];

273 let bytes = 0;

274 try {

275 while (true) {

276 const { done, value } = await reader.read();

277 if (done) break;

278 bytes += value.length;

279 if (bytes > 8 * 1024 * 1024) throw new Error("HTML page exceeds 8 MiB");

280 buffers.push(value);

281 }

282 } finally {

283 await reader.cancel();

284 }

285 return { url, ...parseHTML(Buffer.concat(buffers).toString("utf8")) };

286 }

287}

288 

289async function getHyperlinks(address: string): Promise<string[]> {

290 const page = await fetchPage(address, new URL(address).host);

291 if (!page) return [];

292 return page.links.flatMap((link) => {

293 if (!link || link.startsWith("#")) return [];

294 try {

295 return [new URL(link, page.url).href];

296 } catch {

297 return [];

298 }

299 });

300}

301```

302 

193```python303```python

194# Function to get the hyperlinks from a URL304# Function to get the hyperlinks from a URL

195def get_hyperlinks(url):305def get_hyperlinks(url):


370 480 

371Keep links within the target domain481Keep links within the target domain

372 482 

483```typescript

484async function getDomainHyperlinks(

485 domain: string,

486 address: string

487): Promise<string[]> {

488 const links = await getHyperlinks(address);

489 const result = new Set<string>();

490 for (const link of links) {

491 const url = new URL(link);

492 if (!validURL(url) || url.host !== domain) continue;

493 url.hash = "";

494 result.add(url.href);

495 }

496 return [...result];

497}

498const address = "https://example.com";

499console.log(

500 JSON.stringify(await getDomainHyperlinks(new URL(address).host, address))

501);

502```

503 

373```python504```python

374# Function to get the hyperlinks from a URL that are within the same domain505# Function to get the hyperlinks from a URL that are within the same domain

375def get_domain_hyperlinks(local_domain, url):506def get_domain_hyperlinks(local_domain, url):


448 579 

449Crawl the website580Crawl the website

450 581 

582```typescript

583import { createHash } from "node:crypto";

584import { mkdir, writeFile } from "node:fs/promises";

585import path from "node:path";

586 

587async function crawl(address: string): Promise<void> {

588 const initial = new URL(address);

589 if (!validURL(initial)) throw new Error("Expected an HTTP or HTTPS URL");

590 initial.hash = "";

591 const directory = path.join("text", initial.host);

592 await mkdir(directory, { recursive: true });

593 await mkdir("processed", { recursive: true });

594 const queue = [initial.href];

595 const queued = new Set(queue);

596 const visited = new Set<string>();

597 while (queue.length) {

598 const current = queue.pop()!;

599 const page = await fetchPage(current, initial.host);

600 if (!page || visited.has(page.url.href)) continue;

601 visited.add(page.url.href);

602 console.log(page.url.href);

603 const digest = createHash("sha256").update(page.url.href).digest("hex");

604 // URL-encoded paths keep filenames ASCII; the digest prevents collisions.

605 const prefix = `${initial.host}${page.url.pathname}`

606 .replaceAll("/", "_")

607 .slice(0, 186);

608 await writeFile(path.join(directory, `${prefix}#${digest}.txt`), page.text);

609 for (const link of page.links) {

610 if (!link || link.startsWith("#")) continue;

611 let next: URL;

612 try {

613 next = new URL(link, page.url);

614 } catch {

615 continue;

616 }

617 next.hash = "";

618 if (

619 !validURL(next) ||

620 next.host !== initial.host ||

621 queued.has(next.href) ||

622 visited.has(next.href)

623 )

624 continue;

625 queued.add(next.href);

626 queue.push(next.href);

627 }

628 }

629}

630 

631await crawl("https://example.com");

632```

633 

451```python634```python

452from hashlib import sha256635from hashlib import sha256

453 636 


813 996 

814Clean the scraped text997Clean the scraped text

815 998 

999```typescript

1000function removeNewlines(texts: string[]): string[] {

1001 return texts.map((text) =>

1002 text.replaceAll("\n", " ").replaceAll("\\n", " ").replace(/ {2,}/g, " ")

1003 );

1004}

1005```

1006 

816```python1007```python

817def remove_newlines(serie):1008def remove_newlines(serie):

818 serie = serie.str.replace("\n", " ")1009 serie = serie.str.replace("\n", " ")


871 1062 

872Save scraped pages as a dataset1063Save scraped pages as a dataset

873 1064 

1065```typescript

1066import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";

1067import path from "node:path";

1068import { stringify } from "csv-stringify/sync";

1069 

1070const address = new URL("https://example.com");

1071const directory = path.join("text", address.host);

1072const rows: { fname: string; text: string }[] = [];

1073const entries = await readdir(directory, { withFileTypes: true });

1074entries.sort((a, b) => a.name.localeCompare(b.name));

1075for (const entry of entries) {

1076 if (!entry.isFile() || !entry.name.endsWith(".txt")) continue;

1077 let title = entry.name.slice(0, -4).replace(/#[a-f0-9]{64}$/, "");

1078 if (title === address.host || title === `${address.host}_`) title = "index";

1079 else if (title.startsWith(`${address.host}_`))

1080 title = title.slice(address.host.length + 1);

1081 title = title.replaceAll("#update", "").replace(/[-_]/g, " ");

1082 const content = await readFile(path.join(directory, entry.name), "utf8");

1083 const text = content

1084 .replaceAll("\n", " ")

1085 .replaceAll("\\n", " ")

1086 .replace(/ {2,}/g, " ");

1087 rows.push({ fname: title, text: `${title}. ${text}` });

1088}

1089await mkdir("processed", { recursive: true });

1090await writeFile(

1091 "processed/scraped.csv",

1092 stringify(rows, {

1093 header: true,

1094 columns: ["fname", "text"],

1095 })

1096);

1097```

1098 

874```python1099```python

875from pathlib import Path1100from pathlib import Path

876 1101 


1040 1265 

1041Count tokens in scraped pages1266Count tokens in scraped pages

1042 1267 

1268```typescript

1269import { readFile, writeFile } from "node:fs/promises";

1270import { createCanvas } from "@napi-rs/canvas";

1271import { getEncoding } from "js-tiktoken";

1272const encoding = getEncoding("cl100k_base");

1273import { parse } from "csv-parse/sync";

1274const rows: { text: string }[] = parse(

1275 await readFile("processed/scraped.csv", "utf8"),

1276 { columns: true, skip_empty_lines: true }

1277);

1278const texts = rows.map((row) => row.text);

1279const counts = texts.map((text) => encoding.encode(text).length);

1280const bins = Array<number>(10).fill(0);

1281const maximum = Math.max(1, ...counts);

1282for (const count of counts)

1283 bins[Math.min(9, Math.floor((count / maximum) * 10))]++;

1284const canvas = createCanvas(800, 600);

1285const context = canvas.getContext("2d");

1286context.fillStyle = "white";

1287context.fillRect(0, 0, 800, 600);

1288context.fillStyle = "black";

1289context.font = "20px sans-serif";

1290context.fillText("Token counts", 40, 30);

1291const largestBin = Math.max(1, ...bins);

1292context.fillStyle = "steelblue";

1293for (const [index, count] of bins.entries()) {

1294 const height = (count / largestBin) * 480;

1295 context.fillRect(40 + index * 72, 540 - height, 68, height);

1296}

1297context.fillStyle = "black";

1298context.fillText("0", 40, 575);

1299context.fillText(String(maximum), 740, 575);

1300await writeFile("token-histogram.png", await canvas.encode("png"));

1301```

1302 

1043```python1303```python

1044import tiktoken1304import tiktoken

1045 1305 


1202 1462 

1203Split long pages into chunks1463Split long pages into chunks

1204 1464 

1465```typescript

1466import { readFile, writeFile } from "node:fs/promises";

1467import { parse } from "csv-parse/sync";

1468import { getEncoding } from "js-tiktoken";

1469 

1470const encoding = getEncoding("cl100k_base");

1471function splitIntoMany(text: string, maxTokens = 500): string[] {

1472 if (!Number.isInteger(maxTokens) || maxTokens <= 0) {

1473 throw new Error("maxTokens must be a positive integer");

1474 }

1475 if (!text.trim()) return [];

1476 const sentences = text.split(". ");

1477 const chunks: string[] = [];

1478 let chunk = "";

1479 for (const [index, part] of sentences.entries()) {

1480 const sentence = index < sentences.length - 1 ? `${part}.` : part;

1481 if (encoding.encode(sentence).length > maxTokens) {

1482 throw new Error("Split the oversized sentence before chunking");

1483 }

1484 const candidate = chunk ? `${chunk} ${sentence}` : sentence;

1485 if (encoding.encode(candidate).length > maxTokens) {

1486 chunks.push(chunk);

1487 chunk = sentence;

1488 } else chunk = candidate;

1489 }

1490 if (chunk) chunks.push(chunk);

1491 return chunks;

1492}

1493 

1494const rows: { text: string }[] = parse(

1495 await readFile("processed/scraped.csv", "utf8"),

1496 { columns: true, skip_empty_lines: true }

1497);

1498const chunks = rows.flatMap((row) => splitIntoMany(row.text));

1499await writeFile("processed/chunks.json", JSON.stringify(chunks));

1500```

1501 

1205```python1502```python

1206max_tokens = 5001503max_tokens = 500

1207 1504 


1411 1708 

1412Visualize token counts after splitting1709Visualize token counts after splitting

1413 1710 

1711```typescript

1712import { readFile, writeFile } from "node:fs/promises";

1713import { createCanvas } from "@napi-rs/canvas";

1714import { getEncoding } from "js-tiktoken";

1715const encoding = getEncoding("cl100k_base");

1716const texts: string[] = JSON.parse(

1717 await readFile("processed/chunks.json", "utf8")

1718);

1719const counts = texts.map((text) => encoding.encode(text).length);

1720const bins = Array<number>(10).fill(0);

1721const maximum = Math.max(1, ...counts);

1722for (const count of counts)

1723 bins[Math.min(9, Math.floor((count / maximum) * 10))]++;

1724const canvas = createCanvas(800, 600);

1725const context = canvas.getContext("2d");

1726context.fillStyle = "white";

1727context.fillRect(0, 0, 800, 600);

1728context.fillStyle = "black";

1729context.font = "20px sans-serif";

1730context.fillText("Token counts", 40, 30);

1731const largestBin = Math.max(1, ...bins);

1732context.fillStyle = "steelblue";

1733for (const [index, count] of bins.entries()) {

1734 const height = (count / largestBin) * 480;

1735 context.fillRect(40 + index * 72, 540 - height, 68, height);

1736}

1737context.fillStyle = "black";

1738context.fillText("0", 40, 575);

1739context.fillText(String(maximum), 740, 575);

1740await writeFile("token-histogram.png", await canvas.encode("png"));

1741```

1742 

1414```python1743```python

1415df = pd.DataFrame(shortened, columns=["text"])1744df = pd.DataFrame(shortened, columns=["text"])

1416df["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))1745df["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))


1531 1860 

1532Create embeddings for the scraped text1861Create embeddings for the scraped text

1533 1862 

1863```typescript

1864import OpenAI from "openai";

1865import { readFile, writeFile } from "node:fs/promises";

1866import { stringify } from "csv-stringify/sync";

1867 

1868const client = new OpenAI();

1869const chunks: string[] = JSON.parse(

1870 await readFile("processed/chunks.json", "utf8")

1871);

1872if (

1873 !Array.isArray(chunks) ||

1874 !chunks.every((text) => typeof text === "string")

1875) {

1876 throw new Error("Expected an array of text chunks");

1877}

1878const rows: (string | number)[][] = [["text", "n_tokens", "embeddings"]];

1879for (const text of chunks) {

1880 const response = await client.embeddings.create({

1881 model: "text-embedding-3-small",

1882 input: text,

1883 });

1884 if (

1885 response.data.length !== 1 ||

1886 response.data[0].index !== 0 ||

1887 !response.data[0].embedding.length

1888 ) {

1889 throw new Error("Expected one embedding per chunk");

1890 }

1891 rows.push([

1892 text,

1893 response.usage.prompt_tokens,

1894 JSON.stringify(response.data[0].embedding),

1895 ]);

1896}

1897await writeFile("processed/embeddings.csv", stringify(rows));

1898```

1899 

1534```python1900```python

1535from openai import OpenAI1901from openai import OpenAI

1536 1902 


1652 2018 

1653Load the saved embeddings2019Load the saved embeddings

1654 2020 

2021```typescript

2022import { readFile } from "node:fs/promises";

2023import { parse } from "csv-parse/sync";

2024 

2025const records: { text: string; embeddings: string }[] = parse(

2026 await readFile("processed/embeddings.csv", "utf8"),

2027 { columns: true, skip_empty_lines: true }

2028);

2029const rows = records.map((row) => ({

2030 text: row.text,

2031 embedding: JSON.parse(row.embeddings) as number[],

2032}));

2033if (!rows.length) throw new Error("No embeddings");

2034const dimensions = rows[0].embedding.length;

2035for (const row of rows) {

2036 if (

2037 !Array.isArray(row.embedding) ||

2038 !dimensions ||

2039 row.embedding.length !== dimensions ||

2040 !row.embedding.every(Number.isFinite)

2041 ) {

2042 throw new Error("Expected finite embeddings with consistent dimensions");

2043 }

2044}

2045console.log(rows[0].embedding);

2046```

2047 

1655```python2048```python

1656from ast import literal_eval2049from ast import literal_eval

1657import numpy as np2050import numpy as np


1755 2148 

1756Build context for a question2149Build context for a question

1757 2150 

2151```typescript

2152import OpenAI from "openai";

2153import { readFile } from "node:fs/promises";

2154import { parse } from "csv-parse/sync";

2155 

2156interface EmbeddedRow {

2157 text: string;

2158 nTokens: number;

2159 embedding: number[];

2160}

2161async function loadEmbeddings(path: string): Promise<EmbeddedRow[]> {

2162 const records: { text: string; n_tokens: string; embeddings: string }[] =

2163 parse(await readFile(path, "utf8"), {

2164 columns: true,

2165 skip_empty_lines: true,

2166 });

2167 const rows = records.map((row) => ({

2168 text: row.text,

2169 nTokens: Number(row.n_tokens),

2170 embedding: JSON.parse(row.embeddings) as number[],

2171 }));

2172 if (!rows.length) throw new Error("No embeddings");

2173 const dimensions = rows[0].embedding.length;

2174 for (const row of rows) {

2175 if (

2176 typeof row.text !== "string" ||

2177 !Number.isInteger(row.nTokens) ||

2178 row.nTokens < 0 ||

2179 !Array.isArray(row.embedding) ||

2180 !dimensions ||

2181 row.embedding.length !== dimensions ||

2182 !row.embedding.every(Number.isFinite)

2183 ) {

2184 throw new Error("Invalid embedded row");

2185 }

2186 }

2187 return rows;

2188}

2189function cosineSimilarity(a: number[], b: number[]): number {

2190 if (a.length !== b.length || !a.length || !a.every(Number.isFinite))

2191 throw new Error("Invalid embedding dimensions or values");

2192 const dot = a.reduce((sum, value, i) => sum + value * b[i], 0);

2193 const norm = Math.sqrt(

2194 a.reduce((sum, value) => sum + value * value, 0) *

2195 b.reduce((sum, value) => sum + value * value, 0)

2196 );

2197 if (!(norm > 0)) throw new Error("Embedding must have a nonzero norm");

2198 return dot / norm;

2199}

2200async function createContext(

2201 client: OpenAI,

2202 question: string,

2203 rows: EmbeddedRow[],

2204 maxTokens = 1800

2205): Promise<string> {

2206 const response = await client.embeddings.create({

2207 model: "text-embedding-3-small",

2208 input: question,

2209 });

2210 if (response.data.length !== 1)

2211 throw new Error("Expected one query embedding");

2212 const ranked = rows

2213 .map((row) => ({

2214 row,

2215 similarity: cosineSimilarity(response.data[0].embedding, row.embedding),

2216 }))

2217 .sort((a, b) => b.similarity - a.similarity);

2218 const parts: string[] = [];

2219 let tokens = 0;

2220 for (const { row } of ranked) {

2221 tokens += row.nTokens + 4;

2222 if (tokens > maxTokens) break;

2223 parts.push(row.text);

2224 }

2225 return parts.join("\n\n###\n\n");

2226}

2227```

2228 

1758```python2229```python

1759def distances_from_embeddings(query, embeddings, distance_metric="cosine"):2230def distances_from_embeddings(query, embeddings, distance_metric="cosine"):

1760 if distance_metric != "cosine":2231 if distance_metric != "cosine":


1964 2435 

1965Answer a question from the website2436Answer a question from the website

1966 2437 

2438```typescript

2439async function answerQuestion(

2440 client: OpenAI,

2441 rows: EmbeddedRow[],

2442 question: string

2443): Promise<string> {

2444 const context = await createContext(client, question, rows);

2445 const response = await client.responses.create({

2446 model: "gpt-6-luna",

2447 instructions:

2448 'Answer the question using only the supplied context. If the context does not answer the question, say "I don\'t know."',

2449 input: `Context: ${context}\n\nQuestion: ${question}`,

2450 });

2451 if (response.status !== "completed")

2452 throw new Error(`Response ended with status ${response.status}`);

2453 return response.output_text.trim();

2454}

2455```

2456 

1967```python2457```python

1968def answer_question(df, question, max_len=1800):2458def answer_question(df, question, max_len=1800):

1969 context = create_context(question, df, max_len=max_len)2459 context = create_context(question, df, max_len=max_len)


2013 2503 

2014Try example questions2504Try example questions

2015 2505 

2506```typescript

2507const client = new OpenAI();

2508const rows = await loadEmbeddings("processed/embeddings.csv");

2509for (const question of [

2510 "What is ChatGPT?",

2511 "What did I have for breakfast today?",

2512]) {

2513 console.log(await answerQuestion(client, rows, question));

2514}

2515```

2516 

2016```python2517```python

2017print(answer_question(df, "What is ChatGPT?"))2518print(answer_question(df, "What is ChatGPT?"))

2018print(answer_question(df, "What did I have for breakfast today?"))2519print(answer_question(df, "What did I have for breakfast today?"))