SpyBara
Go Premium

Documentation 2026-11-23 23:58 UTC to 2026-11-24 23:00 UTC

38 files changed +3,711 −151. 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

162}162}

163```163```

164 164 

165```java

166import java.util.*;

167 

168System.out.println(countChatMessageTokens(List.of(Map.of("role", "user", "content", "Hi"))));

169 

170// Maven dependency: com.knuddels:jtokkit:1.1.0

171static final com.knuddels.jtokkit.api.Encoding ENCODING =

172 com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry()

173 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

174 

175static int countChatMessageTokens(List<Map<String, String>> messages) {

176 // This estimate follows gpt-3.5-turbo-0613 message framing, not all models.

177 int tokens = 3;

178 for (var message : messages) {

179 tokens += 3;

180 for (var entry : message.entrySet()) {

181 tokens += ENCODING.countTokens(entry.getValue());

182 if (entry.getKey().equals("name")) tokens++;

183 }

184 }

185 return tokens;

186}

187```

188 

165```ruby189```ruby

166require "tiktoken_ruby"190require "tiktoken_ruby"

167 191 


311}335}

312```336```

313 337 

338```java

339import java.util.*;

340 

341List<Map<String, String>> messages =

342 List.of(

343 Map.of(

344 "role",

345 "system",

346 "content",

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

348 Map.of(

349 "role",

350 "system",

351 "name",

352 "example_user",

353 "content",

354 "New synergies will help drive top-line growth."),

355 Map.of(

356 "role",

357 "system",

358 "name",

359 "example_assistant",

360 "content",

361 "Things working well together will increase revenue."),

362 Map.of(

363 "role",

364 "system",

365 "name",

366 "example_user",

367 "content",

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

369 Map.of(

370 "role",

371 "system",

372 "name",

373 "example_assistant",

374 "content",

375 "Let's talk later when we're less busy about how to do better."),

376 Map.of(

377 "role",

378 "user",

379 "content",

380 "This late pivot means we don't have time to boil the ocean for the client deliverable."));

381System.out.println(countChatMessageTokens(messages) + " prompt tokens counted.");

382 

383static final com.knuddels.jtokkit.api.Encoding ENCODING =

384 com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry()

385 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

386 

387static int countChatMessageTokens(List<Map<String, String>> messages) {

388 // This estimate follows gpt-3.5-turbo-0613 message framing, not all models.

389 int tokens = 3;

390 for (var message : messages) {

391 tokens += 3;

392 for (var entry : message.entrySet()) {

393 tokens += ENCODING.countTokens(entry.getValue());

394 if (entry.getKey().equals("name")) tokens++;

395 }

396 }

397 return tokens;

398}

399```

400 

314```ruby401```ruby

315require "json"402require "json"

316 403 


484}571}

485```572```

486 573 

574```java

575 

576 

577mu[j] = mu[j] - counts[j] * frequencyPenalty - (counts[j] > 0 ? presencePenalty : 0);

578System.out.println(mu[j]);

579```

580 

487```csharp581```csharp

488using System.Globalization;582using System.Globalization;

489 583 

Details

182}182}

183```183```

184 184 

185```java

186import com.openai.client.OpenAIClient;

187import com.openai.client.okhttp.OpenAIOkHttpClient;

188import com.openai.models.beta.agents.sessions.artifacts.*;

189import java.nio.file.*;

190 

191// Use your configured OpenAIClient named client.

192downloadArtifact(

193 client, "sess_123", "turn_123", "/workspace/outputs/report.pdf", Path.of("report.pdf"));

194 

195static void downloadArtifact(

196 OpenAIClient client, String sessionId, String turnId, String path, Path destination)

197 throws Exception {

198 var artifacts = client.beta().agents().sessions().artifacts();

199 for (var artifact :

200 artifacts.list(ArtifactListParams.builder().sessionId(sessionId).build()).autoPager()) {

201 if (!artifact.turnId().equals(turnId) || !artifact.path().equals(path)) continue;

202 try (var content =

203 artifacts.content(

204 ArtifactContentParams.builder()

205 .sessionId(sessionId)

206 .artifactId(artifact.id())

207 .build())) {

208 Files.copy(content.body(), destination, StandardCopyOption.REPLACE_EXISTING);

209 }

210 return;

211 }

212 throw new java.io.FileNotFoundException("No artifact for " + path + " in turn " + turnId);

213}

214```

215 

185```ruby216```ruby

186require "openai"217require "openai"

187 218 

Details

127 127 

128 128 

129 129 

130 

131 

132The Java version uses `io.modelcontextprotocol.sdk:mcp-core:1.1.5`, `io.modelcontextprotocol.sdk:mcp-json-jackson2:1.1.5`, and `com.fasterxml.jackson.core:jackson-databind:2.18.11`. It serves the same tool over standard input and output:

133 

134 

135 

136 

130Run a customer lookup MCP server137Run a customer lookup MCP server

131 138 

132```typescript139```typescript


245}252}

246```253```

247 254 

255```java

256import com.fasterxml.jackson.databind.json.JsonMapper;

257import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapper;

258import io.modelcontextprotocol.server.McpServer;

259import io.modelcontextprotocol.server.transport.StdioServerTransportProvider;

260import io.modelcontextprotocol.spec.McpSchema;

261import java.io.FilterInputStream;

262import java.io.IOException;

263import java.util.concurrent.CountDownLatch;

264 

265var mapper = new JacksonMcpJsonMapper(JsonMapper.builder().build());

266var closed = new CountDownLatch(1);

267var input =

268 new FilterInputStream(System.in) {

269 @Override

270 public int read(byte[] bytes, int offset, int length) throws IOException {

271 int count = super.read(bytes, offset, length);

272 if (count == -1) closed.countDown();

273 return count;

274 }

275 };

276var transport = new StdioServerTransportProvider(mapper, input, System.out);

277var tool =

278 McpSchema.Tool.builder()

279 .name("get_customer")

280 .description("Look up a customer in the example data.")

281 .inputSchema(

282 mapper,

283 """

284 {"type":"object","properties":{"customer_id":{"type":"string"}},"required":["customer_id"],"additionalProperties":false}

285 """)

286 .build();

287var server =

288 McpServer.sync(transport)

289 .serverInfo("customer-lookup", "1.0.0")

290 .capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())

291 .toolCall(

292 tool,

293 (exchange, request) -> {

294 String text =

295 "123".equals(request.arguments().get("customer_id"))

296 ? "{\"customer\":{\"name\":\"Example Customer\",\"plan\":\"pro\"}}"

297 : "{\"customer\":null}";

298 return McpSchema.CallToolResult.builder()

299 .addTextContent(text)

300 .isError(false)

301 .build();

302 })

303 .build();

304try {

305 closed.await();

306} finally {

307 server.closeGracefully();

308}

309```

310 

248```ruby311```ruby

249require "mcp"312require "mcp"

250require "json"313require "json"

Details

414}414}

415```415```

416 416 

417```java

418import com.fasterxml.jackson.databind.ObjectMapper;

419import com.openai.client.OpenAIClient;

420import com.openai.client.okhttp.OpenAIOkHttpClient;

421import com.openai.models.beta.agents.*;

422import com.openai.models.beta.agents.sessions.SessionCreateParams;

423import java.io.ByteArrayOutputStream;

424import java.nio.file.*;

425import java.util.*;

426import java.util.zip.*;

427 

428// Use your configured OpenAIClient named client.

429System.out.println(uploadPlugin(client, plugin));

430 

431static String uploadPlugin(OpenAIClient client, Path pluginDirectory) throws Exception {

432 Path plugin = pluginDirectory.toAbsolutePath().normalize();

433 // Reject links before reading the manifest or any archive content.

434 if (Files.isSymbolicLink(plugin))

435 throw new java.io.IOException("Plugin directory must not be a symbolic link");

436 plugin = plugin.toRealPath();

437 List<Path> entries;

438 try (var files = Files.walk(plugin)) {

439 entries = files.sorted().toList();

440 }

441 for (var entry : entries) {

442 if (Files.isSymbolicLink(entry)

443 || (!Files.isDirectory(entry, LinkOption.NOFOLLOW_LINKS)

444 && !Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)))

445 throw new java.io.IOException("Unsupported plugin entry: " + entry);

446 }

447 com.fasterxml.jackson.databind.JsonNode manifest;

448 try (var input =

449 Files.newInputStream(

450 plugin.resolve(".codex-plugin/plugin.json"), LinkOption.NOFOLLOW_LINKS)) {

451 manifest = new ObjectMapper().readTree(input);

452 }

453 var bytes = new ByteArrayOutputStream();

454 try (var archive = new ZipOutputStream(bytes)) {

455 for (var file : entries) {

456 if (Files.isDirectory(file, LinkOption.NOFOLLOW_LINKS)) continue;

457 archive.putNextEntry(

458 new ZipEntry(plugin.getParent().relativize(file).toString().replace('\\', '/')));

459 try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) {

460 input.transferTo(archive);

461 }

462 archive.closeEntry();

463 }

464 }

465 var session =

466 client

467 .beta()

468 .agents()

469 .sessions()

470 .create(

471 SessionCreateParams.builder()

472 .agent(SessionCreateParams.Agent.builder().model("gpt-6-astra").build())

473 .environment(

474 EnvironmentParam.OpenAIHosted.builder()

475 .addPlugin(

476 HostedPluginParam.builder()

477 .name(manifest.required("name").asText())

478 .description(manifest.required("description").asText())

479 .source(

480 InlineCapabilitySourceParam.builder()

481 .data(

482 Base64.getEncoder()

483 .encodeToString(bytes.toByteArray()))

484 .build())

485 .build())

486 .build())

487 .build());

488 return session.id();

489}

490```

491 

417```ruby492```ruby

418require "openai"493require "openai"

419require "json"494require "json"

guides/chatkit.md +91 −90

Details

52 52 

531. On your server, generate a client token.531. On your server, generate a client token.

54 54 

55 This example starts a service that creates a ChatKit session through the OpenAI API and returns the session's client secret:55 Create a ChatKit session through the OpenAI API and return its client secret. The Python and Ruby examples include an authenticated HTTP endpoint; the TypeScript, Go, and Java examples provide the session-creation helper for your endpoint:

56 

57 Server: create a ChatKit session

58 

59```typescript

60export default async function getChatKitSessionToken(deviceId: string) {

61 const apiKey = process.env.OPENAI_API_KEY;

62 if (!apiKey) {

63 throw new Error("OPENAI_API_KEY is required");

64 }

65 

66 const response = await fetch("https://api.openai.com/v1/chatkit/sessions", {

67 method: "POST",

68 headers: {

69 "Content-Type": "application/json",

70 "OpenAI-Beta": "chatkit_beta=v1",

71 Authorization: `Bearer ${apiKey}`,

72 },

73 body: JSON.stringify({

74 workflow: { id: "wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1" },

75 user: deviceId,

76 }),

77 });

78 

79 if (!response.ok) {

80 throw new Error(

81 `Failed to create a ChatKit session: ${response.status} ${await response.text()}`

82 );

83 }

84 

85 const { client_secret } = await response.json();

86 

87 if (!client_secret) {

88 throw new Error("ChatKit session response did not include client_secret");

89 }

90 

91 return client_secret;

92}

93```

56 94 

57```python95```python

58# Replace the illustrative IDs and URLs below with your own resource values.96# Replace the illustrative IDs and URLs below with your own resource values.


117 return {"client_secret": session.client_secret}155 return {"client_secret": session.client_secret}

118```156```

119 157 

158```go

159// Call after authenticating the request. Pass the user's stable ID from your

160// server-side authentication context, never a client-supplied device ID.

161func getChatKitSessionToken(ctx context.Context, client openai.Client, authenticatedUserID string) (string, error) {

162 // Replace this illustrative workflow ID with your published workflow.

163 session, err := client.Beta.ChatKit.Sessions.New(ctx, openai.BetaChatKitSessionNewParams{

164 User: authenticatedUserID,

165 Workflow: openai.ChatSessionWorkflowParam{

166 ID: "wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1",

167 },

168 })

169 if err != nil {

170 return "", err

171 }

172 return session.ClientSecret, nil

173}

174```

175 

176```java

177import com.openai.client.OpenAIClient;

178import com.openai.client.okhttp.OpenAIOkHttpClient;

179import com.openai.models.beta.chatkit.sessions.*;

180import com.openai.models.beta.chatkit.threads.ChatSessionWorkflowParam;

181 

182// Call after authenticating the request. Pass the user's stable ID from your

183// server-side authentication context, never a client-supplied device ID.

184static String getChatKitSessionToken(OpenAIClient client, String authenticatedUserId) {

185 // Replace this illustrative workflow ID with your published workflow.

186 return client

187 .beta()

188 .chatkit()

189 .sessions()

190 .create(

191 SessionCreateParams.builder()

192 .user(authenticatedUserId)

193 .workflow(

194 ChatSessionWorkflowParam.builder()

195 .id("wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1")

196 .build())

197 .build())

198 .clientSecret();

199}

200```

201 

120```ruby202```ruby

121# Replace the illustrative IDs and URLs below with your own resource values.203# Replace the illustrative IDs and URLs below with your own resource values.

122require "json"204require "json"


180 262 

181 For Ruby, install WEBrick with `gem install webrick`.263 For Ruby, install WEBrick with `gem install webrick`.

182 264 

183 Before starting the service, replace `wf_123` with your workflow ID and set `OPENAI_API_KEY` and `CHATKIT_AUTHENTICATED_USERS`. The latter value is a JSON map from your application's bearer tokens to stable user IDs. In production, replace this environment-backed map with your application's authentication or session lookup.265 For Go, run `go get github.com/openai/openai-go/v3@v3.105.0`. For Java, add the Maven dependency `com.openai:openai-java:4.105.0`.

184 266 

1852. In your server-side code, pass in your workflow ID and secret key to the session endpoint.267 Set `OPENAI_API_KEY` and use your workflow ID. For the Python and Ruby services, also set `CHATKIT_AUTHENTICATED_USERS`. The latter value is a JSON map from your application's bearer tokens to stable user IDs. In production, replace this environment-backed map with your application's authentication or session lookup.

268 

2692. Return the client secret from your server endpoint to your frontend.

186 270 

187 The client secret is the credential that your ChatKit frontend uses to open or refresh the chat session. You don't store it; you immediately hand it off to the ChatKit client library.271 The client secret is the credential that your ChatKit frontend uses to open or refresh the chat session. You don't store it; you immediately hand it off to the ChatKit client library.

188 272 

189 See the [chatkit-js repo](https://github.com/openai/chatkit-js) on GitHub.273 See the [chatkit-js repo](https://github.com/openai/chatkit-js) on GitHub.

190 274 

191 For Go, run `go get github.com/openai/openai-go/v3@v3.70.0`. For Java, add the Maven dependency `com.openai:openai-java:4.75.1`.2753. In your project directory, install the ChatKit React bindings:

192 

193 Create a ChatKit session token

194 

195```typescript

196export default async function getChatKitSessionToken(deviceId: string) {

197 const apiKey = process.env.OPENAI_API_KEY;

198 if (!apiKey) {

199 throw new Error("OPENAI_API_KEY is required");

200 }

201 

202 const response = await fetch("https://api.openai.com/v1/chatkit/sessions", {

203 method: "POST",

204 headers: {

205 "Content-Type": "application/json",

206 "OpenAI-Beta": "chatkit_beta=v1",

207 Authorization: `Bearer ${apiKey}`,

208 },

209 body: JSON.stringify({

210 workflow: { id: "wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1" },

211 user: deviceId,

212 }),

213 });

214 

215 if (!response.ok) {

216 throw new Error(

217 `Failed to create a ChatKit session: ${response.status} ${await response.text()}`

218 );

219 }

220 

221 const { client_secret } = await response.json();

222 

223 if (!client_secret) {

224 throw new Error("ChatKit session response did not include client_secret");

225 }

226 

227 return client_secret;

228}

229```

230 

231```go

232// Call after authenticating the request. Pass the user's stable ID from your

233// server-side authentication context, never a client-supplied device ID.

234func getChatKitSessionToken(ctx context.Context, client openai.Client, authenticatedUserID string) (string, error) {

235 // Replace this illustrative workflow ID with your published workflow.

236 session, err := client.Beta.ChatKit.Sessions.New(ctx, openai.BetaChatKitSessionNewParams{

237 User: authenticatedUserID,

238 Workflow: openai.ChatSessionWorkflowParam{

239 ID: "wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1",

240 },

241 })

242 if err != nil {

243 return "", err

244 }

245 return session.ClientSecret, nil

246}

247```

248 276 

249```java277 Install the ChatKit React bindings

250import com.openai.client.OpenAIClient;

251import com.openai.client.okhttp.OpenAIOkHttpClient;

252import com.openai.models.beta.chatkit.sessions.*;

253import com.openai.models.beta.chatkit.threads.ChatSessionWorkflowParam;

254 278 

255// Call after authenticating the request. Pass the user's stable ID from your279```bash

256// server-side authentication context, never a client-supplied device ID.280npm install @openai/chatkit-react

257static String getChatKitSessionToken(OpenAIClient client, String authenticatedUserId) {

258 // Replace this illustrative workflow ID with your published workflow.

259 return client

260 .beta()

261 .chatkit()

262 .sessions()

263 .create(

264 SessionCreateParams.builder()

265 .user(authenticatedUserId)

266 .workflow(

267 ChatSessionWorkflowParam.builder()

268 .id("wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1")

269 .build())

270 .build())

271 .clientSecret();

272}

273```281```

274 282 

275 283 

2763. In your project directory, install the ChatKit React bindings:

277 

278 ```bash

279 npm install @openai/chatkit-react

280 ```

281 

282 

2834. Add the ChatKit JS script to your page. Drop this snippet into your page’s `<head>` or wherever you load scripts, and the browser will fetch and run ChatKit for you.2844. Add the ChatKit JS script to your page. Drop this snippet into your page’s `<head>` or wherever you load scripts, and the browser will fetch and run ChatKit for you.

284 285 

285 index.html286 index.html

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 13Python server SDK: attach a widget action

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 14 

34```python15```python

35button = Button(16button = Button(


44 25 

45Actions can also be sent imperatively by your frontend with `sendCustomAction()`. This is probably most useful when you need ChatKit to respond to interaction happening outside ChatKit, but it can also be used to chain actions when you need to respond on both the client and the server (more on that below).26Actions can also be sent imperatively by your frontend with `sendCustomAction()`. This is probably most useful when you need ChatKit to respond to interaction happening outside ChatKit, but it can also be used to chain actions when you need to respond on both the client and the server (more on that below).

46 27 

28Client: send an action to the server

29 

47```typescript30```typescript

48await chatKit.sendCustomAction({31await chatKit.sendCustomAction({

49 type: "example",32 type: "example",


58 41 

59By default, actions are sent to your server. You can handle actions on your server by implementing the `action` method on `ChatKitServer`.42By default, actions are sent to your server. You can handle actions on your server by implementing the `action` method on `ChatKitServer`.

60 43 

44Python server SDK: handle an action

45 

61```python46```python

62class MyChatKitServer(ChatKitServer[RequestContext]):47class MyChatKitServer(ChatKitServer[RequestContext]):

63 async def action(48 async def action(


96 81 

97Sometimes you’ll want to handle actions in your client integration. To do that you need to specify that the action should be sent to your client-side action handler by adding `handler="client"` to the `ActionConfig`.82Sometimes you’ll want to handle actions in your client integration. To do that you need to specify that the action should be sent to your client-side action handler by adding `handler="client"` to the `ActionConfig`.

98 83 

84Python server SDK: configure a client-handled action

85 

99```python86```python

100button = Button(87button = Button(

101 label="Example",88 label="Example",


106 93 

107Then, when the action is triggered, it will then be passed to a callback that you provide when instantiating ChatKit.94Then, when the action is triggered, it will then be passed to a callback that you provide when instantiating ChatKit.

108 95 

96Client: handle the action and notify the server

97 

109```typescript98```typescript

110async function handleWidgetAction(action: { type: string }) {99async function handleWidgetAction(action: { type: string }) {

111 if (action.type === "example") {100 if (action.type === "example") {


131 120 

132By default `Action` and `ActionConfig` are not strongly typed. However, we do expose a `create` helper on `Action` that generates `ActionConfig`s from a set of strongly-typed actions.121By default `Action` and `ActionConfig` are not strongly typed. However, we do expose a `create` helper on `Action` that generates `ActionConfig`s from a set of strongly-typed actions.

133 122 

123Python server SDK: define and validate typed actions

124 

134```python125```python

135class ExamplePayload(BaseModel):126class ExamplePayload(BaseModel):

136 id: int127 id: int


193- `Select(name="title")` → `action.payload.title`184- `Select(name="title")` → `action.payload.title`

194- `Select(name="todo.title")` → `action.payload.todo.title`185- `Select(name="todo.title")` → `action.payload.todo.title`

195 186 

187Python server SDK: define a form and handle submission

188 

196```python189```python

197form = Form(190form = Form(

198 direction="col",191 direction="col",


262 255 

263Use `ActionConfig.loadingBehavior` to control how actions trigger different loading states in a widget.256Use `ActionConfig.loadingBehavior` to control how actions trigger different loading states in a widget.

264 257 

258Python server SDK: configure widget loading behavior

259 

265```python260```python

266button = Button(261button = Button(

267 label="This may take a while...",262 label="This may take a while...",

Details

57 57 

58For all theming options, see the [API reference](https://openai.github.io/chatkit-js/api/openai/chatkit/type-aliases/themeoption/).58For all theming options, see the [API reference](https://openai.github.io/chatkit-js/api/openai/chatkit/type-aliases/themeoption/).

59 59 

60Customize the ChatKit theme

61 

60```typescript62```typescript

61import type { ChatKitOptions } from "@openai/chatkit";63import type { ChatKitOptions } from "@openai/chatkit";

62 64 


81 83 

82Let users know what to ask or guide their first input by changing the composer’s placeholder text.84Let users know what to ask or guide their first input by changing the composer’s placeholder text.

83 85 

86Set the greeting and placeholder text

87 

84```typescript88```typescript

85const options: Partial<ChatKitOptions> = {89const options: Partial<ChatKitOptions> = {

86 composer: {90 composer: {


97 101 

98Guide users on what to ask or do by suggesting prompt ideas when starting a conversation.102Guide users on what to ask or do by suggesting prompt ideas when starting a conversation.

99 103 

104Add starter prompts

105 

100```typescript106```typescript

101const options: Partial<ChatKitOptions> = {107const options: Partial<ChatKitOptions> = {

102 startScreen: {108 startScreen: {


122 128 

123Custom header buttons help you add navigation, context, or actions relevant to your integration.129Custom header buttons help you add navigation, context, or actions relevant to your integration.

124 130 

131Add custom header buttons

132 

125```typescript133```typescript

126const options: Partial<ChatKitOptions> = {134const options: Partial<ChatKitOptions> = {

127 header: {135 header: {


146 154 

147You can also control the number, size, and types of files that users can attach to messages.155You can also control the number, size, and types of files that users can attach to messages.

148 156 

157Enable file attachments

158 

149```typescript159```typescript

150const options: Partial<ChatKitOptions> = {160const options: Partial<ChatKitOptions> = {

151 composer: {161 composer: {


167- Use `onTagSearch` to return a list of entities based on the input query.177- Use `onTagSearch` to return a list of entities based on the input query.

168- Use `onClick` to handle the click event of an entity.178- Use `onClick` to handle the click event of an entity.

169 179 

180Configure entity tags

181 

170```typescript182```typescript

171const options: Partial<ChatKitOptions> = {183const options: Partial<ChatKitOptions> = {

172 entities: {184 entities: {


205 217 

206 218 

207 219 

220Show entity previews

221 

208```typescript222```typescript

209const options: Partial<ChatKitOptions> = {223const options: Partial<ChatKitOptions> = {

210 entities: {224 entities: {


230Enhance productivity by letting users trigger app-specific actions from the composer bar. The selected tool244Enhance productivity by letting users trigger app-specific actions from the composer bar. The selected tool

231will be sent to the model as a tool preference.245will be sent to the model as a tool preference.

232 246 

247Add composer tools

248 

233```typescript249```typescript

234const options: Partial<ChatKitOptions> = {250const options: Partial<ChatKitOptions> = {

235 composer: {251 composer: {


250 266 

251Disable major UI regions and features if you need more customization over the options available in the header and want to implement your own instead. Disabling history can be useful when the concept of threads and history doesn't make sense for your use case—e.g., in a support chatbot.267Disable major UI regions and features if you need more customization over the options available in the header and want to implement your own instead. Disabling history can be useful when the concept of threads and history doesn't make sense for your use case—e.g., in a support chatbot.

252 268 

269Show or hide UI regions

270 

253```typescript271```typescript

254const options: Partial<ChatKitOptions> = {272const options: Partial<ChatKitOptions> = {

255 history: { enabled: false },273 history: { enabled: false },


262 280 

263Override the default locale if you have an app-wide language setting. By default, the locale is set to the browser's locale.281Override the default locale if you have an app-wide language setting. By default, the locale is set to the browser's locale.

264 282 

283Set the locale

284 

265```typescript285```typescript

266const options: Partial<ChatKitOptions> = {286const options: Partial<ChatKitOptions> = {

267 locale: "de-DE",287 locale: "de-DE",

Details

22 22 

23Capture widget events with the `onAction` callback from `WidgetsOption` or equivalent React hook. Forward the action payload to your backend to handle actions.23Capture widget events with the `onAction` callback from `WidgetsOption` or equivalent React hook. Forward the action payload to your backend to handle actions.

24 24 

25Client: forward a widget action to the server

26 

25```typescript27```typescript

26chatkit.setOptions({28chatkit.setOptions({

27 widgets: {29 widgets: {

Details

22 22 

23### 1. Install the server package23### 1. Install the server package

24 24 

25Server: install the Python ChatKit SDK

26 

25```bash27```bash

26pip install openai-chatkit28pip install openai-chatkit

27```29```


32user message or client tool output arrives. Helpers like `stream_agent_response` connect35user message or client tool output arrives. Helpers like `stream_agent_response` connect

33the server to the Agents SDK.36the server to the Agents SDK.

34 37 

38Python server SDK: implement a ChatKit server

39 

35```python40```python

36class MyChatKitServer(ChatKitServer[RequestContext]):41class MyChatKitServer(ChatKitServer[RequestContext]):

37 async def respond(42 async def respond(


68Use your framework of choice to forward HTTP requests to the server instance. For73Use your framework of choice to forward HTTP requests to the server instance. For

69example, with FastAPI:74example, with FastAPI:

70 75 

76Python server SDK: expose the endpoint with FastAPI

77 

71```python78```python

72from fastapi import FastAPI, Request, Response79from fastapi import FastAPI, Request, Response

73from fastapi.responses import StreamingResponse80from fastapi.responses import StreamingResponse


105Client tools must be registered both in the client options and on your agent. Use112Client tools must be registered both in the client options and on your agent. Use

106`ctx.context.client_tool_call` to enqueue a call from an Agents SDK tool.113`ctx.context.client_tool_call` to enqueue a call from an Agents SDK tool.

107 114 

115Python server SDK: trigger a client tool

116 

108```python117```python

109@function_tool(description_override="Add an item to the user's todo list.")118@function_tool(description_override="Add an item to the user's todo list.")

110async def add_to_todo_list(ctx: RunContextWrapper[AgentContext], item: str) -> None:119async def add_to_todo_list(ctx: RunContextWrapper[AgentContext], item: str) -> None:


146text blocks, lists, and other layouts. The helper `stream_widget` can render a widget155text blocks, lists, and other layouts. The helper `stream_widget` can render a widget

147immediately or stream updates as they arrive.156immediately or stream updates as they arrive.

148 157 

158Python server SDK: stream an interactive widget

159 

149```python160```python

150async def respond(161async def respond(

151 self,162 self,


206 217 

207ChatKit emits `CustomEvent` instances from the Web Component. Listen for lifecycle events and read payload data from `event.detail`:218ChatKit emits `CustomEvent` instances from the Web Component. Listen for lifecycle events and read payload data from `event.detail`:

208 219 

220Client: listen for ChatKit events

221 

209```typescript222```typescript

210chatkit.addEventListener("chatkit.error", (event) => {223chatkit.addEventListener("chatkit.error", (event) => {

211 console.error(event.detail.error);224 console.error(event.detail.error);

Details

275}275}

276```276```

277 277 

278```java

279import com.fasterxml.jackson.databind.ObjectMapper;

280import java.util.List;

281import java.util.Map;

282 

283// Replace the illustrative voice ID with your own custom voice.

284var config =

285 Map.of(

286 "session",

287 Map.of(

288 "type",

289 "realtime",

290 "model",

291 "gpt-realtime-2.1-mini",

292 "instructions",

293 "Read the user's text aloud without adding commentary.",

294 "output_modalities",

295 List.of("audio"),

296 "audio",

297 Map.of("output", Map.of("voice", Map.of("id", "voice_123abc")))));

298System.out.println(new ObjectMapper().writeValueAsString(config));

299```

300 

278```ruby301```ruby

279# Replace the illustrative IDs and URLs below with your own resource values.302# Replace the illustrative IDs and URLs below with your own resource values.

280require "json"303require "json"

Details

170 170 

171## Use cases171## Use cases

172 172 

173The Java examples use `com.openai:openai-java:4.105.0`, `org.apache.commons:commons-csv:1.14.1`, and `com.fasterxml.jackson.core:jackson-databind:2.18.11`. For token counting, add `com.knuddels:jtokkit:1.1.0`. For visualization, clustering, classification, and regression, also add `com.github.haifengl:smile-core:3.1.1`; the examples use that version’s API. Keep imports at the top of your file and helper methods and records at class scope. Place the statements for each step inside a `main` method that declares checked exceptions. Use the same working directory for the CSV files shared by the steps.

174 

173Here we show some representative use cases, using the [Amazon fine-food reviews dataset](https://www.kaggle.com/snap/amazon-fine-food-reviews).175Here we show some representative use cases, using the [Amazon fine-food reviews dataset](https://www.kaggle.com/snap/amazon-fine-food-reviews).

174 176 

175### Obtaining the embeddings177### Obtaining the embeddings


212 214 

213 215 

214 216 

217 

218 

219 

220Save the review dataset as `data/fine_food_reviews_1k.csv`. Keep `Summary`, `Text`, `Score`, `UserId`, and `ProductId`; the Java producer preserves these columns and adds `combined` and `ada_embedding`. Use at least four labeled reviews for the visualization. The visualization sets t-SNE perplexity based on the dataset size, with a maximum of 15, and writes `local-plot.png`.

221 

222 

223 

224 

215Create review embeddings225Create review embeddings

216 226 

217```typescript227```typescript


373```383```

374 384 

375```java385```java

386import com.fasterxml.jackson.databind.ObjectMapper;

376import com.openai.client.OpenAIClient;387import com.openai.client.OpenAIClient;

377import com.openai.client.okhttp.OpenAIOkHttpClient;388import com.openai.client.okhttp.OpenAIOkHttpClient;

378import com.openai.models.embeddings.EmbeddingCreateParams;389import com.openai.models.embeddings.EmbeddingCreateParams;

379import java.io.IOException;390import java.nio.file.*;

380import java.nio.file.Files;391import java.util.*;

381import java.nio.file.Path;392import org.apache.commons.csv.*;

382import java.util.List;

383 393 

384static String csvField(String value) {

385 return "\"" + value.replace("\"", "\"\"") + "\"";

386}

387 

388List<String> reviews = List.of("A rich cup of coffee.", "A bright herbal tea.");

389Path output = Path.of("output", "embedded_1k_reviews.csv");394Path output = Path.of("output", "embedded_1k_reviews.csv");

390Files.createDirectories(output.getParent());395Files.createDirectories(output.getParent());

391try (var writer = Files.newBufferedWriter(output)) {396try (var reviews =

392 writer.write("combined,ada_embedding\n");397 CSVFormat.DEFAULT

393 for (String review : reviews) {398 .builder()

399 .setHeader()

400 .setSkipHeaderRecord(true)

401 .get()

402 .parse(Files.newBufferedReader(Path.of("data/fine_food_reviews_1k.csv")))) {

403 var headers = new ArrayList<>(reviews.getHeaderNames());

404 headers.add("combined");

405 headers.add("ada_embedding");

406 try (var writer =

407 CSVFormat.DEFAULT

408 .builder()

409 .setHeader(headers.toArray(String[]::new))

410 .get()

411 .print(Files.newBufferedWriter(output))) {

412 for (var review : reviews) {

413 String combined = (review.get("Summary") + " " + review.get("Text")).replace("\n", " ");

394 var embedding =414 var embedding =

395 client415 client

396 .embeddings()416 .embeddings()

397 .create(417 .create(

398 EmbeddingCreateParams.builder()418 EmbeddingCreateParams.builder()

399 .model("text-embedding-3-small")419 .model("text-embedding-3-small")

400 .inputOfArrayOfStrings(List.of(review.replace("\n", " ")))420 .inputOfArrayOfStrings(List.of(combined))

401 .build())421 .build())

402 .data()422 .data()

403 .get(0)423 .get(0)

404 .embedding();424 .embedding();

405 writer.write(csvField(review) + "," + csvField(embedding.toString()) + "\n");425 var values = new ArrayList<String>();

426 for (String header : reviews.getHeaderNames()) values.add(review.get(header));

427 values.add(combined);

428 values.add(new ObjectMapper().writeValueAsString(embedding));

429 writer.printRecord(values);

430 }

406 }431 }

407}432}

408System.out.println(output);433System.out.println(output);


622}647}

623```648```

624 649 

650```java

651import com.fasterxml.jackson.databind.ObjectMapper;

652import java.nio.file.*;

653import java.util.*;

654import org.apache.commons.csv.*;

655 

656var vectors = new ArrayList<List<Double>>();

657try (var csv =

658 CSVFormat.DEFAULT

659 .builder()

660 .setHeader()

661 .setSkipHeaderRecord(true)

662 .get()

663 .parse(Files.newBufferedReader(Path.of("output/embedded_1k_reviews.csv")))) {

664 for (var row : csv) {

665 List<Double> vector =

666 new ObjectMapper()

667 .readValue(

668 row.get("ada_embedding"),

669 new com.fasterxml.jackson.core.type.TypeReference<List<Double>>() {});

670 if (vector.stream().anyMatch(v -> v == null || !Double.isFinite(v)))

671 throw new IllegalArgumentException("Invalid embedding");

672 vectors.add(vector);

673 }

674}

675System.out.println(vectors.get(0));

676```

677 

625```ruby678```ruby

626# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.679# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.

627require "csv"680require "csv"


806 859 

807 860 

808 861 

809In many common cases, the model is not trained on data which contains key facts and information you want to make accessible when generating responses to a user query. One way of solving this, as shown below, is to put additional information into the context window of the model. This is effective in many use cases but leads to higher token costs. In this notebook, we explore the tradeoff between this approach and embeddings bases search.862The model may not have learned the facts you want it to use when responding to a user query. One way of solving this, as shown below, is to put additional information into the context window of the model. This is effective in many use cases but leads to higher token costs. In this notebook, we explore the tradeoff between this approach and embedding-based search.

810 863 

811Answer a question with retrieved context864Answer a question with retrieved context

812 865 


2065}2118}

2066```2119```

2067 2120 

2121```java

2122import com.fasterxml.jackson.databind.ObjectMapper;

2123import java.nio.file.*;

2124import java.util.*;

2125import org.apache.commons.csv.*;

2126import smile.manifold.TSNE;

2127 

2128var vectors = new ArrayList<double[]>();

2129var colors = new ArrayList<Integer>();

2130try (var csv =

2131 CSVFormat.DEFAULT

2132 .builder()

2133 .setHeader()

2134 .setSkipHeaderRecord(true)

2135 .get()

2136 .parse(Files.newBufferedReader(Path.of("output/embedded_1k_reviews.csv")))) {

2137 for (var row : csv) {

2138 vectors.add(new ObjectMapper().readValue(row.get("ada_embedding"), double[].class));

2139 colors.add(Integer.parseInt(row.get("Score")) - 1);

2140 }

2141}

2142if (vectors.size() < 4)

2143 throw new IllegalArgumentException("Provide at least four labeled reviews.");

2144smile.math.MathEx.setSeed(42);

2145var tsne =

2146 new TSNE(

2147 vectors.toArray(double[][]::new), 2, Math.min(15, (vectors.size() - 1) / 3), 200, 1000);

2148var points = tsne.coordinates;

2149var image =

2150 new java.awt.image.BufferedImage(640, 480, java.awt.image.BufferedImage.TYPE_INT_RGB);

2151var graphics = image.createGraphics();

2152var plotted = new ArrayList<double[]>();

2153try {

2154 graphics.setColor(java.awt.Color.WHITE);

2155 graphics.fillRect(0, 0, 640, 480);

2156 var palette =

2157 new java.awt.Color[] {

2158 java.awt.Color.RED,

2159 java.awt.Color.ORANGE,

2160 java.awt.Color.YELLOW,

2161 java.awt.Color.CYAN,

2162 java.awt.Color.GREEN

2163 };

2164 double minX = Arrays.stream(points).mapToDouble(p -> p[0]).min().orElseThrow(),

2165 maxX = Arrays.stream(points).mapToDouble(p -> p[0]).max().orElseThrow();

2166 double minY = Arrays.stream(points).mapToDouble(p -> p[1]).min().orElseThrow(),

2167 maxY = Arrays.stream(points).mapToDouble(p -> p[1]).max().orElseThrow();

2168 for (int i = 0; i < points.length; i++) {

2169 var point = points[i];

2170 int x = 20 + (int) (600 * (point[0] - minX) / Math.max(1e-12, maxX - minX));

2171 int y = 20 + (int) (440 * (point[1] - minY) / Math.max(1e-12, maxY - minY));

2172 graphics.setColor(palette[colors.get(i)]);

2173 graphics.fillOval(x - 3, y - 3, 6, 6);

2174 plotted.add(point);

2175 }

2176} finally {

2177 graphics.dispose();

2178}

2179javax.imageio.ImageIO.write(image, "png", Path.of("local-plot.png").toFile());

2180```

2181 

2068```ruby2182```ruby

2069require "csv"2183require "csv"

2070require "json"2184require "json"


2118 2232 

2119This code splits the data into a training set and a testing set, which will be used by the following two use cases, namely regression and classification.2233This code splits the data into a training set and a testing set, which will be used by the following two use cases, namely regression and classification.

2120 2234 

2235 

2236 

2237 

2238The Java split takes a `double[][] vectors` array and a matching `int[] scores` array from your labeled reviews. It returns primitive arrays that both model examples can use; the regression example converts the integer ratings to continuous targets.

2239 

2240 

2241 

2242 

2121Split the dataset for training and testing2243Split the dataset for training and testing

2122 2244 

2123```typescript2245```typescript


2290}2412}

2291```2413```

2292 2414 

2415```java

2416import com.fasterxml.jackson.databind.ObjectMapper;

2417import java.nio.file.Path;

2418import java.util.*;

2419 

2420// Shuffle paired examples once so each vector stays aligned with its score.

2421var indices = new ArrayList<Integer>();

2422for (int i = 0; i < vectors.length; i++) indices.add(i);

2423Collections.shuffle(indices, new Random(42));

2424int testSize = (int) Math.ceil(vectors.length * 0.2);

2425var testIndices = indices.subList(0, testSize);

2426var trainIndices = indices.subList(testSize, indices.size());

2427var xTrain = trainIndices.stream().map(i -> vectors[i]).toArray(double[][]::new);

2428var xTest = testIndices.stream().map(i -> vectors[i]).toArray(double[][]::new);

2429var yTrain = trainIndices.stream().mapToInt(i -> scores[i]).toArray();

2430var yTest = testIndices.stream().mapToInt(i -> scores[i]).toArray();

2431System.out.println("Training examples: " + xTrain.length);

2432System.out.println("Test examples: " + xTest.length);

2433 

2434 

2435```

2436 

2293```ruby2437```ruby

2294vectors = rows.map { |row| row.fetch("ada_embedding") }2438vectors = rows.map { |row| row.fetch("ada_embedding") }

2295scores = rows.map { |row| Integer(row.fetch("Score")) }2439scores = rows.map { |row| Integer(row.fetch("Score")) }


2512}2656}

2513```2657```

2514 2658 

2659```java

2660import com.fasterxml.jackson.databind.ObjectMapper;

2661import java.nio.file.*;

2662import java.util.*;

2663import org.apache.commons.csv.*;

2664import smile.data.DataFrame;

2665import smile.data.formula.Formula;

2666import smile.data.vector.DoubleVector;

2667import smile.regression.RandomForest;

2668 

2669smile.math.MathEx.setSeed(42);

2670String[] columns =

2671 java.util.stream.IntStream.range(0, xTrain[0].length)

2672 .mapToObj(index -> "embedding_" + index)

2673 .toArray(String[]::new);

2674var training =

2675 DataFrame.of(xTrain, columns)

2676 .merge(DoubleVector.of("score", Arrays.stream(yTrain).asDoubleStream().toArray()));

2677var options = new Properties();

2678options.setProperty("smile.random_forest.trees", "100");

2679options.setProperty("smile.random_forest.node_size", "1");

2680options.setProperty("smile.random_forest.max_nodes", "4");

2681var forest = RandomForest.fit(Formula.lhs("score"), training, options);

2682var test = DataFrame.of(xTest, columns);

2683var predictions = new ArrayList<Number>();

2684for (int i = 0; i < test.nrow(); i++) predictions.add(forest.predict(test.get(i)));

2685System.out.println(predictions);

2686```

2687 

2515```ruby2688```ruby

2516require "rumale/ensemble"2689require "rumale/ensemble"

2517 2690 


2765}2938}

2766```2939```

2767 2940 

2941```java

2942import com.fasterxml.jackson.databind.ObjectMapper;

2943import java.nio.file.*;

2944import java.util.*;

2945import org.apache.commons.csv.*;

2946import smile.classification.RandomForest;

2947import smile.data.DataFrame;

2948import smile.data.formula.Formula;

2949import smile.data.vector.IntVector;

2950 

2951smile.math.MathEx.setSeed(42);

2952String[] columns =

2953 java.util.stream.IntStream.range(0, xTrain[0].length)

2954 .mapToObj(index -> "embedding_" + index)

2955 .toArray(String[]::new);

2956var training = DataFrame.of(xTrain, columns).merge(IntVector.of("score", yTrain));

2957var options = new Properties();

2958options.setProperty("smile.random_forest.trees", "100");

2959options.setProperty("smile.random_forest.node_size", "1");

2960options.setProperty("smile.random_forest.max_nodes", "4");

2961var forest = RandomForest.fit(Formula.lhs("score"), training, options);

2962var test = DataFrame.of(xTest, columns);

2963var predictions = new ArrayList<Number>();

2964for (int i = 0; i < test.nrow(); i++) predictions.add(forest.predict(test.get(i)));

2965System.out.println(predictions);

2966```

2967 

2768```ruby2968```ruby

2769require "rumale/ensemble"2969require "rumale/ensemble"

2770 2970 


3202}3402}

3203```3403```

3204 3404 

3405```java

3406import com.fasterxml.jackson.databind.ObjectMapper;

3407import java.nio.file.*;

3408import java.util.*;

3409import org.apache.commons.csv.*;

3410 

3411// vectors is a double[][] with one embedding per review.

3412// userIds and productIds are String[] columns in the same review-row order.

3413var users = averageBy(userIds, vectors);

3414var products = averageBy(productIds, vectors);

3415System.out.println(new ObjectMapper().writeValueAsString(users));

3416System.out.println(new ObjectMapper().writeValueAsString(products));

3417 

3418static Map<String, double[]> averageBy(String[] groups, double[][] vectors) {

3419 var sums = new LinkedHashMap<String, double[]>();

3420 var counts = new HashMap<String, Integer>();

3421 for (int i = 0; i < vectors.length; i++) {

3422 var sum = sums.computeIfAbsent(groups[i], key -> new double[vectors[0].length]);

3423 if (sum.length != vectors[i].length)

3424 throw new IllegalArgumentException("Embedding dimensions differ");

3425 for (int j = 0; j < sum.length; j++) sum[j] += vectors[i][j];

3426 counts.merge(groups[i], 1, Integer::sum);

3427 }

3428 sums.forEach(

3429 (group, sum) -> {

3430 for (int j = 0; j < sum.length; j++) sum[j] /= counts.get(group);

3431 });

3432 return sums;

3433}

3434```

3435 

3205```ruby3436```ruby

3206vectors = rows.map { |row| row.fetch("ada_embedding") }3437vectors = rows.map { |row| row.fetch("ada_embedding") }

3207user_ids = rows.map { |row| row.fetch("UserId") }3438user_ids = rows.map { |row| row.fetch("UserId") }


3480}3711}

3481```3712```

3482 3713 

3714```java

3715import com.fasterxml.jackson.databind.ObjectMapper;

3716import java.nio.file.*;

3717import java.util.*;

3718import org.apache.commons.csv.*;

3719import smile.clustering.KMeans;

3720 

3721// matrix is a double[][] containing at least four review embeddings.

3722// Each row must have the same number of dimensions.

3723smile.math.MathEx.setSeed(42);

3724var clusters = KMeans.fit(matrix, 4);

3725System.out.println(Arrays.toString(clusters.y));

3726```

3727 

3483```ruby3728```ruby

3484require "rumale/clustering"3729require "rumale/clustering"

3485 3730 


3559}3804}

3560```3805```

3561 3806 

3807```java

3808import com.fasterxml.jackson.databind.ObjectMapper;

3809import java.nio.file.*;

3810import java.util.*;

3811import org.apache.commons.csv.*;

3812 

3813System.out.println(ENCODING.countTokens("tiktoken is great!"));

3814 

3815static final com.knuddels.jtokkit.api.Encoding ENCODING =

3816 com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry()

3817 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

3818```

3819 

3562```ruby3820```ruby

3563require "tiktoken_ruby"3821require "tiktoken_ruby"

3564 3822 

Details

448}448}

449```449```

450 450 

451```java

452import com.openai.client.okhttp.OpenAIOkHttpClient;

453import com.openai.core.JsonValue;

454import com.openai.models.finetuning.alpha.graders.*;

455import com.openai.models.graders.gradermodels.PythonGrader;

456import java.nio.file.Files;

457import java.nio.file.Path;

458import java.util.Map;

459 

460// Use your configured OpenAIClient named client.

461// Save the Python grading function as grader.py before running this example.

462var grader =

463 PythonGrader.builder()

464 .name("word_overlap")

465 .source(Files.readString(Path.of("grader.py")))

466 .build();

467System.out.println(

468 client

469 .fineTuning()

470 .alpha()

471 .graders()

472 .validate(GraderValidateParams.builder().grader(grader).build()));

473System.out.println(

474 client

475 .fineTuning()

476 .alpha()

477 .graders()

478 .run(

479 GraderRunParams.builder()

480 .grader(grader)

481 .item(JsonValue.from(Map.of("reference_answer", "fuzzy wuzzy had no hair")))

482 .modelSample("fuzzy wuzzy was a bear")

483 .build()));

484```

485 

451```ruby486```ruby

452require "openai"487require "openai"

453 488 

Details

2722}2722}

2723```2723```

2724 2724 

2725```java

2726import com.openai.client.okhttp.OpenAIOkHttpClient;

2727import com.openai.core.MultipartField;

2728import com.openai.models.images.*;

2729import java.io.InputStream;

2730import java.nio.file.Files;

2731import java.nio.file.Path;

2732import java.util.Base64;

2733 

2734// Use your configured OpenAIClient named client.

2735try (var image = Files.newInputStream(Path.of("kitchen.webp"));

2736 var markup = Files.newInputStream(Path.of("markup-vase-overlay-gpt-image-2-6.png"))) {

2737 var result =

2738 client

2739 .images()

2740 .edit(

2741 ImageEditParams.builder()

2742 .model("gpt-image-2.6-flare")

2743 .image(

2744 MultipartField.<ImageEditParams.Image>builder()

2745 .value(ImageEditParams.Image.ofInputStream(image))

2746 .filename("kitchen.webp")

2747 .contentType("image/webp")

2748 .build())

2749 .markup(

2750 MultipartField.<InputStream>builder()

2751 .value(markup)

2752 .filename("markup-vase-overlay-gpt-image-2-6.png")

2753 .contentType("image/png")

2754 .build())

2755 .quality(ImageEditParams.Quality.MEDIUM)

2756 .prompt(

2757 "Recolor the striped vase inside the red circle to solid cobalt blue ceramic. Keep its shape, the dried stems, and the rest of the kitchen unchanged. Remove the red circle from the finished photo.")

2758 .build());

2759 Files.write(

2760 Path.of("vase.png"),

2761 Base64.getDecoder().decode(result.data().orElseThrow().get(0).b64Json().orElseThrow()));

2762}

2763```

2764 

2725```ruby2765```ruby

2726require "openai"2766require "openai"

2727require "pathname"2767require "pathname"


3437}3477}

3438```3478```

3439 3479 

3480```java

3481import java.awt.image.BufferedImage;

3482import java.io.File;

3483import javax.imageio.ImageIO;

3484 

3485var mask = ImageIO.read(new File("mask.png"));

3486var rgba = new BufferedImage(mask.getWidth(), mask.getHeight(), BufferedImage.TYPE_INT_ARGB);

3487for (int y = 0; y < mask.getHeight(); y++) {

3488 for (int x = 0; x < mask.getWidth(); x++) {

3489 int gray;

3490 if (mask.getColorModel().getColorSpace().getType() == java.awt.color.ColorSpace.TYPE_GRAY

3491 && mask.getRaster().getNumBands() == 1) {

3492 // Preserve grayscale intensities while normalizing their bit depth.

3493 long maximum = (1L << mask.getSampleModel().getSampleSize(0)) - 1;

3494 gray = (int) Math.round(mask.getRaster().getSampleDouble(x, y, 0) * 255 / maximum);

3495 } else {

3496 // Indexed PNG samples are palette indices, not grayscale intensities.

3497 int rgb = mask.getRGB(x, y);

3498 gray =

3499 (299 * ((rgb >>> 16) & 255) + 587 * ((rgb >>> 8) & 255) + 114 * (rgb & 255) + 500)

3500 / 1000;

3501 }

3502 rgba.setRGB(x, y, (gray << 24) | (gray << 16) | (gray << 8) | gray);

3503 }

3504}

3505ImageIO.write(rgba, "png", new File("mask_alpha.png"));

3506```

3507 

3440```ruby3508```ruby

3441require "chunky_png"3509require "chunky_png"

3442 3510 

Details

1533}1533}

1534```1534```

1535 1535 

1536```java

1537import com.openai.client.okhttp.OpenAIOkHttpClient;

1538import com.openai.core.MultipartField;

1539import com.openai.models.images.*;

1540import java.nio.file.Files;

1541import java.nio.file.Path;

1542import java.util.Base64;

1543 

1544// Use your configured OpenAIClient named client.

1545String model = args[0];

1546String suffix = ".png";

1547String logoPrompt =

1548 "Create an original, non-infringing logo for a company called Field & Flour, a local bakery.\nThe logo should feel warm, simple, and timeless. Use clean, vector-like shapes, a strong silhouette, and balanced negative space.\nFavor simplicity over detail so it reads clearly at small and large sizes. Flat design, minimal strokes, no gradients unless essential.\nFully transparent background. Deliver a single centered logo with generous padding, clean alpha edges, and no solid backdrop, scenery, checkerboard, or watermark.";

1549var logos =

1550 client

1551 .images()

1552 .generate(

1553 ImageGenerateParams.builder()

1554 .model(model)

1555 .prompt(logoPrompt)

1556 .size(ImageGenerateParams.Size._1024X1536)

1557 .quality(ImageGenerateParams.Quality.MEDIUM)

1558 .background(ImageGenerateParams.Background.TRANSPARENT)

1559 .outputFormat(ImageGenerateParams.OutputFormat.PNG)

1560 .n(4)

1561 .build());

1562var images = logos.data().orElseThrow();

1563for (int i = 0; i < images.size(); i++) {

1564 Files.write(

1565 Path.of("logo-generation-" + (i + 1) + suffix),

1566 Base64.getDecoder().decode(images.get(i).b64Json().orElseThrow()));

1567}

1568String cutoutPrompt =

1569 "Extract the product from the input image and isolate it on a fully transparent background.\nOutput: centered product, crisp silhouette, no halos/fringing.\nPreserve product geometry and label legibility exactly.\nAdd only light polishing. Do not add a solid backdrop, checkerboard, scenery, or shadow.\nDo not restyle the product; remove the background and preserve clean alpha transparency.";

1570try (var image = Files.newInputStream(Path.of("input_images/shampoo.webp"))) {

1571 var cutout =

1572 client

1573 .images()

1574 .edit(

1575 ImageEditParams.builder()

1576 .model(model)

1577 .prompt(cutoutPrompt)

1578 .image(

1579 MultipartField.<ImageEditParams.Image>builder()

1580 .value(ImageEditParams.Image.ofInputStream(image))

1581 .filename("shampoo.webp")

1582 .contentType("image/webp")

1583 .build())

1584 .size(ImageEditParams.Size._1024X1536)

1585 .quality(ImageEditParams.Quality.MEDIUM)

1586 .background(ImageEditParams.Background.TRANSPARENT)

1587 .outputFormat(ImageEditParams.OutputFormat.PNG)

1588 .build());

1589 Files.write(

1590 Path.of("extract-product" + suffix),

1591 Base64.getDecoder().decode(cutout.data().orElseThrow().get(0).b64Json().orElseThrow()));

1592}

1593```

1594 

1536```ruby1595```ruby

1537require "base64"1596require "base64"

1538require "openai"1597require "openai"


3127}3186}

3128```3187```

3129 3188 

3189```java

3190import com.openai.client.okhttp.OpenAIOkHttpClient;

3191import com.openai.core.MultipartField;

3192import com.openai.models.images.*;

3193import java.nio.file.Files;

3194import java.nio.file.Path;

3195import java.util.Base64;

3196 

3197// Use your configured OpenAIClient named client.

3198String model = "gpt-image-2.5-sunburst";

3199String suffix = "-gpt-image-2.5-sunburst.png";

3200String logoPrompt =

3201 "Create an original, non-infringing logo for a company called Field & Flour, a local bakery.\nThe logo should feel warm, simple, and timeless. Use clean, vector-like shapes, a strong silhouette, and balanced negative space.\nFavor simplicity over detail so it reads clearly at small and large sizes. Flat design, minimal strokes, no gradients unless essential.\nFully transparent background. Deliver a single centered logo with generous padding, clean alpha edges, and no solid backdrop, scenery, checkerboard, or watermark.";

3202var logos =

3203 client

3204 .images()

3205 .generate(

3206 ImageGenerateParams.builder()

3207 .model(model)

3208 .prompt(logoPrompt)

3209 .size(ImageGenerateParams.Size._1024X1536)

3210 .quality(ImageGenerateParams.Quality.MEDIUM)

3211 .background(ImageGenerateParams.Background.TRANSPARENT)

3212 .outputFormat(ImageGenerateParams.OutputFormat.PNG)

3213 .n(4)

3214 .build());

3215var images = logos.data().orElseThrow();

3216for (int i = 0; i < images.size(); i++) {

3217 Files.write(

3218 Path.of("logo-generation-" + (i + 1) + suffix),

3219 Base64.getDecoder().decode(images.get(i).b64Json().orElseThrow()));

3220}

3221String cutoutPrompt =

3222 "Extract the product from the input image and isolate it on a fully transparent background.\nOutput: centered product, crisp silhouette, no halos/fringing.\nPreserve product geometry and label legibility exactly.\nAdd only light polishing. Do not add a solid backdrop, checkerboard, scenery, or shadow.\nDo not restyle the product; remove the background and preserve clean alpha transparency.";

3223try (var image = Files.newInputStream(Path.of("input_images/shampoo.webp"))) {

3224 var cutout =

3225 client

3226 .images()

3227 .edit(

3228 ImageEditParams.builder()

3229 .model(model)

3230 .prompt(cutoutPrompt)

3231 .image(

3232 MultipartField.<ImageEditParams.Image>builder()

3233 .value(ImageEditParams.Image.ofInputStream(image))

3234 .filename("shampoo.webp")

3235 .contentType("image/webp")

3236 .build())

3237 .size(ImageEditParams.Size._1024X1536)

3238 .quality(ImageEditParams.Quality.MEDIUM)

3239 .background(ImageEditParams.Background.TRANSPARENT)

3240 .outputFormat(ImageEditParams.OutputFormat.PNG)

3241 .build());

3242 Files.write(

3243 Path.of("extract-product" + suffix),

3244 Base64.getDecoder().decode(cutout.data().orElseThrow().get(0).b64Json().orElseThrow()));

3245}

3246```

3247 

3130```csharp3248```csharp

3131using OpenAI.Images;3249using OpenAI.Images;

3132#pragma warning disable OPENAI0013250#pragma warning disable OPENAI001

Details

123}123}

124```124```

125 125 

126```java

127import com.openai.client.OpenAIClient;

128import com.openai.client.okhttp.OpenAIOkHttpClient;

129import com.openai.models.chat.completions.ChatCompletionCreateParams;

130 

131// Use your configured OpenAIClient named client.

132ChatCompletionCreateParams params =

133 ChatCompletionCreateParams.builder()

134 .model("gpt-6.2-astra")

135 .addUserMessage("Write a one-sentence bedtime story about a unicorn.")

136 .build();

137client.chat().completions().create(params).choices().stream()

138 .flatMap(choice -> choice.message().content().stream())

139 .forEach(System.out::println);

140```

141 

126```csharp142```csharp

127using OpenAI.Chat;143using OpenAI.Chat;

128#pragma warning disable OPENAI001144#pragma warning disable OPENAI001


200}216}

201```217```

202 218 

219```java

220import com.openai.client.OpenAIClient;

221import com.openai.client.okhttp.OpenAIOkHttpClient;

222import com.openai.models.responses.ResponseCreateParams;

223 

224// Use your configured OpenAIClient named client.

225ResponseCreateParams params =

226 ResponseCreateParams.builder()

227 .model("gpt-6.2-astra")

228 .input("Write a one-sentence bedtime story about a unicorn.")

229 .build();

230client.responses().create(params).output().stream()

231 .flatMap(item -> item.message().stream())

232 .flatMap(message -> message.content().stream())

233 .flatMap(content -> content.outputText().stream())

234 .forEach(text -> System.out.println(text.text()));

235```

236 

203```csharp237```csharp

204using OpenAI.Responses;238using OpenAI.Responses;

205#pragma warning disable OPENAI001239#pragma warning disable OPENAI001

Details

8 8 

9## Code refactoring example9## Code refactoring example

10 10 

11Predicted Outputs are particularly useful for regenerating text documents and code files with small modifications. Let's say you want the [GPT-4o model](https://developers.openai.com/api/docs/models#gpt-4o) to refactor a piece of JavaScript code, and convert the `username` property of the `User` class to be `email` instead:11Predicted Outputs are particularly useful for regenerating text documents and code files with small modifications. Let's say you want the [GPT-4o model](https://developers.openai.com/api/docs/models#gpt-4o) to refactor a piece of JavaScript or Java code, and convert the `username` property of the `User` class to be `email` instead:

12 12 

13```typescript13```typescript

14class User {14class User {


20export default User;20export default User;

21```21```

22 22 

23```java

24public static final class User {

25 public String firstName = "";

26 public String lastName = "";

27 public String username = "";

28}

29```

30 

23 31 

24Most of the file will be unchanged, except for line 4 above. If you use the current text of the code file as your prediction, you can regenerate the entire file with lower latency. These time savings add up quickly for larger files.32Most of the file will be unchanged, except for the property declaration. If you use the current text of the code file as your prediction, you can regenerate the entire file with lower latency. These time savings add up quickly for larger files.

25 33 

26Below is an example of using the `prediction` parameter in our SDKs to predict that the final output of the model will be very similar to our original code file, which we use as the prediction text.34Below is an example of using the `prediction` parameter in our SDKs to predict that the final output of the model will be similar to our original code file, which we use as the prediction text.

27 35 

28Refactor a JavaScript class with a Predicted Output36Refactor a JavaScript class with a Predicted Output

29 37 


571 579 

572## Position of predicted text in response580## Position of predicted text in response

573 581 

574When providing prediction text, your prediction can appear anywhere within the generated response, and still provide latency reduction for the response. Let's say your predicted text is the simple [Hono](https://hono.dev/) server shown below:582When providing prediction text, your prediction can appear anywhere within the generated response, and still provide latency reduction for the response. Let's say your predicted text is the [JavaScript web server](https://hono.dev/) shown below:

575 583 

576```typescript584```typescript

577import { serve } from "@hono/node-server";585import { serve } from "@hono/node-server";

Details

145}145}

146```146```

147 147 

148```java

149import com.openai.client.okhttp.OpenAIOkHttpClient;

150import com.openai.core.JsonMissing;

151import com.openai.models.responses.*;

152import java.nio.file.*;

153 

154// Use your configured OpenAIClient named client.

155String policy = Files.readString(Path.of("support-policy.txt")); // At least 1,024 tokens.

156var baseline =

157 ResponseCreateParams.builder()

158 .model("gpt-6-astra")

159 .instructions(policy)

160 .input("Reply with exactly OK.");

161var first =

162 client

163 .responses()

164 .create(

165 baseline

166 .addTool(

167 FunctionTool.builder()

168 .name("get_time")

169 .parameters(JsonMissing.of())

170 .strict(JsonMissing.of())

171 .build())

172 .build());

173var second =

174 client

175 .responses()

176 .create(

177 ResponseCreateParams.builder()

178 .model("gpt-6-astra")

179 .instructions(policy)

180 .input("Reply with exactly OK.")

181 .addTool(

182 FunctionTool.builder()

183 .name("get_date")

184 .parameters(JsonMissing.of())

185 .strict(JsonMissing.of())

186 .build())

187 .promptCacheOptions(

188 ResponseCreateParams.PromptCacheOptions.builder()

189 .comparisonResponseId(first.id())

190 .build())

191 .build());

192second

193 .promptCacheDiagnostics()

194 .flatMap(Response.PromptCacheDiagnostics::cacheMiss)

195 .ifPresent(

196 diagnostics -> {

197 System.out.println(diagnostics.reason().asString());

198 System.out.println(

199 diagnostics.comparisonReusableTokens().map(Object::toString).orElse("None"));

200 System.out.println(diagnostics.cacheMissedTokens());

201 });

202```

203 

148```ruby204```ruby

149require "openai"205require "openai"

150 206 

Details

154 154 

155 155 

156 156 

157 

158 

159 

160The Java version uses `org.bouncycastle:bcprov-jdk18on:1.83`, `io.github.erdtman:java-json-canonicalization:1.1`, and `com.fasterxml.jackson.core:jackson-databind:2.18.11`.

161 

162 

163 

164 

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

158 166 

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

160- `capsule`: The bytes returned by your cloud key-management service.168- `capsule`: The bytes returned by your cloud key-management service.

161- `original_key_id`: The original key registration ID from step 2.169- `original_key_id`: The original key registration ID from step 2.

162- `original_public_key_pem`: That cloud key version's RSA public key in PEM format, as bytes.170- `original_public_key_pem`: That cloud key version's RSA public key in PEM format, as bytes in Python or a string in Java.

163 171 

164The function returns the decrypted content as a UTF-8 string. A failed check stops recovery.172The function returns the decrypted content as a UTF-8 string. A failed check stops recovery.

165 173 


535}543}

536```544```

537 545 

546```java

547import com.fasterxml.jackson.core.*;

548import com.fasterxml.jackson.databind.*;

549import com.fasterxml.jackson.databind.node.ObjectNode;

550import java.math.BigInteger;

551import java.nio.*;

552import java.nio.charset.*;

553import java.nio.file.*;

554import java.security.*;

555import java.security.interfaces.RSAPublicKey;

556import java.security.spec.X509EncodedKeySpec;

557import java.util.*;

558import javax.crypto.*;

559import javax.crypto.spec.*;

560import org.bouncycastle.asn1.sec.SECNamedCurves;

561import org.bouncycastle.crypto.hpke.HPKE;

562import org.erdtman.jcs.JsonCanonicalizer;

563 

564 

565 

566static final ObjectMapper JSON =

567 new ObjectMapper(new JsonFactory().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION));

568 

569static String recoverRecord(byte[] bundleBytes, byte[] capsule, String keyId, String publicPem)

570 throws Exception {

571 try {

572 var bundle = JSON.readTree(bundleBytes);

573 require(

574 bundle.path("bundle_version").isIntegralNumber()

575 && bundle.path("bundle_version").bigIntegerValue().equals(BigInteger.ONE),

576 "Unsupported bundle version");

577 var record = (ObjectNode) bundle.required("protected_record");

578 var access = (ObjectNode) bundle.required("customer_access");

579 require(

580 "v4".equals(record.path("version").asText())

581 && "HPKE-v1-DHKEM_P256_HKDF_SHA256-EXPORT_ONLY-AES256_GCM"

582 .equals(record.path("algorithm").asText()),

583 "Unsupported record");

584 require(

585 access.path("version").isIntegralNumber()

586 && access.path("version").bigIntegerValue().equals(BigInteger.ONE)

587 && "RSA-OAEP-256".equals(access.path("algorithm").asText()),

588 "Unsupported recovery capsule");

589 require(keyId.equals(access.path("customer_key_id").asText()), "Wrong key registration");

590 require(

591 decode(access.required("recovery_secret").asText()).length == 384, "Wrong RSA length");

592 byte[] der =

593 Base64.getMimeDecoder()

594 .decode(

595 publicPem

596 .replace("-----BEGIN PUBLIC KEY-----", "")

597 .replace("-----END PUBLIC KEY-----", ""));

598 var publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der));

599 require(

600 publicKey instanceof RSAPublicKey rsa && rsa.getModulus().bitLength() == 3072,

601 "Expected RSA-3072");

602 require(

603 MessageDigest.isEqual(

604 decode(access.required("customer_public_key_fingerprint").asText()),

605 sha(publicKey.getEncoded())),

606 "Wrong key");

607 byte[] runtime = decode(record.required("safety_review_runtime_public_key").asText());

608 require(runtime.length == 65 && runtime[0] == 4, "Invalid P-256 encoding");

609 var curve = SECNamedCurves.getByName("secp256r1");

610 var point = curve.getCurve().decodePoint(runtime);

611 require(point.isValid() && !point.isInfinity(), "Invalid P-256 point");

612 var jwk =

613 Map.of(

614 "crv",

615 "P-256",

616 "kty",

617 "EC",

618 "x",

619 encode(Arrays.copyOfRange(runtime, 1, 33)),

620 "y",

621 encode(Arrays.copyOfRange(runtime, 33, 65)));

622 require(

623 record.required("key_thumbprint").asText().equals(encode(sha(canonical(jwk)))),

624 "Wrong runtime key");

625 byte[] nonce = decode(record.required("nonce").asText()),

626 ciphertext = decode(record.required("ciphertext").asText());

627 require(nonce.length == 12 && ciphertext.length >= 16, "Invalid AES-GCM encoding");

628 var header = access.deepCopy();

629 header.remove("recovery_secret");

630 byte[] binding =

631 sha(

632 canonical(

633 Map.of(

634 "purpose",

635 "OpenAI-PSP-v4/customer-recovery-binding",

636 "bundle_version",

637 1,

638 "record",

639 record,

640 "recovery_header",

641 header)));

642 require(

643 capsule.length == 72

644 && Arrays.equals(

645 Arrays.copyOfRange(capsule, 0, 8), new byte[] {80, 83, 80, 118, 52, 0, 0, 1})

646 && MessageDigest.isEqual(Arrays.copyOfRange(capsule, 40, 72), binding),

647 "Invalid recovery capsule binding");

648 byte[] scalar = Arrays.copyOfRange(capsule, 8, 40);

649 var e = new BigInteger(1, scalar);

650 require(e.signum() > 0 && e.compareTo(curve.getN()) < 0, "Invalid P-256 private scalar");

651 var suite =

652 new HPKE(

653 HPKE.mode_base, HPKE.kem_P256_SHA256, HPKE.kdf_HKDF_SHA256, HPKE.aead_EXPORT_ONLY);

654 byte[] ephemeralPublic = curve.getG().multiply(e).getEncoded(false);

655 var pair = suite.deserializePrivateKey(scalar, ephemeralPublic);

656 var sender =

657 suite.setupBaseS(

658 suite.deserializePublicKey(runtime),

659 "OpenAI-PSP-v4/HPKE-export".getBytes(StandardCharsets.UTF_8),

660 pair);

661 require(

662 MessageDigest.isEqual(

663 sender.getEncapsulation(), decode(record.required("encrypted_dek").asText())),

664 "Wrong recovered scalar");

665 var aadRecord = record.deepCopy();

666 aadRecord.remove("ciphertext");

667 byte[] aad = canonical(aadRecord);

668 byte[] prefix = "OpenAI-PSP-v4/payload-key".getBytes(StandardCharsets.UTF_8);

669 byte[] context = ByteBuffer.allocate(prefix.length + 32).put(prefix).put(sha(aad)).array();

670 byte[] key = sender.export(context, 32);

671 try {

672 var cipher = Cipher.getInstance("AES/GCM/NoPadding");

673 cipher.init(

674 Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce));

675 cipher.updateAAD(aad);

676 return StandardCharsets.UTF_8

677 .newDecoder()

678 .onMalformedInput(CodingErrorAction.REPORT)

679 .decode(ByteBuffer.wrap(cipher.doFinal(ciphertext)))

680 .toString();

681 } finally {

682 Arrays.fill(key, (byte) 0);

683 Arrays.fill(scalar, (byte) 0);

684 }

685 } catch (AEADBadTagException error) {

686 throw error;

687 } catch (Exception error) {

688 throw new IllegalArgumentException("Invalid recovery bundle or capsule", error);

689 }

690}

691 

692static byte[] canonical(Object value) throws Exception {

693 return new JsonCanonicalizer(JSON.writeValueAsString(value)).getEncodedUTF8();

694}

695 

696static byte[] sha(byte[] value) throws Exception {

697 return MessageDigest.getInstance("SHA-256").digest(value);

698}

699 

700static String encode(byte[] value) {

701 return Base64.getUrlEncoder().withoutPadding().encodeToString(value);

702}

703 

704static byte[] decode(String value) {

705 byte[] decoded = Base64.getUrlDecoder().decode(value);

706 require(encode(decoded).equals(value), "Noncanonical base64url");

707 return decoded;

708}

709 

710static void require(boolean condition, String message) {

711 if (!condition) throw new IllegalArgumentException(message);

712}

713```

714 

538```ruby715```ruby

539require "base64"716require "base64"

540require "digest"717require "digest"

Details

824}824}

825```825```

826 826 

827```java

828import com.openai.client.okhttp.OpenAIOkHttpClient;

829import com.openai.errors.RateLimitException;

830import com.openai.models.responses.*;

831import java.util.concurrent.ThreadLocalRandom;

832import java.util.function.Supplier;

833 

834var client = OpenAIOkHttpClient.builder().fromEnv().maxRetries(0).build();

835var params =

836 ResponseCreateParams.builder()

837 .model("gpt-6-luna")

838 .input("Say hello in one sentence.")

839 .reasoning(

840 com.openai.models.Reasoning.builder()

841 .effort(com.openai.models.ReasoningEffort.LOW)

842 .build())

843 .maxOutputTokens(2048)

844 .build();

845var response =

846 retryWithExponentialBackoff(() -> client.responses().create(params), 1000, 2, true, 10);

847response.output().stream()

848 .flatMap(item -> item.message().stream())

849 .flatMap(message -> message.content().stream())

850 .flatMap(content -> content.outputText().stream())

851 .forEach(text -> System.out.println(text.text()));

852 

853static <T> T retryWithExponentialBackoff(

854 Supplier<T> operation, long initialDelayMs, double base, boolean jitter, int maxRetries)

855 throws InterruptedException {

856 double delay = initialDelayMs;

857 for (int retries = 0; ; retries++) {

858 try {

859 return operation.get();

860 } catch (RateLimitException error) {

861 if (retries >= maxRetries) throw error;

862 delay *= base * (1 + (jitter ? ThreadLocalRandom.current().nextDouble() : 0));

863 Thread.sleep((long) delay);

864 }

865 }

866}

867```

868 

827```csharp869```csharp

828using System.ClientModel;870using System.ClientModel;

829using System.ClientModel.Primitives;871using System.ClientModel.Primitives;

Details

1284}1284}

1285```1285```

1286 1286 

1287```java

1288import com.openai.client.okhttp.OkHttpClient;

1289import com.openai.core.ClientOptions;

1290import com.openai.core.JsonMissing;

1291import com.openai.helpers.RealtimeConnection;

1292import com.openai.helpers.RealtimeWebSocketOptions;

1293import com.openai.models.realtime.*;

1294import java.nio.file.Files;

1295import java.nio.file.Path;

1296import java.util.Base64;

1297 

1298connection.send(

1299 RealtimeClientEvent.ofConversationItemCreate(

1300 ConversationItemCreateEvent.builder()

1301 .item(

1302 RealtimeConversationItemUserMessage.builder()

1303 .object_(JsonMissing.of())

1304 .addContent(

1305 RealtimeConversationItemUserMessage.Content.builder()

1306 .type(

1307 RealtimeConversationItemUserMessage.Content.Type.INPUT_IMAGE)

1308 .imageUrl(

1309 "data:image/png;base64,"

1310 + Base64.getEncoder()

1311 .encodeToString(

1312 Files.readAllBytes(Path.of("image.png"))))

1313 .build())

1314 .addContent(

1315 RealtimeConversationItemUserMessage.Content.builder()

1316 .type(RealtimeConversationItemUserMessage.Content.Type.INPUT_TEXT)

1317 .text("Describe this image.")

1318 .build())

1319 .build())

1320 .build()));

1321connection.send(

1322 RealtimeClientEvent.ofResponseCreate(

1323 ResponseCreateEvent.builder()

1324 .response(

1325 RealtimeResponseCreateParams.builder()

1326 .addOutputModality(RealtimeResponseCreateParams.OutputModality.TEXT)

1327 .build())

1328 .build()));

1329while (true) {

1330 var event = connection.receive();

1331 if (event.error().isPresent())

1332 throw new IllegalStateException(event.error().orElseThrow().toString());

1333 if (event.responseDone().isPresent()) {

1334 var response = event.responseDone().orElseThrow().response();

1335 if (!response.status().filter(RealtimeResponse.Status.COMPLETED::equals).isPresent())

1336 throw new IllegalStateException("Response did not complete: " + response.status());

1337 break;

1338 }

1339}

1340```

1341 

1287```csharp1342```csharp

1288using OpenAI.Realtime;1343using OpenAI.Realtime;

1289#pragma warning disable OPENAI0021344#pragma warning disable OPENAI002

Details

921}921}

922```922```

923 923 

924```java

925import com.openai.client.okhttp.OkHttpClient;

926import com.openai.core.ClientOptions;

927import com.openai.helpers.RealtimeConnection;

928import com.openai.helpers.RealtimeWebSocketOptions;

929import com.openai.models.realtime.*;

930import java.util.List;

931 

932connection.send(

933 RealtimeClientEvent.ofSessionUpdate(

934 SessionUpdateEvent.builder()

935 .session(

936 RealtimeSessionCreateRequest.builder()

937 .addTool(

938 RealtimeToolsConfigUnion.Mcp.builder()

939 .serverLabel("openai_docs")

940 .serverUrl("https://developers.openai.com/mcp")

941 .allowedToolsOfMcp(List.of("search_openai_docs"))

942 .requireApproval(

943 RealtimeToolsConfigUnion.Mcp.RequireApproval

944 .McpToolApprovalSetting.NEVER)

945 .build())

946 .build())

947 .build()));

948 

949var expectedCalls = new java.util.HashSet<String>();

950var completedCalls = new java.util.HashSet<String>();

951boolean responseCompleted = false;

952long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(90);

953while (true) {

954 var event =

955 connection

956 .receiveAsync()

957 .get(

958 Math.max(0, deadline - System.nanoTime()),

959 java.util.concurrent.TimeUnit.NANOSECONDS);

960 if (event.error().isPresent())

961 throw new IllegalStateException(event.error().orElseThrow().toString());

962 if (event.mcpListToolsFailed().isPresent())

963 throw new IllegalStateException("MCP tool listing failed");

964 if (event.responseMcpCallFailed().isPresent())

965 throw new IllegalStateException("MCP tool call failed");

966 event

967 .mcpListToolsInProgress()

968 .ifPresent(

969 value -> System.out.println("Listing MCP tools for item: " + value.itemId()));

970 if (event.mcpListToolsCompleted().isPresent()) {

971 System.out.println(

972 "MCP tools ready for item: " + event.mcpListToolsCompleted().orElseThrow().itemId());

973 connection.send(

974 RealtimeClientEvent.ofResponseCreate(

975 ResponseCreateEvent.builder()

976 .response(

977 RealtimeResponseCreateParams.builder()

978 .addOutputModality(RealtimeResponseCreateParams.OutputModality.TEXT)

979 .addInput(

980 RealtimeConversationItemUserMessage.builder()

981 .object_(com.openai.core.JsonMissing.of())

982 .addContent(

983 RealtimeConversationItemUserMessage.Content.builder()

984 .type(

985 RealtimeConversationItemUserMessage.Content.Type

986 .INPUT_TEXT)

987 .text(

988 "Which Realtime API transport should browser clients use?")

989 .build())

990 .build())

991 .toolChoice(com.openai.models.responses.ToolChoiceOptions.REQUIRED)

992 .parallelToolCalls(false)

993 .build())

994 .build()));

995 }

996 event

997 .conversationItemDone()

998 .ifPresent(

999 done -> {

1000 done.item()

1001 .mcpListTools()

1002 .ifPresent(

1003 item ->

1004 System.out.println(

1005 "MCP tools ready on "

1006 + item.serverLabel()

1007 + ": "

1008 + item.tools().stream()

1009 .map(tool -> tool.name())

1010 .collect(java.util.stream.Collectors.joining(", "))));

1011 done.item()

1012 .mcpApprovalRequest()

1013 .ifPresent(

1014 item ->

1015 System.out.println(

1016 "Approval required for: "

1017 + item.name()

1018 + " "

1019 + item.arguments()));

1020 });

1021 event

1022 .responseMcpCallArgumentsDone()

1023 .ifPresent(

1024 value -> System.out.println("Final MCP call arguments: " + value.arguments()));

1025 event

1026 .responseMcpCallInProgress()

1027 .ifPresent(value -> System.out.println("Running MCP tool for item: " + value.itemId()));

1028 event

1029 .responseMcpCallCompleted()

1030 .ifPresent(value -> System.out.println("MCP tool call completed: " + value.itemId()));

1031 event

1032 .responseOutputItemDone()

1033 .ifPresent(

1034 done -> {

1035 done.item()

1036 .mcpCall()

1037 .ifPresent(

1038 call -> {

1039 if (call.id().isBlank()

1040 || call.error().isPresent()

1041 || call.output().filter(output -> !output.isBlank()).isEmpty())

1042 throw new IllegalStateException("MCP tool call failed");

1043 if (!completedCalls.add(call.id()))

1044 throw new IllegalStateException("Duplicate MCP result");

1045 System.out.println(

1046 "MCP output from "

1047 + call.serverLabel()

1048 + "."

1049 + call.name()

1050 + ": "

1051 + call.output().orElseThrow());

1052 });

1053 done.item()

1054 .realtimeConversationItemAssistantMessage()

1055 .ifPresent(

1056 item ->

1057 System.out.println(

1058 "Assistant: "

1059 + item.content().stream()

1060 .map(content -> content.text().orElse(""))

1061 .collect(java.util.stream.Collectors.joining())));

1062 });

1063 if (event.responseDone().isPresent()) {

1064 var response = event.responseDone().orElseThrow().response();

1065 if (responseCompleted

1066 || !response.status().filter(RealtimeResponse.Status.COMPLETED::equals).isPresent())

1067 throw new IllegalStateException("Realtime response did not complete");

1068 for (var item : response.output().orElseThrow())

1069 item.mcpCall()

1070 .ifPresent(

1071 call -> {

1072 if (call.id().isBlank() || !expectedCalls.add(call.id()))

1073 throw new IllegalStateException("Invalid MCP call identity");

1074 });

1075 if (expectedCalls.isEmpty())

1076 throw new IllegalStateException("The response did not call an MCP tool");

1077 responseCompleted = true;

1078 }

1079 if (responseCompleted && expectedCalls.equals(completedCalls)) {

1080 System.out.println("Realtime turn complete.");

1081 break;

1082 }

1083}

1084```

1085 

924```ruby1086```ruby

925completed_events = {}1087completed_events = {}

926expected_calls = []1088expected_calls = []

Details

215}215}

216```216```

217 217 

218```java

219import com.openai.client.okhttp.OkHttpClient;

220import com.openai.core.ClientOptions;

221import com.openai.helpers.RealtimeConnection;

222import com.openai.helpers.RealtimeWebSocketOptions;

223import com.openai.models.realtime.*;

224import java.nio.file.*;

225import java.util.Base64;

226 

227var http = OkHttpClient.builder().build();

228var options =

229 ClientOptions.builder()

230 .fromEnv()

231 .httpClient(http)

232 .putHeader("OpenAI-Safety-Identifier", "hashed-user-id")

233 .build();

234try (http;

235 var connection =

236 RealtimeConnection.connect(

237 options, RealtimeWebSocketOptions.builder().transcription().build())) {

238 send(

239 connection,

240 RealtimeClientEvent.ofSessionUpdate(

241 SessionUpdateEvent.builder()

242 .session(

243 RealtimeTranscriptionSessionCreateRequest.builder()

244 .audio(

245 RealtimeTranscriptionSessionAudio.builder()

246 .input(

247 RealtimeTranscriptionSessionAudioInput.builder()

248 .format(

249 RealtimeAudioFormats.AudioPcm.builder()

250 .type(

251 RealtimeAudioFormats.AudioPcm.Type.AUDIO_PCM)

252 .rate(RealtimeAudioFormats.AudioPcm.Rate._24000)

253 .build())

254 .turnDetection(com.openai.core.JsonValue.from(null))

255 .transcription(

256 AudioTranscription.builder()

257 .model("gpt-live-transcribe")

258 .build())

259 .build())

260 .build())

261 .build())

262 .build()));

263 while (true) {

264 var event = connection.receive();

265 if (event.error().isPresent())

266 throw new IllegalStateException(event.error().orElseThrow().toString());

267 if (event.sessionUpdated().isPresent()) break;

268 }

269 byte[] audio = Files.readAllBytes(Path.of("speech.pcm"));

270 if (audio.length == 0 || audio.length % 2 != 0)

271 throw new IllegalArgumentException("Expected mono PCM16 at 24 kHz");

272 for (int start = 0; start < audio.length; start += 9600) {

273 var chunk =

274 java.util.Arrays.copyOfRange(audio, start, Math.min(start + 9600, audio.length));

275 send(

276 connection,

277 RealtimeClientEvent.ofInputAudioBufferAppend(

278 InputAudioBufferAppendEvent.builder()

279 .audio(Base64.getEncoder().encodeToString(chunk))

280 .build()));

281 }

282 send(

283 connection,

284 RealtimeClientEvent.ofInputAudioBufferCommit(

285 InputAudioBufferCommitEvent.builder().build()));

286 String itemId = null;

287 while (true) {

288 var event = connection.receive();

289 if (event.error().isPresent())

290 throw new IllegalStateException(event.error().orElseThrow().toString());

291 if (event.inputAudioBufferCommitted().isPresent())

292 itemId = event.inputAudioBufferCommitted().orElseThrow().itemId();

293 if (event.conversationItemInputAudioTranscriptionDelta().isPresent()) {

294 var delta = event.conversationItemInputAudioTranscriptionDelta().orElseThrow();

295 if (delta.itemId().equals(itemId))

296 System.err.println(

297 "Partial transcript (" + delta.itemId() + "): " + delta.delta().orElse(""));

298 }

299 if (event.conversationItemInputAudioTranscriptionCompleted().isPresent()) {

300 var completed = event.conversationItemInputAudioTranscriptionCompleted().orElseThrow();

301 if (completed.itemId().equals(itemId)) {

302 System.out.println("Final transcript: " + completed.transcript());

303 break;

304 }

305 }

306 if (event.conversationItemInputAudioTranscriptionFailed().isPresent()

307 && event

308 .conversationItemInputAudioTranscriptionFailed()

309 .orElseThrow()

310 .itemId()

311 .equals(itemId)) throw new IllegalStateException("Transcription failed");

312 }

313}

314 

315static void send(RealtimeConnection connection, RealtimeClientEvent event) throws Exception {

316 long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10);

317 while (true) {

318 try {

319 connection.send(event);

320 return;

321 } catch (com.openai.core.http.WebSocketWriteNotAttempted.Busy busy) {

322 if (System.nanoTime() >= deadline) throw busy;

323 Thread.sleep(10);

324 }

325 }

326}

327```

328 

218```csharp329```csharp

219using OpenAI.Realtime;330using OpenAI.Realtime;

220#pragma warning disable OPENAI002331#pragma warning disable OPENAI002

Details

150 150 

151 151 

152 152 

153Before running this example, add the Maven dependency `com.openai:openai-java:4.75.1`.153Before running this example, add the Maven dependency `com.openai:openai-java:4.105.0`.

154 154 

155 155 

156 156 


158 158 

159 159 

160 160 

161The Java examples cover connection setup, language configuration, and audio input separately. They don't show a complete translation workflow: the Java SDK supports receiving events and finishing a session, but this guide doesn't include Java examples for those steps. Use the Node.js or Python examples to follow the complete workflow below.161The Java examples cover connection setup, language configuration, audio input, event reception, and session completion in separate snippets. Keep the same translation connection across these steps in your application.

162 162 

163 163 

164 164 


534}534}

535```535```

536 536 

537```java

538static void listen(TranslationConnection connection) {

539 while (true) {

540 var event = connection.receive();

541 if (event.error().isPresent())

542 throw new IllegalStateException(event.error().orElseThrow().toString());

543 if (event.sessionCreated().isPresent()) System.out.println("session.created");

544 if (event.sessionUpdated().isPresent()) System.out.println("session.updated");

545 event.sessionOutputTranscriptDelta().ifPresent(delta -> System.out.print(delta.delta()));

546 event

547 .sessionOutputAudioDelta()

548 .ifPresent(

549 delta -> {

550 byte[] pcm = Base64.getDecoder().decode(delta.delta());

551 // Feed pcm to your application's 24 kHz audio player.

552 System.err.println("Received audio bytes: " + pcm.length);

553 });

554 if (event.sessionClosed().isPresent()) {

555 System.out.println();

556 return;

557 }

558 }

559}

560```

561 

537```ruby562```ruby

538handle_translation_event = lambda do |event, output|563handle_translation_event = lambda do |event, output|

539 case event564 case event


711}736}

712```737```

713 738 

739```java

740// Stop sending audio, then drain events until the server acknowledges closure.

741var finished = connection.finishAsync(java.time.Duration.ofSeconds(30));

742listen(connection);

743finished.join();

744```

745 

714```ruby746```ruby

715# Finish the existing session and consume its trailing output through session.closed.747# Finish the existing session and consume its trailing output through session.closed.

716File.open("translated.pcm", "wb") do |output|748File.open("translated.pcm", "wb") do |output|

Details

158}158}

159```159```

160 160 

161```java

162import com.openai.client.OpenAIClient;

163import com.openai.client.okhttp.OpenAIOkHttpClient;

164import com.openai.models.beta.responses.*;

165 

166// Use your configured OpenAIClient named client.

167System.out.println(reviewPullRequest(client, "-timeout = 30\n+timeout = None"));

168 

169static String reviewPullRequest(OpenAIClient client, String diff) {

170 var response =

171 client

172 .beta()

173 .responses()

174 .create(

175 ResponseCreateParams.builder()

176 .model("gpt-6.2-sol")

177 .input(

178 "Review the pull-request diff below with three agents: one for correctness, one for security, and one for missing tests. Reconcile duplicate or conflicting findings, then return a prioritized review with file and line references.\n\n<diff>\n"

179 + diff

180 + "\n</diff>")

181 .multiAgent(

182 ResponseCreateParams.MultiAgent.builder()

183 .enabled(true)

184 .maxConcurrentSubagents(3)

185 .build())

186 .addBeta(ResponseCreateParams.Beta.of("responses_multi_agent=v1"))

187 .build());

188 return response.output().stream()

189 .flatMap(item -> item.message().stream())

190 .filter(

191 message ->

192 message.agent().map(agent -> agent.agentName().equals("/root")).orElse(false))

193 .filter(

194 message ->

195 message

196 .phase()

197 .filter(BetaResponseOutputMessage.Phase.FINAL_ANSWER::equals)

198 .isPresent())

199 .flatMap(message -> message.content().stream())

200 .flatMap(content -> content.outputText().stream())

201 .map(text -> text.text())

202 .collect(java.util.stream.Collectors.joining());

203}

204```

205 

161```ruby206```ruby

162def review_pull_request(client, diff)207def review_pull_request(client, diff)

163 response = client.beta.responses.create(208 response = client.beta.responses.create(


1256}1301}

1257```1302```

1258 1303 

1304```java

1305import com.openai.client.okhttp.OpenAIOkHttpClient;

1306import com.openai.core.JsonValue;

1307import com.openai.core.ObjectMappers;

1308import com.openai.core.http.WebSocketOptions;

1309import com.openai.models.beta.responses.*;

1310import java.util.*;

1311import java.util.concurrent.TimeUnit;

1312 

1313 

1314 

1315var client = OpenAIOkHttpClient.fromEnv();

1316try (var connection =

1317 client

1318 .beta()

1319 .responses()

1320 .connectWebSocket(

1321 WebSocketOptions.builder()

1322 .putHeader("OpenAI-Beta", "responses_multi_agent=v1")

1323 .build())) {

1324 var tool =

1325 BetaFunctionTool.builder()

1326 .name("get_proposal")

1327 .strict(true)

1328 .parameters(

1329 BetaFunctionTool.Parameters.builder()

1330 .putAdditionalProperty("type", JsonValue.from("object"))

1331 .putAdditionalProperty(

1332 "properties",

1333 JsonValue.from(

1334 Map.of(

1335 "proposal",

1336 Map.of("type", "string", "enum", List.of("alpha", "beta")))))

1337 .putAdditionalProperty("required", JsonValue.from(List.of("proposal")))

1338 .putAdditionalProperty("additionalProperties", JsonValue.from(false))

1339 .build())

1340 .build();

1341 

1342 var input = new ArrayList<BetaResponseInputItem>();

1343 input.add(

1344 BetaResponseInputItem.ofBetaEasyInputMessage(

1345 BetaEasyInputMessage.builder()

1346 .role(BetaEasyInputMessage.Role.USER)

1347 .content(new Scanner(System.in).nextLine())

1348 .build()));

1349 String previousResponseId = null;

1350 while (true) {

1351 var request =

1352 BetaResponsesClientEvent.ResponseCreate.builder()

1353 .model("gpt-6.2-sol")

1354 .store(true)

1355 .inputOfBetaResponse(input)

1356 .addTool(tool)

1357 .multiAgent(

1358 BetaResponsesClientEvent.ResponseCreate.MultiAgent.builder()

1359 .enabled(true)

1360 .maxConcurrentSubagents(3)

1361 .build());

1362 if (previousResponseId != null) request.previousResponseId(previousResponseId);

1363 connection.send(BetaResponsesClientEvent.ofResponseCreate(request.build()));

1364 String responseId = null;

1365 BetaResponse completed = null;

1366 int pending = 0;

1367 var retryInput = new ArrayList<BetaResponseInputItem>();

1368 long deadline = System.nanoTime() + TimeUnit.MINUTES.toNanos(5);

1369 while (completed == null || pending != 0) {

1370 var event =

1371 connection

1372 .receiveAsync()

1373 .get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);

1374 if (event.error().isPresent()

1375 || event.responseFailed().isPresent()

1376 || event.responseIncomplete().isPresent())

1377 throw new IllegalStateException("Multi-agent response failed: " + event);

1378 if (event.responseCreated().isPresent())

1379 responseId = event.responseCreated().orElseThrow().response().id();

1380 if (event.responseOutputItemDone().isPresent()) {

1381 var item = event.responseOutputItemDone().orElseThrow().item();

1382 if (item.functionCall().isPresent()) {

1383 var call = item.functionCall().orElseThrow();

1384 if (responseId == null || !call.name().equals("get_proposal"))

1385 throw new IllegalStateException("Unexpected function call");

1386 String proposal =

1387 ObjectMappers.jsonMapper().readTree(call.arguments()).path("proposal").asText();

1388 if (!proposal.equals("alpha") && !proposal.equals("beta"))

1389 throw new IllegalArgumentException("Unknown proposal");

1390 String result =

1391 ObjectMappers.jsonMapper()

1392 .writeValueAsString(

1393 Map.of(

1394 "estimated_weeks",

1395 proposal.equals("alpha") ? 6 : 8,

1396 "risk",

1397 proposal.equals("alpha") ? "medium" : "low"));

1398 connection.send(

1399 BetaResponsesClientEvent.ofResponseInject(

1400 BetaResponseInjectEvent.builder()

1401 .responseId(responseId)

1402 .addInput(

1403 BetaResponseInputItem.FunctionCallOutput.builder()

1404 .callId(call.callId())

1405 .output(result)

1406 .build())

1407 .build()));

1408 pending++;

1409 }

1410 }

1411 if (event.responseInjectCreated().isPresent()) pending--;

1412 if (event.responseInjectFailed().isPresent()) {

1413 var failed = event.responseInjectFailed().orElseThrow();

1414 pending--;

1415 if (!failed

1416 .error()

1417 .code()

1418 .equals(BetaResponseInjectFailedEvent.Error.Code.RESPONSE_ALREADY_COMPLETED))

1419 throw new IllegalStateException("Injection failed: " + failed.error());

1420 retryInput.addAll(failed.input());

1421 }

1422 if (pending < 0) throw new IllegalStateException("Unexpected injection acknowledgement");

1423 if (event.responseCompleted().isPresent())

1424 completed = event.responseCompleted().orElseThrow().response();

1425 }

1426 if (!retryInput.isEmpty()) {

1427 input = retryInput;

1428 previousResponseId = completed.id();

1429 continue;

1430 }

1431 completed.output().stream()

1432 .flatMap(item -> item.message().stream())

1433 .filter(

1434 message ->

1435 message.agent().map(agent -> agent.agentName().equals("/root")).orElse(false))

1436 .filter(

1437 message ->

1438 message

1439 .phase()

1440 .filter(BetaResponseOutputMessage.Phase.FINAL_ANSWER::equals)

1441 .isPresent())

1442 .flatMap(message -> message.content().stream())

1443 .flatMap(content -> content.outputText().stream())

1444 .forEach(text -> System.out.print(text.text()));

1445 System.out.println();

1446 break;

1447 }

1448} finally {

1449 client.close();

1450}

1451```

1452 

1259```ruby1453```ruby

1260require "async"1454require "async"

1261require "async/http/endpoint"1455require "async/http/endpoint"

Details

763 763 

764 764 

765 765 

766 

767 

768 

769The Java example uses audio streams for uncompressed WAV files. It writes a single chunk containing at most ten minutes of audio and totaling less than 25 MB, so stereo recordings or recordings with higher sample rates produce shorter chunks.

770 

771 

772 

773 

766Split a long audio file774Split a long audio file

767 775 

768```typescript776```typescript


870}878}

871```879```

872 880 

881```java

882import com.fasterxml.jackson.databind.ObjectMapper;

883import java.nio.file.*;

884import java.util.*;

885import javax.sound.sampled.*;

886 

887try (var song = AudioSystem.getAudioInputStream(Path.of("good_morning.wav").toFile())) {

888 var format = song.getFormat();

889 if (format.getFrameSize() <= 0 || format.getFrameRate() <= 0)

890 throw new IllegalArgumentException("WAV must have a known frame size and rate");

891 // Keep headroom below the 25 MB upload limit, including WAV headers.

892 long byteLimitedFrames = (24_000_000L - 1024) / format.getFrameSize();

893 long frames = Math.min(byteLimitedFrames, (long) (600 * format.getFrameRate()));

894 if (song.getFrameLength() != AudioSystem.NOT_SPECIFIED)

895 frames = Math.min(frames, song.getFrameLength());

896 try (var firstTenMinutes = new AudioInputStream(song, format, frames)) {

897 AudioSystem.write(

898 firstTenMinutes, AudioFileFormat.Type.WAVE, Path.of("good_morning_10.wav").toFile());

899 

900}

901}

902```

903 

873```ruby904```ruby

874# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.905# standard:disable Lint/UselessAssignment -- Preserve named results for the next workflow step.

875require "open3"906require "open3"

Details

10 10 

11Steering does not rewrite output already sent to your application, undo earlier actions, or cancel tools that have already started.11Steering does not rewrite output already sent to your application, undo earlier actions, or cancel tools that have already started.

12 12 

13The Java example requires Java 17 or later. For connection setup and general transport behavior, see [WebSocket mode](https://developers.openai.com/api/docs/guides/websocket-mode). For exact event definitions, see the [Responses WebSocket events reference](https://developers.openai.com/api/reference/resources/responses/websocket-events).13For connection setup and general transport behavior, see [WebSocket mode](https://developers.openai.com/api/docs/guides/websocket-mode). For exact event definitions, see the [Responses WebSocket events reference](https://developers.openai.com/api/reference/resources/responses/websocket-events).

14 14 

15## Send a steering message15## Send a steering message

16 16 

Details

473 473 

474 474 

475 475 

476 

477 

478Add `com.microsoft.playwright:playwright:1.61.0` to your Maven dependencies. Run `com.microsoft.playwright.CLI` with the arguments `install chromium` from your IDE or build tool, using the same dependency classpath. Run subsequent browser actions and capture screenshots inside the setup’s `try` block before the setup closes the browser and Playwright resources.

479 

480 

481 

482 

476Start a browser instance483Start a browser instance

477 484 

478```typescript485```typescript


503 page = browser.new_page(viewport={"width": 1280, "height": 720})510 page = browser.new_page(viewport={"width": 1280, "height": 720})

504```511```

505 512 

513```java

514import com.microsoft.playwright.*;

515import com.microsoft.playwright.options.*;

516import com.openai.core.ObjectMappers;

517import java.nio.file.*;

518import java.util.*;

519 

520try (var playwright = Playwright.create();

521 var browser =

522 playwright

523 .chromium()

524 .launch(

525 new BrowserType.LaunchOptions()

526 .setHeadless(true)

527 .setChromiumSandbox(true)

528 .setEnv(Map.of())

529 .setArgs(List.of("--disable-extensions", "--disable-file-system")))) {

530 var page = browser.newPage(new Browser.NewPageOptions().setViewportSize(1280, 720));

531 

532}

533 

534 

535```

536 

506```ruby537```ruby

507require "playwright"538require "playwright"

508 539 


675vm = VM(display=":99", container_name="cua-image")706vm = VM(display=":99", container_name="cua-image")

676```707```

677 708 

709```java

710import com.openai.core.ObjectMappers;

711import java.nio.charset.StandardCharsets;

712import java.nio.file.*;

713import java.util.*;

714 

715 

716 

717record VM(String display, String containerName) {}

718 

719static byte[] dockerExec(

720 String containerName,

721 String executable,

722 List<String> arguments,

723 Map<String, String> environment)

724 throws Exception {

725 var command = new ArrayList<String>(List.of("docker", "exec"));

726 environment.forEach(

727 (name, value) -> {

728 command.add("--env");

729 command.add(name + "=" + value);

730 });

731 command.add(containerName);

732 command.add(executable);

733 command.addAll(arguments);

734 

735var process =

736 new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT).start();

737 process.getOutputStream().close();

738 try (var output = process.getInputStream()) {

739 byte[] result = output.readAllBytes();

740 if (process.waitFor() != 0) throw new IllegalStateException("Container command failed");

741 return result;

742 } finally {

743 process.destroy();

744 }

745}

746 

747static void xdotool(VM vm, String... arguments) throws Exception {

748 dockerExec(vm.containerName(), "xdotool", List.of(arguments), Map.of("DISPLAY", vm.display()));

749}

750```

751 

678```ruby752```ruby

679def docker_exec(container_name, executable, args, decode: true, env: {})753def docker_exec(container_name, executable, args, decode: true, env: {})

680 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }754 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }


892 return [(point.x, point.y) for point in path]966 return [(point.x, point.y) for point in path]

893```967```

894 968 

969```java

970import com.microsoft.playwright.*;

971import com.microsoft.playwright.options.*;

972import com.openai.core.ObjectMappers;

973import com.openai.models.responses.ComputerAction;

974import java.nio.file.*;

975import java.util.*;

976 

977 

978 

979static String normalizeKey(String key) {

980 return switch (key) {

981 case "ENTER", "RETURN" -> "Enter";

982 case "ESC", "ESCAPE" -> "Escape";

983 case "TAB" -> "Tab";

984 case "SPACE" -> "Space";

985 case "BACKSPACE" -> "Backspace";

986 case "DELETE", "DEL" -> "Delete";

987 case "HOME" -> "Home";

988 case "END" -> "End";

989 case "PAGEUP" -> "PageUp";

990 case "PAGEDOWN" -> "PageDown";

991 case "UP", "ARROWUP" -> "ArrowUp";

992 case "DOWN", "ARROWDOWN" -> "ArrowDown";

993 case "LEFT", "ARROWLEFT" -> "ArrowLeft";

994 case "RIGHT", "ARROWRIGHT" -> "ArrowRight";

995 case "CTRL", "CONTROL" -> "Control";

996 case "SHIFT" -> "Shift";

997 case "ALT", "OPTION" -> "Alt";

998 case "META", "CMD", "COMMAND" -> "Meta";

999 default -> key;

1000 };

1001}

1002 

1003static MouseButton normalizeButton(String button) {

1004 return switch (button) {

1005 case "left" -> MouseButton.LEFT;

1006 case "wheel" -> MouseButton.MIDDLE;

1007 case "right" -> MouseButton.RIGHT;

1008 default -> throw new IllegalArgumentException("Unsupported mouse button: " + button);

1009 };

1010}

1011 

1012static List<List<Long>> normalizeDragPath(List<ComputerAction.Drag.Path> path) {

1013 return path.stream().map(point -> List.of(point.x(), point.y())).toList();

1014}

1015```

1016 

895```ruby1017```ruby

896def normalize_key(key)1018def normalize_key(key)

897 names = {1019 names = {


1160 return [(point.x, point.y) for point in path]1282 return [(point.x, point.y) for point in path]

1161```1283```

1162 1284 

1285```java

1286import com.openai.core.ObjectMappers;

1287import com.openai.models.responses.ComputerAction;

1288import java.nio.file.*;

1289import java.util.*;

1290 

1291 

1292 

1293static String normalizeKey(String key) {

1294 return switch (key) {

1295 case "ENTER", "RETURN" -> "Return";

1296 case "ESC", "ESCAPE" -> "Escape";

1297 case "TAB" -> "Tab";

1298 case "SPACE" -> "space";

1299 case "BACKSPACE" -> "BackSpace";

1300 case "DELETE", "DEL" -> "Delete";

1301 case "HOME" -> "Home";

1302 case "END" -> "End";

1303 case "PAGEUP" -> "Page_Up";

1304 case "PAGEDOWN" -> "Page_Down";

1305 case "UP", "ARROWUP" -> "Up";

1306 case "DOWN", "ARROWDOWN" -> "Down";

1307 case "LEFT", "ARROWLEFT" -> "Left";

1308 case "RIGHT", "ARROWRIGHT" -> "Right";

1309 case "CTRL", "CONTROL" -> "ctrl";

1310 case "SHIFT" -> "shift";

1311 case "ALT", "OPTION" -> "alt";

1312 case "META", "CMD", "COMMAND" -> "super";

1313 default -> key;

1314 };

1315}

1316 

1317static int normalizeButton(String button) {

1318 return switch (button) {

1319 case "left" -> 1;

1320 case "wheel" -> 2;

1321 case "right" -> 3;

1322 case "back" -> 8;

1323 case "forward" -> 9;

1324 default -> throw new IllegalArgumentException("Unsupported mouse button: " + button);

1325 };

1326}

1327 

1328static List<List<Long>> normalizeDragPath(List<ComputerAction.Drag.Path> path) {

1329 return path.stream().map(point -> List.of(point.x(), point.y())).toList();

1330}

1331 

1332static List<Integer> scrollButtons(long x, long y) {

1333 var buttons = new ArrayList<Integer>();

1334 for (long[] direction : new long[][] {{y, 4, 5}, {x, 6, 7}}) {

1335 if (direction[0] == 0) continue;

1336 int button = (int) (direction[0] < 0 ? direction[1] : direction[2]);

1337 int clicks = Math.max(1, (int) Math.abs(Math.rint(direction[0] / 100.0)));

1338 for (int i = 0; i < clicks; i++) buttons.add(button);

1339 }

1340 return buttons;

1341}

1342```

1343 

1163```ruby1344```ruby

1164def normalize_xdotool_key(key)1345def normalize_xdotool_key(key)

1165 names = {1346 names = {


1394 raise ValueError(f"Unsupported action: {action.type}")1575 raise ValueError(f"Unsupported action: {action.type}")

1395```1576```

1396 1577 

1578```java

1579import com.microsoft.playwright.*;

1580import com.microsoft.playwright.options.*;

1581import com.openai.core.ObjectMappers;

1582import com.openai.models.responses.ComputerAction;

1583import java.nio.file.*;

1584import java.util.*;

1585 

1586 

1587 

1588static void handleComputerActions(Page page, List<ComputerAction> actions) {

1589 for (var action : actions) {

1590 List<String> keys = List.of();

1591 Runnable operation;

1592 if (action.isClick()) {

1593 var click = action.asClick();

1594 keys = click.keys().orElse(List.of());

1595 operation =

1596 () ->

1597 page.mouse()

1598 .click(

1599 click.x(),

1600 click.y(),

1601 new Mouse.ClickOptions()

1602 .setButton(normalizeButton(click.button().toString())));

1603 } else if (action.isDoubleClick()) {

1604 var click = action.asDoubleClick();

1605 keys = click.keys().orElse(List.of());

1606 operation = () -> page.mouse().dblclick(click.x(), click.y());

1607 } else if (action.isMove()) {

1608 var move = action.asMove();

1609 keys = move.keys().orElse(List.of());

1610 operation = () -> page.mouse().move(move.x(), move.y());

1611 } else if (action.isDrag()) {

1612 var drag = action.asDrag();

1613 keys = drag.keys().orElse(List.of());

1614 var path = normalizeDragPath(drag.path());

1615 if (path.size() < 2)

1616 throw new IllegalArgumentException("Drag requires at least two points");

1617 operation =

1618 () -> {

1619 page.mouse().move(path.get(0).get(0), path.get(0).get(1));

1620 page.mouse().down();

1621 try {

1622 for (var point : path.subList(1, path.size()))

1623 page.mouse().move(point.get(0), point.get(1));

1624 } finally {

1625 page.mouse().up();

1626 }

1627 };

1628 } else if (action.isScroll()) {

1629 var scroll = action.asScroll();

1630 keys = scroll.keys().orElse(List.of());

1631 operation =

1632 () -> {

1633 page.mouse().move(scroll.x(), scroll.y());

1634 page.mouse().wheel(scroll.scrollX(), scroll.scrollY());

1635 };

1636 } else if (action.isKeypress()) {

1637 page.keyboard()

1638 .press(

1639 String.join(

1640 "+",

1641 action.asKeypress().keys().stream().map(key -> normalizeKey(key)).toList()));

1642 continue;

1643 } else if (action.isType()) {

1644 page.keyboard().type(action.asType().text());

1645 continue;

1646 } else if (action.isWait()) {

1647 page.waitForTimeout(2000);

1648 continue;

1649 } else if (action.isScreenshot()) {

1650 continue; // The caller captures the page after processing actions.

1651 } else throw new IllegalArgumentException("Unsupported computer action");

1652 if (!keys.isEmpty()) throw new IllegalArgumentException("Use the modifier-aware handler");

1653 operation.run();

1654 }

1655}

1656```

1657 

1397```ruby1658```ruby

1398def perform_browser_action(page, action)1659def perform_browser_action(page, action)

1399 case action.type1660 case action.type


1684 raise ValueError(f"Unsupported action: {action.type}")1945 raise ValueError(f"Unsupported action: {action.type}")

1685```1946```

1686 1947 

1948```java

1949import com.openai.core.ObjectMappers;

1950import com.openai.models.responses.ComputerAction;

1951import java.nio.charset.StandardCharsets;

1952import java.nio.file.*;

1953import java.util.*;

1954 

1955 

1956 

1957interface Operation {

1958 void run() throws Exception;

1959}

1960 

1961static void handleComputerActions(VM vm, List<ComputerAction> actions) throws Exception {

1962 for (var action : actions) {

1963 List<String> keys = List.of();

1964 Operation operation;

1965 if (action.isClick()) {

1966 var click = action.asClick();

1967 keys = click.keys().orElse(List.of());

1968 operation =

1969 () ->

1970 xdotool(

1971 vm,

1972 "mousemove",

1973 "--sync",

1974 Long.toString(click.x()),

1975 Long.toString(click.y()),

1976 "click",

1977 Integer.toString(normalizeButton(click.button().toString())));

1978 } else if (action.isDoubleClick()) {

1979 var click = action.asDoubleClick();

1980 keys = click.keys().orElse(List.of());

1981 operation =

1982 () ->

1983 xdotool(

1984 vm,

1985 "mousemove",

1986 "--sync",

1987 Long.toString(click.x()),

1988 Long.toString(click.y()),

1989 "click",

1990 "--repeat",

1991 "2",

1992 "--delay",

1993 "100",

1994 "1");

1995 } else if (action.isMove()) {

1996 var move = action.asMove();

1997 keys = move.keys().orElse(List.of());

1998 operation =

1999 () ->

2000 xdotool(

2001 vm, "mousemove", "--sync", Long.toString(move.x()), Long.toString(move.y()));

2002 } else if (action.isDrag()) {

2003 var drag = action.asDrag();

2004 keys = drag.keys().orElse(List.of());

2005 var path = normalizeDragPath(drag.path());

2006 if (path.size() < 2)

2007 throw new IllegalArgumentException("Drag requires at least two points");

2008 operation =

2009 () -> {

2010 xdotool(

2011 vm,

2012 "mousemove",

2013 "--sync",

2014 path.get(0).get(0).toString(),

2015 path.get(0).get(1).toString(),

2016 "mousedown",

2017 "1");

2018 try {

2019 for (var point : path.subList(1, path.size()))

2020 xdotool(

2021 vm, "mousemove", "--sync", point.get(0).toString(), point.get(1).toString());

2022 } finally {

2023 xdotool(vm, "mouseup", "1");

2024 }

2025 };

2026 } else if (action.isScroll()) {

2027 var scroll = action.asScroll();

2028 keys = scroll.keys().orElse(List.of());

2029 operation =

2030 () -> {

2031 xdotool(

2032 vm, "mousemove", "--sync", Long.toString(scroll.x()), Long.toString(scroll.y()));

2033 for (int button : scrollButtons(scroll.scrollX(), scroll.scrollY()))

2034 xdotool(vm, "click", Integer.toString(button));

2035 };

2036 } else if (action.isKeypress()) {

2037 xdotool(

2038 vm,

2039 "key",

2040 String.join(

2041 "+", action.asKeypress().keys().stream().map(key -> normalizeKey(key)).toList()));

2042 continue;

2043 } else if (action.isType()) {

2044 xdotool(vm, "type", "--clearmodifiers", "--", action.asType().text());

2045 continue;

2046 } else if (action.isWait()) {

2047 Thread.sleep(2000);

2048 continue;

2049 } else if (action.isScreenshot()) {

2050 continue;

2051 } else throw new IllegalArgumentException("Unsupported computer action");

2052 if (!keys.isEmpty()) throw new IllegalArgumentException("Use the modifier-aware handler");

2053 operation.run();

2054 }

2055}

2056```

2057 

1687```ruby2058```ruby

1688def run_xdotool(vm, *args)2059def run_xdotool(vm, *args)

1689 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })2060 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })


1747 2118 

1748 2119 

1749 2120 

1750Mouse actions can include an optional `keys` array for modifier-assisted workflows such as `Ctrl`+click to open a link in a new tab or `Shift`+click to extend a selection. When `keys` is present on `click`, `double_click`, `drag`, `move`, or `scroll`, hold those modifiers for the duration of the mouse action, then release them before continuing to the next action.2121Mouse actions can include an optional `keys` array for modifier-assisted workflows such as `Ctrl`+click to open a link in a new tab or `Shift`+click to extend a selection. When `keys` is present on `click`, `double_click`, `drag`, `move`, or `scroll`, hold those modifiers throughout the mouse action, then release them before continuing to the next action.

1751 2122 

1752You may also need to map model-emitted key names such as `CTRL`, `ALT`, `META`, and `ARROWLEFT` to the names your runtime expects.2123You may also need to map model-emitted key names such as `CTRL`, `ALT`, `META`, and `ARROWLEFT` to the names your runtime expects.

1753 2124 


1964 raise ValueError(f"Unsupported action: {action.type}")2335 raise ValueError(f"Unsupported action: {action.type}")

1965```2336```

1966 2337 

2338```java

2339import com.microsoft.playwright.*;

2340import com.microsoft.playwright.options.*;

2341import com.openai.core.ObjectMappers;

2342import com.openai.models.responses.ComputerAction;

2343import java.nio.file.*;

2344import java.util.*;

2345 

2346 

2347 

2348static void withModifiers(Page page, List<String> keys, Runnable callback) {

2349 var pressed = new ArrayList<String>();

2350 try {

2351 for (String key : keys) {

2352 String normalized = normalizeKey(key);

2353 page.keyboard().down(normalized);

2354 pressed.add(normalized);

2355 }

2356 callback.run();

2357 } finally {

2358 Collections.reverse(pressed);

2359 for (String key : pressed) page.keyboard().up(key);

2360 }

2361}

2362 

2363static void handleComputerActions(Page page, List<ComputerAction> actions) {

2364 for (var action : actions) {

2365 List<String> keys = List.of();

2366 Runnable operation;

2367 if (action.isClick()) {

2368 var click = action.asClick();

2369 keys = click.keys().orElse(List.of());

2370 operation =

2371 () ->

2372 page.mouse()

2373 .click(

2374 click.x(),

2375 click.y(),

2376 new Mouse.ClickOptions()

2377 .setButton(normalizeButton(click.button().toString())));

2378 } else if (action.isDoubleClick()) {

2379 var click = action.asDoubleClick();

2380 keys = click.keys().orElse(List.of());

2381 operation = () -> page.mouse().dblclick(click.x(), click.y());

2382 } else if (action.isMove()) {

2383 var move = action.asMove();

2384 keys = move.keys().orElse(List.of());

2385 operation = () -> page.mouse().move(move.x(), move.y());

2386 } else if (action.isDrag()) {

2387 var drag = action.asDrag();

2388 keys = drag.keys().orElse(List.of());

2389 var path = normalizeDragPath(drag.path());

2390 if (path.size() < 2)

2391 throw new IllegalArgumentException("Drag requires at least two points");

2392 operation =

2393 () -> {

2394 page.mouse().move(path.get(0).get(0), path.get(0).get(1));

2395 page.mouse().down();

2396 try {

2397 for (var point : path.subList(1, path.size()))

2398 page.mouse().move(point.get(0), point.get(1));

2399 } finally {

2400 page.mouse().up();

2401 }

2402 };

2403 } else if (action.isScroll()) {

2404 var scroll = action.asScroll();

2405 keys = scroll.keys().orElse(List.of());

2406 operation =

2407 () -> {

2408 page.mouse().move(scroll.x(), scroll.y());

2409 page.mouse().wheel(scroll.scrollX(), scroll.scrollY());

2410 };

2411 } else if (action.isKeypress()) {

2412 page.keyboard()

2413 .press(

2414 String.join(

2415 "+",

2416 action.asKeypress().keys().stream().map(key -> normalizeKey(key)).toList()));

2417 continue;

2418 } else if (action.isType()) {

2419 page.keyboard().type(action.asType().text());

2420 continue;

2421 } else if (action.isWait()) {

2422 page.waitForTimeout(2000);

2423 continue;

2424 } else if (action.isScreenshot()) {

2425 continue; // The caller captures the page after processing actions.

2426 } else throw new IllegalArgumentException("Unsupported computer action");

2427 withModifiers(page, keys, operation);

2428 }

2429}

2430```

2431 

1967```ruby2432```ruby

1968def with_modifiers(page, keys)2433def with_modifiers(page, keys)

1969 pressed = []2434 pressed = []


2288 raise ValueError(f"Unsupported action: {action.type}")2753 raise ValueError(f"Unsupported action: {action.type}")

2289```2754```

2290 2755 

2756```java

2757import com.openai.core.ObjectMappers;

2758import com.openai.models.responses.ComputerAction;

2759import java.nio.charset.StandardCharsets;

2760import java.nio.file.*;

2761import java.util.*;

2762 

2763 

2764 

2765interface Operation {

2766 void run() throws Exception;

2767}

2768 

2769static void withModifiers(VM vm, List<String> keys, Operation callback) throws Exception {

2770 var pressed = new ArrayList<String>();

2771 try {

2772 for (String key : keys) {

2773 String normalized = normalizeKey(key);

2774 xdotool(vm, "keydown", normalized);

2775 pressed.add(normalized);

2776 }

2777 callback.run();

2778 } finally {

2779 Collections.reverse(pressed);

2780 for (String key : pressed) xdotool(vm, "keyup", key);

2781 }

2782}

2783 

2784static void handleComputerActions(VM vm, List<ComputerAction> actions) throws Exception {

2785 for (var action : actions) {

2786 List<String> keys = List.of();

2787 Operation operation;

2788 if (action.isClick()) {

2789 var click = action.asClick();

2790 keys = click.keys().orElse(List.of());

2791 operation =

2792 () ->

2793 xdotool(

2794 vm,

2795 "mousemove",

2796 "--sync",

2797 Long.toString(click.x()),

2798 Long.toString(click.y()),

2799 "click",

2800 Integer.toString(normalizeButton(click.button().toString())));

2801 } else if (action.isDoubleClick()) {

2802 var click = action.asDoubleClick();

2803 keys = click.keys().orElse(List.of());

2804 operation =

2805 () ->

2806 xdotool(

2807 vm,

2808 "mousemove",

2809 "--sync",

2810 Long.toString(click.x()),

2811 Long.toString(click.y()),

2812 "click",

2813 "--repeat",

2814 "2",

2815 "--delay",

2816 "100",

2817 "1");

2818 } else if (action.isMove()) {

2819 var move = action.asMove();

2820 keys = move.keys().orElse(List.of());

2821 operation =

2822 () ->

2823 xdotool(

2824 vm, "mousemove", "--sync", Long.toString(move.x()), Long.toString(move.y()));

2825 } else if (action.isDrag()) {

2826 var drag = action.asDrag();

2827 keys = drag.keys().orElse(List.of());

2828 var path = normalizeDragPath(drag.path());

2829 if (path.size() < 2)

2830 throw new IllegalArgumentException("Drag requires at least two points");

2831 operation =

2832 () -> {

2833 xdotool(

2834 vm,

2835 "mousemove",

2836 "--sync",

2837 path.get(0).get(0).toString(),

2838 path.get(0).get(1).toString(),

2839 "mousedown",

2840 "1");

2841 try {

2842 for (var point : path.subList(1, path.size()))

2843 xdotool(

2844 vm, "mousemove", "--sync", point.get(0).toString(), point.get(1).toString());

2845 } finally {

2846 xdotool(vm, "mouseup", "1");

2847 }

2848 };

2849 } else if (action.isScroll()) {

2850 var scroll = action.asScroll();

2851 keys = scroll.keys().orElse(List.of());

2852 operation =

2853 () -> {

2854 xdotool(

2855 vm, "mousemove", "--sync", Long.toString(scroll.x()), Long.toString(scroll.y()));

2856 for (int button : scrollButtons(scroll.scrollX(), scroll.scrollY()))

2857 xdotool(vm, "click", Integer.toString(button));

2858 };

2859 } else if (action.isKeypress()) {

2860 xdotool(

2861 vm,

2862 "key",

2863 String.join(

2864 "+", action.asKeypress().keys().stream().map(key -> normalizeKey(key)).toList()));

2865 continue;

2866 } else if (action.isType()) {

2867 xdotool(vm, "type", "--clearmodifiers", "--", action.asType().text());

2868 continue;

2869 } else if (action.isWait()) {

2870 Thread.sleep(2000);

2871 continue;

2872 } else if (action.isScreenshot()) {

2873 continue;

2874 } else throw new IllegalArgumentException("Unsupported computer action");

2875 withModifiers(vm, keys, operation);

2876 }

2877}

2878```

2879 

2291```ruby2880```ruby

2292def with_modifiers(vm, keys)2881def with_modifiers(vm, keys)

2293 pressed = []2882 pressed = []


2738 return page.screenshot(type="png")3327 return page.screenshot(type="png")

2739```3328```

2740 3329 

3330```java

3331import com.microsoft.playwright.*;

3332import com.microsoft.playwright.options.*;

3333import com.openai.core.ObjectMappers;

3334import java.nio.file.*;

3335import java.util.*;

3336 

3337 

3338 

3339static byte[] captureScreenshot(Page page) {

3340 return page.screenshot(new Page.ScreenshotOptions().setType(ScreenshotType.PNG));

3341}

3342```

3343 

2741```ruby3344```ruby

2742def capture_screenshot(page)3345def capture_screenshot(page)

2743 page.screenshot(type: "png")3346 page.screenshot(type: "png")


2778 )3381 )

2779```3382```

2780 3383 

3384```java

3385import com.openai.core.ObjectMappers;

3386import java.nio.file.*;

3387import java.util.*;

3388 

3389 

3390 

3391static byte[] captureScreenshot(VM vm) throws Exception {

3392 return dockerExec(

3393 vm.containerName(),

3394 "import",

3395 List.of("-window", "root", "png:-"),

3396 Map.of("DISPLAY", vm.display()));

3397}

3398```

3399 

2781```ruby3400```ruby

2782def capture_screenshot(vm)3401def capture_screenshot(vm)

2783 docker_exec(3402 docker_exec(


2813 3432 

2814The examples here use ordinary function tools named `exec_js` and `exec_py`. Their `code` argument contains the generated script. Your application sends that script to your execution service, then returns its text and image outputs to the model. If the model asks for clarification instead of returning a tool call, surface that question to the user before continuing.3433The examples here use ordinary function tools named `exec_js` and `exec_py`. Their `code` argument contains the generated script. Your application sends that script to your execution service, then returns its text and image outputs to the model. If the model asks for clarification instead of returning a tool call, surface that question to the user before continuing.

2815 3434 

2816The code runtime can be temporary or persistent. If you need to resume the same browser session, preserve that session separately from individual scripts. A persistent runtime can also retain variables between tool calls. Tell the model which objects, helpers, and state are available.3435The code runtime can be temporary or persistent. If you need to continue the same browser session, preserve that session separately from individual scripts. A persistent runtime can also retain variables between tool calls. Tell the model which objects, helpers, and state are available.

2817 3436 

2818Provide only the capabilities the task requires:3437Provide only the capabilities the task requires:

2819 3438 


2852go get github.com/openai/openai-go/v3@v3.70.03471go get github.com/openai/openai-go/v3@v3.70.0

2853```3472```

2854 3473 

2855For Java 17 or later, add these dependencies to your Maven `pom.xml`:3474For Java, add these dependencies to your Maven `pom.xml`:

2856 3475 

2857```xml3476```xml

2858<dependencies>3477<dependencies>


3232 3851 

3233Check permissions before executing an action. For an action batch, stop before the first action that needs confirmation. For generated code, enforce permissions in the exposed helpers and runtime; a single script can perform many actions. Instructions to the model complement these controls but do not replace them.3852Check permissions before executing an action. For an action batch, stop before the first action that needs confirmation. For generated code, enforce permissions in the exposed helpers and runtime; a single script can perform many actions. Instructions to the model complement these controls but do not replace them.

3234 3853 

3235Let the agent complete safe work before pausing at the point of risk. Explain the proposed action, obtain any required consent, and resume only the approved work. If the user declines, do not execute the request. Your integration must communicate what did and did not run before asking the model to continue.3854Let the agent complete safe work before pausing at the point of risk. Explain the proposed action, obtain any required consent, and continue only the approved work. If the user declines, do not execute the request. Your integration must communicate what did and did not run before asking the model to continue.

3236 3855 

3237<a id="keep-a-human-in-the-loop"></a>3856<a id="keep-a-human-in-the-loop"></a>

3238 3857 

Details

2024}2024}

2025```2025```

2026 2026 

2027```java

2028import com.fasterxml.jackson.databind.ObjectMapper;

2029import java.nio.charset.StandardCharsets;

2030import java.nio.file.*;

2031import java.util.Map;

2032import java.util.concurrent.TimeUnit;

2033 

2034String command = args.length > 0 ? args[0] : "printf shell-executor-ready";

2035double timeoutSeconds = args.length > 1 ? Double.parseDouble(args[1]) : 1.0;

2036System.out.println(new ObjectMapper().writeValueAsString(execute(command, timeoutSeconds)));

2037 

2038// Linux host example: setsid gives the shell and its descendants an owned

2039// process group. Only execute commands approved by your application policy.

2040static Map<String, Object> execute(String command, double timeoutSeconds) throws Exception {

2041 if (!Double.isFinite(timeoutSeconds) || timeoutSeconds <= 0)

2042 throw new IllegalArgumentException("Timeout must be positive and finite");

2043 Path directory = Files.createTempDirectory("shell-example-");

2044 Path stdout = directory.resolve("stdout"), stderr = directory.resolve("stderr");

2045 Process process = null;

2046 try {

2047 process =

2048 new ProcessBuilder("setsid", "sh", "-c", command)

2049 .redirectOutput(stdout.toFile())

2050 .redirectError(stderr.toFile())

2051 .start();

2052 process.getOutputStream().close();

2053 long deadline = System.nanoTime() + (long) (timeoutSeconds * 1_000_000_000L);

2054 boolean timedOut = false;

2055 boolean outputLimit = false;

2056 while (process.isAlive() || groupExists(process.pid())) {

2057 timedOut = System.nanoTime() >= deadline;

2058 outputLimit = Files.size(stdout) > 1024 * 1024 || Files.size(stderr) > 1024 * 1024;

2059 if (timedOut || outputLimit) break;

2060 Thread.sleep(10);

2061 }

2062 // A fast command may finish between polls after exceeding the output cap.

2063 outputLimit |= Files.size(stdout) > 1024 * 1024 || Files.size(stderr) > 1024 * 1024;

2064 int exitCode = process.isAlive() ? -1 : process.exitValue();

2065 if (timedOut || outputLimit) {

2066 signalGroup(process.pid(), "TERM");

2067 process.waitFor(100, TimeUnit.MILLISECONDS);

2068 signalGroup(process.pid(), "KILL");

2069 process.waitFor();

2070 }

2071 if (outputLimit) exitCode = 1;

2072 return Map.of(

2073 "stdout",

2074 readOutput(stdout),

2075 "stderr",

2076 readOutput(stderr),

2077 "exit_code",

2078 exitCode,

2079 "timed_out",

2080 timedOut);

2081 } finally {

2082 if (process != null) {

2083 signalGroup(process.pid(), "KILL");

2084 process.waitFor();

2085 }

2086 Files.deleteIfExists(stdout);

2087 Files.deleteIfExists(stderr);

2088 Files.deleteIfExists(directory);

2089 }

2090}

2091 

2092static boolean groupExists(long pid) throws Exception {

2093 return new ProcessBuilder("kill", "-0", "--", "-" + pid)

2094 .redirectOutput(ProcessBuilder.Redirect.DISCARD)

2095 .redirectError(ProcessBuilder.Redirect.DISCARD)

2096 .start()

2097 .waitFor()

2098 == 0;

2099}

2100 

2101static void signalGroup(long pid, String signal) throws Exception {

2102 new ProcessBuilder("kill", "-" + signal, "--", "-" + pid)

2103 .redirectOutput(ProcessBuilder.Redirect.DISCARD)

2104 .redirectError(ProcessBuilder.Redirect.DISCARD)

2105 .start()

2106 .waitFor();

2107}

2108 

2109static String readOutput(Path path) throws Exception {

2110 try (var input = Files.newInputStream(path)) {

2111 return new String(input.readNBytes(1024 * 1024), StandardCharsets.UTF_8);

2112 }

2113}

2114```

2115 

2027```ruby2116```ruby

2028require "open3"2117require "open3"

2029 2118 

Details

1514tools := realtime.RealtimeToolsConfigParam{{OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("lookup_account"), Description: openai.String("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."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"email": map[string]any{"type": "string"}, "phone": map[string]any{"type": "string"}}, "additionalProperties": false}}}, {OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("check_outage"), Description: openai.String("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."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"service_address": map[string]any{"type": "string"}}, "required": []any{"service_address"}, "additionalProperties": false}}}}1514tools := realtime.RealtimeToolsConfigParam{{OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("lookup_account"), Description: openai.String("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."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"email": map[string]any{"type": "string"}, "phone": map[string]any{"type": "string"}}, "additionalProperties": false}}}, {OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("check_outage"), Description: openai.String("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."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"service_address": map[string]any{"type": "string"}}, "required": []any{"service_address"}, "additionalProperties": false}}}}

1515```1515```

1516 1516 

1517```java

1518import com.openai.client.okhttp.OkHttpClient;

1519import com.openai.core.*;

1520import com.openai.helpers.*;

1521import com.openai.models.realtime.*;

1522import java.util.*;

1523 

1524var http = OkHttpClient.builder().build();

1525var options = ClientOptions.builder().fromEnv().httpClient(http).build();

1526try (http;

1527 var connection =

1528 RealtimeConnection.connect(

1529 options,

1530 RealtimeWebSocketOptions.builder().model("gpt-realtime-1.5").build())) {

1531 var tools =

1532 List.of(

1533 RealtimeFunctionTool.builder()

1534 .type(RealtimeFunctionTool.Type.FUNCTION)

1535 .name("lookup_account")

1536 .description(

1537 "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\u2019ll pull up your account using the email on file.\n- Let me look up your account by {email} now.\n- I\u2019m fetching the account linked to {phone} to verify access.\n- One moment\u2014I\u2019m opening your account details.")

1538 .parameters(

1539 JsonValue.from(

1540 Map.ofEntries(

1541 Map.entry("type", "object"),

1542 Map.entry(

1543 "properties",

1544 Map.ofEntries(

1545 Map.entry(

1546 "email", Map.ofEntries(Map.entry("type", "string"))),

1547 Map.entry(

1548 "phone", Map.ofEntries(Map.entry("type", "string"))))),

1549 Map.entry("additionalProperties", false))))

1550 .build(),

1551 RealtimeFunctionTool.builder()

1552 .type(RealtimeFunctionTool.Type.FUNCTION)

1553 .name("check_outage")

1554 .description(

1555 "Check for network outages affecting a given service address and return status and ETA if applicable.\n\nPreamble sample phrases:\n- I\u2019ll check for any outages at {service_address} right now.\n- Let me look up network status for your area.\n- I\u2019m checking whether there\u2019s an active outage impacting your address.\n- One sec\u2014verifying service status and any posted ETA.")

1556 .parameters(

1557 JsonValue.from(

1558 Map.ofEntries(

1559 Map.entry("type", "object"),

1560 Map.entry(

1561 "properties",

1562 Map.ofEntries(

1563 Map.entry(

1564 "service_address",

1565 Map.ofEntries(Map.entry("type", "string"))))),

1566 Map.entry("required", List.of("service_address")),

1567 Map.entry("additionalProperties", false))))

1568 .build());

1569 var session = RealtimeSessionCreateRequest.builder();

1570 for (var tool : tools) session.addTool(tool);

1571 update(connection, session.build());

1572}

1573 

1574static void update(RealtimeConnection connection, RealtimeSessionCreateRequest session) {

1575 connection.send(

1576 RealtimeClientEvent.ofSessionUpdate(SessionUpdateEvent.builder().session(session).build()));

1577 while (true) {

1578 var event = connection.receive();

1579 if (event.error().isPresent())

1580 throw new IllegalStateException(event.error().orElseThrow().toString());

1581 if (event.sessionUpdated().isPresent()) return;

1582 }

1583}

1584```

1585 

1517```ruby1586```ruby

1518tools = [1587tools = [

1519 {1588 {


2047 2116 

2048#### Example2117#### Example

2049 2118 

2050Update the conversation state2119Build the conversation state

2051 2120 

2052```typescript2121```typescript

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


2252}2321}

2253```2322```

2254 2323 

2324```java

2325import com.openai.core.*;

2326import com.openai.models.realtime.*;

2327import java.util.*;

2328 

2329enum State {

2330 VERIFY,

2331 RESOLVE

2332}

2333 

2334static final Map<String, List<String>> TRANSITIONS =

2335 Map.ofEntries(Map.entry("verify", List.of("resolve")), Map.entry("resolve", List.of()));

2336static final Map<String, String> INSTRUCTIONS =

2337 Map.ofEntries(

2338 Map.entry(

2339 "verify",

2340 "# 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\u2026 Is that correct?').\nExit when: Account ID is returned.\nWhen exit is satisfied: call set_conversation_state(next_state=\"resolve\")."),

2341 Map.entry(

2342 "resolve",

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

2344static final Map<String, List<Map<String, Object>>> TOOLS =

2345 Map.ofEntries(

2346 Map.entry(

2347 "verify",

2348 List.of(

2349 Map.ofEntries(

2350 Map.entry("type", "function"),

2351 Map.entry("name", "lookup_account"),

2352 Map.entry("description", "Fetch account by email or phone."),

2353 Map.entry(

2354 "parameters",

2355 Map.ofEntries(

2356 Map.entry("type", "object"),

2357 Map.entry(

2358 "properties",

2359 Map.ofEntries(

2360 Map.entry(

2361 "email_or_phone",

2362 Map.ofEntries(Map.entry("type", "string"))))),

2363 Map.entry("required", List.of("email_or_phone"))))))),

2364 Map.entry(

2365 "resolve",

2366 List.of(

2367 Map.ofEntries(

2368 Map.entry("type", "function"),

2369 Map.entry("name", "schedule_technician"),

2370 Map.entry("description", "Book a technician visit."),

2371 Map.entry(

2372 "parameters",

2373 Map.ofEntries(

2374 Map.entry("type", "object"),

2375 Map.entry(

2376 "properties",

2377 Map.ofEntries(

2378 Map.entry(

2379 "account_id", Map.ofEntries(Map.entry("type", "string"))),

2380 Map.entry(

2381 "window",

2382 Map.ofEntries(

2383 Map.entry("type", "string"),

2384 Map.entry(

2385 "enum", List.of("10-12 ET", "14-16 ET")))))),

2386 Map.entry("required", List.of("account_id", "window"))))))));

2387 

2388// For transitions, call this only after your application confirms the current state

2389// has met its exit conditions. Send the result in a session.update event.

2390static RealtimeSessionCreateRequest buildSession(State state) {

2391 String name = state.name().toLowerCase(java.util.Locale.ROOT);

2392 var session = RealtimeSessionCreateRequest.builder().instructions(INSTRUCTIONS.get(name));

2393 for (var definition : TOOLS.get(name))

2394 session.addTool(JsonValue.from(definition).convert(RealtimeFunctionTool.class));

2395 var allowed = TRANSITIONS.get(name);

2396 String readable =

2397 allowed.isEmpty() ? "no further states (terminal)" : String.join(", ", allowed);

2398 session.addTool(

2399 RealtimeFunctionTool.builder()

2400 .type(RealtimeFunctionTool.Type.FUNCTION)

2401 .name("set_conversation_state")

2402 .description(

2403 "Switch the conversation phase. Current: '"

2404 + name

2405 + "'. You may switch only to: "

2406 + readable

2407 + ". Call this AFTER exit criteria are satisfied.")

2408 .parameters(

2409 JsonValue.from(

2410 Map.of(

2411 "type",

2412 "object",

2413 "properties",

2414 Map.of("next_state", Map.of("type", "string", "enum", allowed)),

2415 "required",

2416 List.of("next_state"))))

2417 .build());

2418 return session.build();

2419}

2420```

2421 

2255```ruby2422```ruby

2256TRANSITIONS = {2423TRANSITIONS = {

2257 "verify" => ["resolve"],2424 "verify" => ["resolve"],

Details

424}424}

425```425```

426 426 

427```java

428import com.openai.client.okhttp.OkHttpClient;

429import com.openai.core.ClientOptions;

430import com.openai.helpers.RealtimeConnection;

431import com.openai.helpers.RealtimeWebSocketOptions;

432import com.openai.models.realtime.*;

433import java.util.concurrent.TimeUnit;

434 

435var http = OkHttpClient.builder().build();

436var options = ClientOptions.builder().fromEnv().httpClient(http).build();

437 

438// Obtain callId from the existing call's Location header or SIP webhook.

439try (http;

440 var connection =

441 RealtimeConnection.connect(

442 options, RealtimeWebSocketOptions.builder().callId(callId).build())) {

443 connection.send(

444 RealtimeClientEvent.ofSessionUpdate(

445 SessionUpdateEvent.builder()

446 .session(

447 RealtimeSessionCreateRequest.builder()

448 .instructions("Be extra nice today!")

449 .build())

450 .build()));

451 long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);

452 while (true) {

453 var event =

454 connection

455 .receiveAsync()

456 .get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);

457 if (event.error().isPresent())

458 throw new IllegalStateException(event.error().orElseThrow().toString());

459 if (event.sessionUpdated().isPresent()) {

460 var session =

461 event.sessionUpdated().orElseThrow().session().realtimeSessionCreateRequest();

462 if (session.isEmpty()

463 || !session

464 .orElseThrow()

465 .instructions()

466 .filter("Be extra nice today!"::equals)

467 .isPresent()) throw new IllegalStateException("Session update was not applied");

468 System.out.println("session.updated");

469 break;

470 }

471 }

472} finally {

473 options.close();

474}

475```

476 

427```ruby477```ruby

428require "openai"478require "openai"

429 479 

Details

38 38 

39Save the server example in a new directory and set `OPENAI_API_KEY` in its environment. For TypeScript, use Node.js 22.6 or later, save the example as `server.ts`, and run `npm install openai express` followed by `npm pkg set type=module`. For Python, install `openai`. This example binds to `127.0.0.1`, accepts session requests from `http://localhost:3000`, and serves `index.html` from the directory where you run it.39Save the server example in a new directory and set `OPENAI_API_KEY` in its environment. For TypeScript, use Node.js 22.6 or later, save the example as `server.ts`, and run `npm install openai express` followed by `npm pkg set type=module`. For Python, install `openai`. This example binds to `127.0.0.1`, accepts session requests from `http://localhost:3000`, and serves `index.html` from the directory where you run it.

40 40 

41For Go, save the example as `main.go`, initialize a module with `go mod init live-demo`, and install `github.com/openai/openai-go/v3@v3.85.1` with `go get`. Run `go run .` with Go 1.26 or later. For Java, use Java 17 or later, add the Maven dependency `com.openai:openai-java:4.95.0`, and run the `LiveConnectionWebrtcExample` class. For Ruby 3.3 or later, install `openai` 0.110.0 and `webrick` with `gem install openai -v 0.110.0` and `gem install webrick`, save the example as `server.rb`, and run `ruby server.rb`.41For Go, save the example as `main.go`, initialize a module with `go mod init live-demo`, and install `github.com/openai/openai-go/v3@v3.85.1` with `go get`. Run `go run .` with Go 1.26 or later. For Java, add the Maven dependency `com.openai:openai-java:4.95.0` and run the `LiveConnectionWebrtcExample` class. For Ruby 3.3 or later, install `openai` 0.110.0 and `webrick` with `gem install openai -v 0.110.0` and `gem install webrick`, save the example as `server.rb`, and run `ruby server.rb`.

42 42 

43Choose a server language below; each variant serves `index.html` and the same `/api/session` endpoint on port 3000. Use an SDK version with Live support. Run only one variant at a time.43Choose a server language below; each variant serves `index.html` and the same `/api/session` endpoint on port 3000. Use an SDK version with Live support. Run only one variant at a time.

44 44 


780}780}

781```781```

782 782 

783```java

784import com.openai.client.okhttp.OpenAIOkHttpClient;

785import com.openai.models.realtime.*;

786import com.openai.models.realtime.calls.CallCreateParams;

787import com.sun.net.httpserver.HttpServer;

788import java.net.InetSocketAddress;

789import java.nio.charset.StandardCharsets;

790 

791var client = OpenAIOkHttpClient.fromEnv();

792 

793// Authenticate your application's users before exposing this server publicly.

794var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 3000), 0);

795server.createContext(

796 "/session",

797 exchange -> {

798 int status = 200;

799 byte[] body;

800 exchange.getResponseHeaders().set("Content-Type", "application/sdp");

801 try {

802 if (!exchange.getRequestMethod().equals("POST")) {

803 status = 405;

804 body = "Method not allowed".getBytes(StandardCharsets.UTF_8);

805 } else {

806 byte[] offer = exchange.getRequestBody().readNBytes(1024 * 1024 + 1);

807 if (offer.length > 1024 * 1024)

808 throw new IllegalArgumentException("SDP offer is too large");

809 try (var response =

810 client

811 .realtime()

812 .calls()

813 .withRawResponse()

814 .create(

815 CallCreateParams.builder()

816 .sdp(new String(offer, StandardCharsets.UTF_8))

817 .session(

818 RealtimeSessionCreateRequest.builder()

819 .model("gpt-realtime-2.1")

820 .audio(

821 RealtimeAudioConfig.builder()

822 .output(

823 RealtimeAudioConfigOutput.builder()

824 .voice("marin")

825 .build())

826 .build())

827 .build())

828 .putAdditionalHeader("OpenAI-Safety-Identifier", "hashed-user-id")

829 .build())) {

830 status = response.statusCode();

831 body = response.body().readAllBytes();

832 response.headers().values("Location").stream()

833 .findFirst()

834 .ifPresent(location -> exchange.getResponseHeaders().set("Location", location));

835 }

836 }

837 } catch (IllegalArgumentException error) {

838 status = 400;

839 body = "Invalid SDP offer".getBytes(StandardCharsets.UTF_8);

840 } catch (RuntimeException error) {

841 status = 502;

842 body = "Could not create session".getBytes(StandardCharsets.UTF_8);

843 }

844 if (status >= 400) exchange.getResponseHeaders().set("Content-Type", "text/plain");

845 exchange.sendResponseHeaders(status, body.length);

846 try (var output = exchange.getResponseBody()) {

847 output.write(body);

848 } finally {

849 exchange.close();

850 }

851 });

852Runtime.getRuntime()

853 .addShutdownHook(

854 new Thread(

855 () -> {

856 server.stop(0);

857 client.close();

858 }));

859server.start();

860```

861 

783```ruby862```ruby

784require "openai"863require "openai"

785require "webrick"864require "webrick"


971}1050}

972```1051```

973 1052 

1053```java

1054import com.openai.client.okhttp.OpenAIOkHttpClient;

1055import com.openai.core.ObjectMappers;

1056import com.openai.models.realtime.*;

1057import com.openai.models.realtime.clientsecrets.ClientSecretCreateParams;

1058import com.sun.net.httpserver.HttpServer;

1059import java.net.InetSocketAddress;

1060import java.nio.charset.StandardCharsets;

1061 

1062 

1063 

1064var client = OpenAIOkHttpClient.fromEnv();

1065// Authenticate your application's users before exposing this server publicly.

1066var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 3000), 0);

1067server.createContext(

1068 "/token",

1069 exchange -> {

1070 int status = 200;

1071 byte[] body;

1072 try {

1073 if (!exchange.getRequestMethod().equals("GET")) {

1074 status = 405;

1075 body = "{\"error\":\"Method not allowed\"}".getBytes(StandardCharsets.UTF_8);

1076 } else {

1077 var secret =

1078 client

1079 .realtime()

1080 .clientSecrets()

1081 .create(

1082 ClientSecretCreateParams.builder()

1083 .putAdditionalHeader("OpenAI-Safety-Identifier", "hashed-user-id")

1084 .session(

1085 RealtimeSessionCreateRequest.builder()

1086 .model("gpt-realtime-2.1")

1087 .audio(

1088 RealtimeAudioConfig.builder()

1089 .output(

1090 RealtimeAudioConfigOutput.builder()

1091 .voice("marin")

1092 .build())

1093 .build())

1094 .build())

1095 .build());

1096 body = ObjectMappers.jsonMapper().writeValueAsBytes(secret);

1097 }

1098 } catch (RuntimeException error) {

1099 status = 502;

1100 body =

1101 "{\"error\":\"Could not create client credential\"}"

1102 .getBytes(StandardCharsets.UTF_8);

1103 }

1104 exchange.getResponseHeaders().set("Content-Type", "application/json");

1105 exchange.getResponseHeaders().set("Cache-Control", "no-store");

1106 exchange.sendResponseHeaders(status, body.length);

1107 try (var output = exchange.getResponseBody()) {

1108 output.write(body);

1109 } finally {

1110 exchange.close();

1111 }

1112 });

1113Runtime.getRuntime()

1114 .addShutdownHook(

1115 new Thread(

1116 () -> {

1117 server.stop(0);

1118 client.close();

1119 }));

1120server.start();

1121```

1122 

974```ruby1123```ruby

975require "openai"1124require "openai"

976require "webrick"1125require "webrick"

Details

26 26 

27For Node.js 22.6 or later, install `openai` and `ws` with `npm install openai ws` and save the TypeScript example as `client.mts`. For Python on macOS or Linux, install `openai[realtime]` and save the Python example as `client.py`. Set `OPENAI_API_KEY` in the server environment. These examples require an SDK version with Live support. The example reads raw, mono PCM16 audio at 24 kHz from standard input and writes returned audio in the same format to standard output. Connect these streams to your application's audio capture and playback. Logs and transcript events go to standard error so they do not corrupt the audio stream.27For Node.js 22.6 or later, install `openai` and `ws` with `npm install openai ws` and save the TypeScript example as `client.mts`. For Python on macOS or Linux, install `openai[realtime]` and save the Python example as `client.py`. Set `OPENAI_API_KEY` in the server environment. These examples require an SDK version with Live support. The example reads raw, mono PCM16 audio at 24 kHz from standard input and writes returned audio in the same format to standard output. Connect these streams to your application's audio capture and playback. Logs and transcript events go to standard error so they do not corrupt the audio stream.

28 28 

29For Go, use Go 1.26 or later, save the example as `main.go`, initialize a module with `go mod init live-demo`, and install `github.com/openai/openai-go/v3@v3.85.1` with `go get`. For Java, use Java 17 or later, add the Maven dependency `com.openai:openai-java:4.95.0`, and use the `LiveConnectionWebsocketExample` class. For Ruby 3.3 or later, install the SDK with `gem install openai -v 0.110.0`, install its WebSocket dependency with `gem install async-websocket`, and save the example as `client.rb`.29For Go, use Go 1.26 or later, save the example as `main.go`, initialize a module with `go mod init live-demo`, and install `github.com/openai/openai-go/v3@v3.85.1` with `go get`. For Java, add the Maven dependency `com.openai:openai-java:4.95.0` and use the `LiveConnectionWebsocketExample` class. For Ruby 3.3 or later, install the SDK with `gem install openai -v 0.110.0`, install its WebSocket dependency with `gem install async-websocket`, and save the example as `client.rb`.

30 30 

31```typescript31```typescript

32import OpenAI from "openai";32import OpenAI from "openai";


846 846 

847 847

848 848 

849 Use Java 17 or later with `com.openai:openai-java:4.75.1`.849 Use `com.openai:openai-java:4.75.1`.

850 850

851 851 

852 Connect with the OpenAI SDK (Java)852 Connect with the OpenAI SDK (Java)

Details

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.105.0`.19For Go, run `go get github.com/openai/openai-go/v3@v3.105.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` 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 

23In WebSocket mode, start each turn by sending a `response.create` event from the client. The payload mirrors the normal [Responses create body](https://developers.openai.com/api/reference/resources/responses/methods/create), except that transport-specific fields like `stream` and `background` are not used.23In WebSocket mode, start each turn by sending a `response.create` event from the client. The payload mirrors the normal [Responses create body](https://developers.openai.com/api/reference/resources/responses/methods/create), except that transport-specific fields like `stream` and `background` are not used.


783}783}

784```784```

785 785 

786```java

787import com.openai.client.okhttp.OpenAIOkHttpClient;

788import com.openai.core.JsonValue;

789import com.openai.models.responses.*;

790import java.util.*;

791 

792var client = OpenAIOkHttpClient.fromEnv();

793try {

794 var input =

795 List.of(

796 ResponseInputItem.ofEasyInputMessage(

797 EasyInputMessage.builder()

798 .role(EasyInputMessage.Role.USER)

799 .content("Find the failing test.")

800 .build()));

801 var compacted =

802 client

803 .responses()

804 .compact(

805 ResponseCompactParams.builder()

806 .model("gpt-6.2-astra")

807 .inputOfResponseInputItems(input)

808 .build());

809 var next = new ArrayList<ResponseInputItem>();

810 for (var item : compacted.output())

811 next.add(JsonValue.from(item).convert(ResponseInputItem.class));

812 next.add(

813 ResponseInputItem.ofEasyInputMessage(

814 EasyInputMessage.builder()

815 .role(EasyInputMessage.Role.USER)

816 .content("Continue from here.")

817 .build()));

818 try (var connection = client.responses().connect()) {

819 connection.send(

820 ResponsesClientEvent.ofResponseCreate(

821 ResponsesClientEvent.ResponseCreate.builder()

822 .model("gpt-6.2-astra")

823 .streamId("main")

824 .store(false)

825 .inputOfResponse(next)

826 .tools(List.of())

827 .build()));

828 var result = connection.finalResponse();

829 if (result.status().filter(ResponseStatus.COMPLETED::equals).isEmpty())

830 throw new IllegalStateException("Response did not complete");

831 result.output().stream()

832 .flatMap(item -> item.message().stream())

833 .flatMap(message -> message.content().stream())

834 .flatMap(content -> content.outputText().stream())

835 .forEach(text -> System.out.print(text.text()));

836 }

837} finally {

838 client.close();

839}

840```

841 

786```ruby842```ruby

787require "async"843require "async"

788require "openai"844require "openai"


1212}1268}

1213```1269```

1214 1270 

1271```java

1272import com.openai.client.okhttp.OpenAIOkHttpClient;

1273import com.openai.core.http.ResponseConnection;

1274import com.openai.models.responses.*;

1275import java.util.*;

1276 

1277var client = OpenAIOkHttpClient.fromEnv();

1278try (var connection = client.responses().connect();

1279 var planner = connection.lane("planner");

1280 var research = connection.lane("research");

1281 var critic = connection.lane("critic")) {

1282 send(planner, "planner", "Draft a deployment plan for a stateless API service.", null);

1283 send(research, "research", "List common deployment risks for a stateless API service.", null);

1284 var first = completed(planner);

1285 completed(research);

1286 send(critic, "critic", "Find gaps in this deployment plan.", first.id());

1287 // Let the fork load its parent before advancing the original lane's cache.

1288 while (true) {

1289 var event = critic.receive();

1290 if (event.error().isPresent()

1291 || event.responseFailed().isPresent()

1292 || event.responseIncomplete().isPresent())

1293 throw new IllegalStateException("Critic failed");

1294 if (event.responseInProgress().isPresent()) break;

1295 }

1296 send(planner, "planner", "Add rollback and monitoring steps to the plan.", first.id());

1297 completed(critic);

1298 completed(planner);

1299} finally {

1300 client.close();

1301}

1302 

1303static void send(ResponseConnection.Lane lane, String streamId, String text, String previous)

1304 throws Exception {

1305 var builder =

1306 ResponsesClientEvent.ResponseCreate.builder()

1307 .streamId(streamId)

1308 .model("gpt-6.2-astra")

1309 .store(false)

1310 .inputOfResponse(

1311 List.of(

1312 ResponseInputItem.ofEasyInputMessage(

1313 EasyInputMessage.builder()

1314 .role(EasyInputMessage.Role.USER)

1315 .content(text)

1316 .build())));

1317 if (previous != null) builder.previousResponseId(previous);

1318 var event = ResponsesClientEvent.ofResponseCreate(builder.build());

1319 long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10);

1320 while (true) {

1321 try {

1322 lane.send(event);

1323 return;

1324 } catch (com.openai.core.http.WebSocketWriteNotAttempted.Busy busy) {

1325 if (System.nanoTime() >= deadline) throw busy;

1326 Thread.sleep(10);

1327 }

1328 }

1329}

1330 

1331static Response completed(ResponseConnection.Lane lane) {

1332 var response = lane.finalResponse();

1333 if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty())

1334 throw new IllegalStateException("Response did not complete");

1335 return response;

1336}

1337```

1338 

1215```ruby1339```ruby

1216require "async"1340require "async"

1217require "openai"1341require "openai"

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.111.0</version>180 <version>4.113.0</version>

181</dependency>181</dependency>

182```182```

183 183 

mcp.md +174 −3

Details

167 167 

168 168 

169 169 

170The following examples implement both `search` and `fetch` with an MCP SDK.170The examples below implement both the `search` and `fetch` tools. The Python example uses FastMCP. The Java example uses `com.openai:openai-java:4.105.0`, `io.modelcontextprotocol.sdk:mcp-core:1.1.5`, `io.modelcontextprotocol.sdk:mcp-json-jackson2:1.1.5`, and `org.eclipse.jetty.ee10:jetty-ee10-servlet:12.0.41`. Put the Java setup inside the `main` method of a server class, set `OPENAI_API_KEY`, and replace `vs_123` with your vector store ID. The Java server exposes its SSE endpoint at `/sse`.

171 171 

172 172 

173 173 

174#### Full MCP server implementation174#### Search and fetch server implementation

175 175 

176 176 

177 177 


629}629}

630```630```

631 631 

632```java

633import com.fasterxml.jackson.databind.json.JsonMapper;

634import com.openai.client.okhttp.OpenAIOkHttpClient;

635import com.openai.core.ObjectMappers;

636import com.openai.models.vectorstores.VectorStoreSearchParams;

637import com.openai.models.vectorstores.files.*;

638import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapper;

639import io.modelcontextprotocol.server.*;

640import io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;

641import io.modelcontextprotocol.server.transport.HttpServletSseServerTransportProvider;

642import io.modelcontextprotocol.spec.McpSchema;

643import java.util.*;

644import org.eclipse.jetty.ee10.servlet.*;

645import org.eclipse.jetty.server.*;

646 

647 

648 

649var client = OpenAIOkHttpClient.fromEnv();

650 String vectorStoreId = "vs_123";

651 var mapper = new JacksonMcpJsonMapper(JsonMapper.builder().build());

652 var transport =

653 HttpServletSseServerTransportProvider.builder()

654 .jsonMapper(mapper)

655 .sseEndpoint("/sse")

656 .messageEndpoint("/messages/")

657 // Allow local clients and the local MCP Inspector. Add trusted hosts and origins

658 // explicitly when deploying this server behind a proxy.

659 .securityValidator(

660 DefaultServerTransportSecurityValidator.builder()

661 .allowedHosts(List.of("localhost:*", "127.0.0.1:*"))

662 .allowedOrigins(List.of("http://localhost:6274", "http://127.0.0.1:6274"))

663 .build())

664 .build();

665 var search =

666 McpSchema.Tool.builder()

667 .name("search")

668 .description("Search documents, then fetch complete content with citations.")

669 .inputSchema(

670 mapper,

671"""

672{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}

673""")

674 .outputSchema(

675 mapper,

676"""

677{"type":"object","properties":{"results":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"url":{"type":"string"}},"required":["id","title","url"]}}},"required":["results"]}

678""")

679 .build();

680 var fetch =

681 McpSchema.Tool.builder()

682 .name("fetch")

683 .description("Retrieve complete document text, metadata, and citation by file ID.")

684 .inputSchema(

685 mapper,

686"""

687{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}

688""")

689 .outputSchema(

690 mapper,

691"""

692{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"text":{"type":"string"},"url":{"type":"string"},"metadata":{"type":["object","null"]}},"required":["id","title","text","url"]}

693""")

694 .build();

695 var server =

696 McpServer.sync(transport)

697 .serverInfo("Sample MCP Server", "1.0.0")

698 .capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())

699 .toolCall(

700 search,

701 (exchange, request) -> {

702 try {

703 String query = (String) request.arguments().get("query");

704 var results = new ArrayList<Map<String, String>>();

705 if (query != null && !query.isBlank()) {

706 var page =

707 client

708 .vectorStores()

709 .search(

710 vectorStoreId,

711 VectorStoreSearchParams.builder().query(query).build());

712 for (var item : page.data())

713 results.add(

714 Map.of(

715 "id",

716 item.fileId(),

717 "title",

718 item.filename(),

719 "url",

720 "https://platform.openai.com/storage/files/" + item.fileId()));

721 }

722 return result(Map.of("results", results));

723 } catch (Exception error) {

724 return failure(error);

725 }

726 })

727 .toolCall(

728 fetch,

729 (exchange, request) -> {

730 try {

731 String id = (String) request.arguments().get("id");

732 if (id == null || id.isBlank())

733 throw new IllegalArgumentException("Document ID is required");

734 var content =

735 client

736 .vectorStores()

737 .files()

738 .content(

739 id,

740 FileContentParams.builder().vectorStoreId(vectorStoreId).build());

741 var file =

742 client

743 .vectorStores()

744 .files()

745 .retrieve(

746 id,

747 FileRetrieveParams.builder().vectorStoreId(vectorStoreId).build());

748 var parts = new ArrayList<String>();

749 for (var item : content.data()) item.text().ifPresent(parts::add);

750 String title = client.files().retrieve(id).filename();

751 var document = new LinkedHashMap<String, Object>();

752 document.put("id", id);

753 document.put("title", title);

754 document.put("text", String.join("\n", parts));

755 document.put("url", "https://platform.openai.com/storage/files/" + id);

756 document.put(

757 "metadata",

758 file.attributes()

759 .map(value -> ObjectMappers.jsonMapper().valueToTree(value))

760 .orElse(null));

761 return result(document);

762 } catch (Exception error) {

763 return failure(error);

764 }

765 })

766 .build();

767 var httpServer = new Server();

768 var connector = new ServerConnector(httpServer);

769 connector.setHost("127.0.0.1");

770 connector.setPort(8000);

771 httpServer.addConnector(connector);

772 var context = new ServletContextHandler();

773 context.setContextPath("/");

774 context.addServlet(new ServletHolder(transport), "/*");

775 httpServer.setHandler(context);

776 try {

777 httpServer.start();

778 httpServer.join();

779 } finally {

780 server.closeGracefully();

781 httpServer.stop();

782 client.close();

783 }

784 

785static McpSchema.CallToolResult result(Map<String, ?> value) throws Exception {

786 String encoded = ObjectMappers.jsonMapper().writeValueAsString(value);

787 return McpSchema.CallToolResult.builder()

788 .structuredContent(value)

789 .addTextContent(encoded)

790 .isError(false)

791 .build();

792}

793 

794static McpSchema.CallToolResult failure(Exception error) {

795 return McpSchema.CallToolResult.builder()

796 .isError(true)

797 .addTextContent(

798 error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage())

799 .build();

800}

801```

802 

632```ruby803```ruby

633require "openai"804require "openai"

634require "mcp"805require "mcp"


770 941 

771 942 

772 943 

773On Replit, configure `OPENAI_API_KEY` with your OpenAI API key in the "Secrets" UI. In the sample, replace `vs_123` with the ID of the vector store you created earlier for search.944On Replit, configure `OPENAI_API_KEY` with your OpenAI API key in the Secrets UI. In the sample, replace `vs_123` with the ID of the vector store you created earlier for search.

774 945 

775On free Replit accounts, server URLs are active for as long as the editor is active, so while you are testing, you'll need to keep the browser tab open. Select the link icon to get a URL for your MCP server:946On free Replit accounts, server URLs are active for as long as the editor is active, so while you are testing, you'll need to keep the browser tab open. Select the link icon to get a URL for your MCP server:

776 947 

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.111.0</version>190 <version>4.113.0</version>

191</dependency>191</dependency>

192```192```

193 193 

Details

64 64 

65 65 

66 66 

67For Java, use these tested Maven dependencies: `com.openai:openai-java:4.105.0`, `org.jsoup:jsoup:1.24.1`, `org.apache.commons:commons-csv:1.14.1`, `com.knuddels:jtokkit:1.1.0`, and `com.fasterxml.jackson.core:jackson-databind:2.18.11`. Use one Java class for the four crawler excerpts, one class for the three final question-answering excerpts, and a separate class for each intermediate example. In each Java file, put imports at the top, place executable statements in a `main` method that declares checked exceptions, and place helper methods, fields, and records at class scope. Set `OPENAI_API_KEY` and run the classes in order from your IDE or build tool, with the Maven dependencies on the runtime classpath. Use the same working directory so each program can read the preceding program’s `text/` and `processed/` outputs.

68 

67## Setting up a web crawler69## Setting up a web crawler

68 70 

69Choose a website you can crawl. Expand the steps below to collect page text for the embeddings.71Choose a website you can crawl. Expand the steps below to collect page text for the embeddings.


90 92 

91While this crawler is written from scratch, open source packages like [`Scrapy`](https://github.com/scrapy/scrapy) can also help with these operations.93While this crawler is written from scratch, open source packages like [`Scrapy`](https://github.com/scrapy/scrapy) can also help with these operations.

92 94 

93This crawler will start from the root URL passed in at the bottom of the code below, visit each page, find additional links, and visit those pages as well (as long as they have the same root domain). To begin, import the required packages, set the starting URL, and define a subclass of `HTMLParser`.95This crawler will start from the root URL passed in at the bottom of the code below, visit each page, find additional links, and visit those pages as well (as long as they have the same root domain). To begin, import the required packages and set the starting URL. Python uses an `HTMLParser` subclass; Java uses `jsoup`. Combine the four Java excerpts in this section into the same crawler class.

94 96 

95Set up the web crawler97Set up the web crawler

96 98 


192}194}

193```195```

194 196 

197```java

198static final HttpClient HTTP =

199 HttpClient.newBuilder()

200 .connectTimeout(Duration.ofSeconds(10))

201 .followRedirects(HttpClient.Redirect.NEVER)

202 .build();

203 

204static List<String> hyperlinks(String html) {

205 return Jsoup.parse(html).select("a[href]").stream().map(link -> link.attr("href")).toList();

206}

207```

208 

195```ruby209```ruby

196require "net/http"210require "net/http"

197require "uri"211require "uri"


426}440}

427```441```

428 442 

443```java

444static List<String> getHyperlinks(URI url) throws Exception {

445 var response =

446 HTTP.send(

447 HttpRequest.newBuilder(url).timeout(Duration.ofSeconds(10)).GET().build(),

448 HttpResponse.BodyHandlers.ofString());

449 if (response.statusCode() != 200

450 || !response.headers().firstValue("content-type").orElse("").startsWith("text/html"))

451 return List.of();

452 return hyperlinks(response.body());

453}

454```

455 

429```ruby456```ruby

430def fetch_page(url, local_domain = nil)457def fetch_page(url, local_domain = nil)

431 uri = URI.parse(url)458 uri = URI.parse(url)


558}585}

559```586```

560 587 

588```java

589static Set<URI> getDomainHyperlinks(String domain, URI url) throws Exception {

590 return domainHyperlinks(domain, url, getHyperlinks(url));

591}

592 

593static Set<URI> domainHyperlinks(String domain, URI url, List<String> hrefs) {

594 var links = new LinkedHashSet<URI>();

595 for (String href : hrefs) {

596 if (href.isEmpty() || href.startsWith("#")) continue;

597 try {

598 // Query-only references keep the current path, including its final segment.

599 URI link =

600 href.startsWith("?")

601 ? URI.create(url.toString().split("[?#]", 2)[0] + href)

602 : url.resolve(href);

603 link = URI.create(link.toString().split("#", 2)[0]);

604 if (("http".equals(link.getScheme()) || "https".equals(link.getScheme()))

605 && domain.equals(link.getRawAuthority())) links.add(link);

606 } catch (IllegalArgumentException malformed) {

607 /* Ignore malformed links. */

608 }

609 }

610 return links;

611}

612```

613 

561```ruby614```ruby

562def get_domain_hyperlinks(local_domain, url)615def get_domain_hyperlinks(local_domain, url)

563 get_hyperlinks(url).filter_map do |link|616 get_hyperlinks(url).filter_map do |link|


926}979}

927```980```

928 981 

982```java

983import java.net.URI;

984import java.net.http.*;

985import java.nio.charset.StandardCharsets;

986import java.nio.file.*;

987import java.time.Duration;

988import java.util.*;

989import org.jsoup.Jsoup;

990 

991crawl(URI.create("https://example.com/"));

992 

993static void crawl(URI initial) throws Exception {

994 URI start = initial.getRawPath().isEmpty() ? URI.create(initial + "/") : initial;

995 String domain = start.getRawAuthority();

996 Path directory = Path.of("text", domain);

997 Files.createDirectories(directory);

998 Files.createDirectories(Path.of("processed"));

999 var queue = new ArrayDeque<URI>();

1000 queue.add(start);

1001 var seen = new HashSet<URI>();

1002 seen.add(start);

1003 while (!queue.isEmpty()) {

1004 URI url = queue.removeLast();

1005 var response =

1006 HTTP.send(

1007 HttpRequest.newBuilder(url).timeout(Duration.ofSeconds(10)).GET().build(),

1008 HttpResponse.BodyHandlers.ofString());

1009 if (response.statusCode() != 200

1010 || !response

1011 .headers()

1012 .firstValue("content-type")

1013 .orElse("")

1014 .toLowerCase(Locale.ROOT)

1015 .startsWith("text/html")) continue;

1016 System.out.println(url);

1017 String filename = (domain + url.getRawPath()).replace("/", "_");

1018 String suffix =

1019 "#"

1020 + HexFormat.of()

1021 .formatHex(

1022 java.security.MessageDigest.getInstance("SHA-256")

1023 .digest(url.toString().getBytes(StandardCharsets.UTF_8)));

1024 while (filename.getBytes(StandardCharsets.UTF_8).length > 255 - suffix.length() - 4)

1025 filename = filename.substring(0, filename.offsetByCodePoints(filename.length(), -1));

1026 filename += suffix;

1027 Files.writeString(directory.resolve(filename + ".txt"), Jsoup.parse(response.body()).text());

1028 for (URI link : domainHyperlinks(domain, url, hyperlinks(response.body())))

1029 if (seen.add(link)) queue.add(link);

1030 }

1031}

1032```

1033 

929```ruby1034```ruby

930def crawl(full_url)1035def crawl(full_url)

931 initial = URI.parse(full_url)1036 initial = URI.parse(full_url)


1046}1151}

1047```1152```

1048 1153 

1154```java

1155import com.fasterxml.jackson.databind.ObjectMapper;

1156import java.nio.file.*;

1157import java.util.*;

1158import org.apache.commons.csv.*;

1159 

1160System.out.println(removeNewlines("first\nsecond"));

1161 

1162static String removeNewlines(String text) {

1163 return text.replace("\n", " ").replace("\\n", " ").replaceAll(" {2,}", " ");

1164}

1165```

1166 

1049```ruby1167```ruby

1050def remove_newlines(texts)1168def remove_newlines(texts)

1051 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }1169 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }


1223}1341}

1224```1342```

1225 1343 

1344```java

1345import com.fasterxml.jackson.databind.ObjectMapper;

1346import java.nio.file.*;

1347import java.util.*;

1348import org.apache.commons.csv.*;

1349 

1350String domain = java.net.URI.create("https://example.com/").getRawAuthority();

1351var rows = new ArrayList<Map<String, String>>();

1352try (var files = Files.list(Path.of("text", domain))) {

1353 for (var file : files.sorted().toList()) {

1354 String title =

1355 file.getFileName()

1356 .toString()

1357 .replaceFirst("\\.txt$", "")

1358 .replaceFirst("#[0-9a-f]{64}$", "");

1359 if (title.startsWith(domain + "_")) title = title.substring(domain.length() + 1);

1360 else if (title.equals(domain)) title = "index";

1361 if (title.isEmpty()) title = "index";

1362 title = title.replace("-", " ").replace("_", " ").replace("#update", "");

1363 String text = Files.readString(file).replace("\n", " ").replace("\\n", " ");

1364 rows.add(Map.of("fname", title, "text", title + ". " + text));

1365 }

1366}

1367Files.createDirectories(Path.of("processed"));

1368try (var writer =

1369 CSVFormat.DEFAULT

1370 .builder()

1371 .setHeader("id", "fname", "text")

1372 .get()

1373 .print(Files.newBufferedWriter(Path.of("processed/scraped.csv")))) {

1374 for (int i = 0; i < rows.size(); i++)

1375 writer.printRecord(i, rows.get(i).get("fname"), rows.get(i).get("text"));

1376}

1377```

1378 

1226```ruby1379```ruby

1227require "csv"1380require "csv"

1228require "fileutils"1381require "fileutils"


1423}1576}

1424```1577```

1425 1578 

1579```java

1580import com.fasterxml.jackson.databind.ObjectMapper;

1581import java.nio.file.*;

1582import java.util.*;

1583import org.apache.commons.csv.*;

1584 

1585var texts = new ArrayList<String>();

1586try (var csv =

1587 CSVFormat.DEFAULT

1588 .builder()

1589 .setHeader()

1590 .setSkipHeaderRecord(true)

1591 .get()

1592 .parse(Files.newBufferedReader(Path.of("processed/scraped.csv")))) {

1593 for (var row : csv) texts.add(row.get("text"));

1594}

1595var counts = texts.stream().map(ENCODING::countTokens).toList();

1596int total = histogram(counts);

1597 

1598static final com.knuddels.jtokkit.api.Encoding ENCODING =

1599 com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry()

1600 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

1601 

1602static int histogram(List<Integer> counts) throws Exception {

1603 var bins = new TreeMap<Integer, Integer>();

1604 for (int count : counts) bins.merge(count, 1, Integer::sum);

1605 var image =

1606 new java.awt.image.BufferedImage(640, 400, java.awt.image.BufferedImage.TYPE_INT_RGB);

1607 var graphics = image.createGraphics();

1608 try {

1609 graphics.setColor(java.awt.Color.WHITE);

1610 graphics.fillRect(0, 0, 640, 400);

1611 int index = 0, maximum = bins.values().stream().max(Integer::compare).orElse(1);

1612 for (var bin : bins.entrySet()) {

1613 int x = 40 + index++ * 540 / Math.max(1, bins.size()),

1614 height = bin.getValue() * 300 / maximum;

1615 graphics.setColor(java.awt.Color.BLUE);

1616 graphics.fillRect(x, 340 - height, Math.max(1, 500 / Math.max(1, bins.size())), height);

1617 graphics.setColor(java.awt.Color.BLACK);

1618 graphics.drawString(bin.getKey().toString(), x, 360);

1619 }

1620 } finally {

1621 graphics.dispose();

1622 }

1623 javax.imageio.ImageIO.write(image, "png", Path.of("local-plot.png").toFile());

1624 return bins.values().stream().mapToInt(Integer::intValue).sum();

1625}

1626```

1627 

1426```ruby1628```ruby

1427require "csv"1629require "csv"

1428require "tiktoken_ruby"1630require "tiktoken_ruby"


1460 1662 

1461Split longer pages into chunks that fit within the [embedding model’s input limit](https://developers.openai.com/api/docs/models/text-embedding-3-small).1663Split longer pages into chunks that fit within the [embedding model’s input limit](https://developers.openai.com/api/docs/models/text-embedding-3-small).

1462 1664 

1665 

1666 

1667 

1668The Java programs pass data between steps through CSV files. The splitting step reads `processed/scraped.csv` and writes each chunk and its token count to `processed/chunks.csv`. The following histogram and embedding steps read that file.

1669 

1670 

1671 

1672 

1463Split long pages into chunks1673Split long pages into chunks

1464 1674 

1465```typescript1675```typescript


1665}1875}

1666```1876```

1667 1877 

1878```java

1879import com.fasterxml.jackson.databind.ObjectMapper;

1880import java.nio.file.*;

1881import java.util.*;

1882import org.apache.commons.csv.*;

1883 

1884try (var input =

1885 CSVFormat.DEFAULT

1886 .builder()

1887 .setHeader()

1888 .setSkipHeaderRecord(true)

1889 .get()

1890 .parse(Files.newBufferedReader(Path.of("processed/scraped.csv")));

1891 var output =

1892 CSVFormat.DEFAULT

1893 .builder()

1894 .setHeader("text", "n_tokens")

1895 .get()

1896 .print(Files.newBufferedWriter(Path.of("processed/chunks.csv")))) {

1897 for (var row : input) {

1898 for (var chunk : splitIntoMany(row.get("text"), 500)) {

1899 output.printRecord(chunk, ENCODING.countTokens(chunk));

1900 }

1901 }

1902}

1903 

1904static final com.knuddels.jtokkit.api.Encoding ENCODING =

1905 com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry()

1906 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

1907 

1908static List<String> splitIntoMany(String text, int maxTokens) {

1909 if (maxTokens < 1) throw new IllegalArgumentException("maxTokens must be positive");

1910 var chunks = new ArrayList<String>();

1911 if (text.isBlank()) return chunks;

1912 String chunk = "";

1913 String[] sentences = text.split("\\. ", -1);

1914 for (int i = 0; i < sentences.length; i++) {

1915 String sentence = sentences[i] + (i < sentences.length - 1 ? "." : "");

1916 if (ENCODING.countTokens(sentence) > maxTokens)

1917 throw new IllegalArgumentException("Split the overlong sentence before chunking");

1918 String candidate = chunk.isEmpty() ? sentence : chunk + " " + sentence;

1919 if (ENCODING.countTokens(candidate) > maxTokens) {

1920 chunks.add(chunk);

1921 chunk = sentence;

1922 } else chunk = candidate;

1923 }

1924 if (!chunk.isEmpty()) chunks.add(chunk);

1925 return chunks;

1926}

1927```

1928 

1668```ruby1929```ruby

1669require "csv"1930require "csv"

1670require "json"1931require "json"


1821}2082}

1822```2083```

1823 2084 

2085```java

2086import com.fasterxml.jackson.databind.ObjectMapper;

2087import java.nio.file.*;

2088import java.util.*;

2089import org.apache.commons.csv.*;

2090 

2091var texts = new ArrayList<String>();

2092try (var csv =

2093 CSVFormat.DEFAULT

2094 .builder()

2095 .setHeader()

2096 .setSkipHeaderRecord(true)

2097 .get()

2098 .parse(Files.newBufferedReader(Path.of("processed/chunks.csv")))) {

2099 for (var row : csv) texts.add(row.get("text"));

2100}

2101var counts = texts.stream().map(ENCODING::countTokens).toList();

2102int total = histogram(counts);

2103 

2104static final com.knuddels.jtokkit.api.Encoding ENCODING =

2105 com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry()

2106 .getEncoding(com.knuddels.jtokkit.api.EncodingType.CL100K_BASE);

2107 

2108static int histogram(List<Integer> counts) throws Exception {

2109 var bins = new TreeMap<Integer, Integer>();

2110 for (int count : counts) bins.merge(count, 1, Integer::sum);

2111 var image =

2112 new java.awt.image.BufferedImage(640, 400, java.awt.image.BufferedImage.TYPE_INT_RGB);

2113 var graphics = image.createGraphics();

2114 try {

2115 graphics.setColor(java.awt.Color.WHITE);

2116 graphics.fillRect(0, 0, 640, 400);

2117 int index = 0, maximum = bins.values().stream().max(Integer::compare).orElse(1);

2118 for (var bin : bins.entrySet()) {

2119 int x = 40 + index++ * 540 / Math.max(1, bins.size()),

2120 height = bin.getValue() * 300 / maximum;

2121 graphics.setColor(java.awt.Color.BLUE);

2122 graphics.fillRect(x, 340 - height, Math.max(1, 500 / Math.max(1, bins.size())), height);

2123 graphics.setColor(java.awt.Color.BLACK);

2124 graphics.drawString(bin.getKey().toString(), x, 360);

2125 }

2126 } finally {

2127 graphics.dispose();

2128 }

2129 javax.imageio.ImageIO.write(image, "png", Path.of("local-plot.png").toFile());

2130 return bins.values().stream().mapToInt(Integer::intValue).sum();

2131}

2132```

2133 

1824```ruby2134```ruby

1825require "json"2135require "json"

1826require "tiktoken_ruby"2136require "tiktoken_ruby"


1976}2286}

1977```2287```

1978 2288 

2289```java

2290import com.fasterxml.jackson.databind.ObjectMapper;

2291import com.openai.client.okhttp.OpenAIOkHttpClient;

2292import com.openai.models.embeddings.EmbeddingCreateParams;

2293import java.nio.file.*;

2294import java.util.*;

2295import org.apache.commons.csv.*;

2296 

2297var client = OpenAIOkHttpClient.fromEnv();

2298Files.createDirectories(Path.of("processed"));

2299try (var chunks =

2300 CSVFormat.DEFAULT

2301 .builder()

2302 .setHeader()

2303 .setSkipHeaderRecord(true)

2304 .get()

2305 .parse(Files.newBufferedReader(Path.of("processed/chunks.csv")));

2306 var csv =

2307 CSVFormat.DEFAULT

2308 .builder()

2309 .setHeader("text", "n_tokens", "embeddings")

2310 .get()

2311 .print(Files.newBufferedWriter(Path.of("processed/embeddings.csv")))) {

2312 for (var chunk : chunks) {

2313 String text = chunk.get("text");

2314 int tokens = Integer.parseInt(chunk.get("n_tokens"));

2315 var embedding =

2316 client

2317 .embeddings()

2318 .create(

2319 EmbeddingCreateParams.builder()

2320 .model("text-embedding-3-small")

2321 .input(text)

2322 .build())

2323 .data()

2324 .get(0)

2325 .embedding();

2326 csv.printRecord(text, tokens, new ObjectMapper().writeValueAsString(embedding));

2327 }

2328}

2329```

2330 

1979```csharp2331```csharp

1980using System.Globalization;2332using System.Globalization;

1981using System.Text.Json;2333using System.Text.Json;


2047 2399 

2048---2400---

2049 2401 

2050Turning the embeddings into a NumPy array is the first step, which will provide more flexibility in how to use it given the many functions available that operate on NumPy arrays. It will also flatten the dimension to 1-D, which is the required format for many subsequent operations.2402Load the saved embeddings as numeric vectors: NumPy arrays in Python or lists in Java. The Java embedding step preserves the `text` and `n_tokens` columns alongside each vector in `processed/embeddings.csv`, which the answer program reads.

2051 2403 

2052Load the saved embeddings2404Load the saved embeddings

2053 2405 


2166}2518}

2167```2519```

2168 2520 

2521```java

2522import com.fasterxml.jackson.databind.ObjectMapper;

2523import java.nio.file.*;

2524import java.util.*;

2525import org.apache.commons.csv.*;

2526 

2527var vectors = new ArrayList<List<Double>>();

2528try (var csv =

2529 CSVFormat.DEFAULT

2530 .builder()

2531 .setHeader()

2532 .setSkipHeaderRecord(true)

2533 .get()

2534 .parse(Files.newBufferedReader(Path.of("processed/embeddings.csv")))) {

2535 for (var row : csv) {

2536 List<Double> vector =

2537 new ObjectMapper()

2538 .readValue(

2539 row.get("embeddings"),

2540 new com.fasterxml.jackson.core.type.TypeReference<List<Double>>() {});

2541 if (vector.stream().anyMatch(v -> v == null || !Double.isFinite(v)))

2542 throw new IllegalArgumentException("Invalid embedding");

2543 vectors.add(vector);

2544 }

2545}

2546System.out.println(vectors.get(0));

2547```

2548 

2169```ruby2549```ruby

2170require "csv"2550require "csv"

2171require "json"2551require "json"


2177```2557```

2178 2558 

2179 2559 

2180Embed the question using the same model you used to build the index. The example computes cosine distances and retrieves the closest text chunks.2560For Java, combine the next three excerpts—the context builder, answer function, and question calls—into one class. Collect their imports at the top. Place the `Page` record and helper methods at class scope; put the client setup, CSV loading, and question calls in the same `main` method.

2561 

2562Embed the question using the same model you used to build the index. Compare the vectors using cosine similarity and retrieve the closest text chunks.

2181 2563 

2182Build context for a question2564Build context for a question

2183 2565 


2433}2815}

2434```2816```

2435 2817 

2818```java

2819record Page(String text, int tokens, List<Double> embedding) {}

2820 

2821static double cosine(List<Float> query, List<Double> vector) {

2822 if (query.size() != vector.size())

2823 throw new IllegalArgumentException("Embedding dimensions differ");

2824 double dot = 0, a = 0, b = 0;

2825 for (int i = 0; i < query.size(); i++) {

2826 dot += query.get(i) * vector.get(i);

2827 a += Math.pow(query.get(i), 2);

2828 b += Math.pow(vector.get(i), 2);

2829 }

2830 if (a == 0 || b == 0) throw new IllegalArgumentException("Zero embedding norm");

2831 return dot / Math.sqrt(a * b);

2832}

2833 

2834static String createContext(

2835 OpenAIClient client, List<Page> pages, String question, int maxTokens) {

2836 var query =

2837 client

2838 .embeddings()

2839 .create(

2840 EmbeddingCreateParams.builder()

2841 .model("text-embedding-3-small")

2842 .input(question)

2843 .build())

2844 .data()

2845 .get(0)

2846 .embedding();

2847 var ordered = new ArrayList<>(pages);

2848 ordered.sort(

2849 Comparator.comparingDouble((Page page) -> cosine(query, page.embedding())).reversed());

2850 var selected = new ArrayList<String>();

2851 int tokens = 0;

2852 for (var page : ordered) {

2853 tokens += page.tokens() + 4;

2854 if (tokens > maxTokens) break;

2855 selected.add(page.text());

2856 }

2857 return String.join("\n\n###\n\n", selected);

2858}

2859```

2860 

2436```csharp2861```csharp

2437using System.Globalization;2862using System.Globalization;

2438using System.Text.Json;2863using System.Text.Json;


2501```2926```

2502 2927 

2503 2928 

2504The `max_len` argument limits how many tokens of retrieved text to include. Pass that text and the question to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) using `gpt-6-luna`. Read the answer from `response.output_text`.2929The `max_len` argument in Python, or `maxTokens` in Java, limits how many tokens of retrieved text to include. Pass that text and the question to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) using `gpt-6-luna`. The example extracts the response's output text.

2505 2930 

2506Answer a question from the website2931Answer a question from the website

2507 2932 


2555}2980}

2556```2981```

2557 2982 

2983```java

2984import com.fasterxml.jackson.databind.ObjectMapper;

2985import com.openai.client.OpenAIClient;

2986import com.openai.client.okhttp.OpenAIOkHttpClient;

2987import com.openai.models.embeddings.EmbeddingCreateParams;

2988import com.openai.models.responses.ResponseCreateParams;

2989import java.nio.file.*;

2990import java.util.*;

2991import org.apache.commons.csv.*;

2992 

2993var client = OpenAIOkHttpClient.fromEnv();

2994var pages = new ArrayList<Page>();

2995try (var csv =

2996 CSVFormat.DEFAULT

2997 .builder()

2998 .setHeader()

2999 .setSkipHeaderRecord(true)

3000 .get()

3001 .parse(Files.newBufferedReader(Path.of("processed/embeddings.csv")))) {

3002 for (var row : csv)

3003 pages.add(

3004 new Page(

3005 row.get("text"),

3006 Integer.parseInt(row.get("n_tokens")),

3007 new ObjectMapper()

3008 .readValue(

3009 row.get("embeddings"),

3010 new com.fasterxml.jackson.core.type.TypeReference<List<Double>>() {})));

3011}

3012 

3013static String answerQuestion(

3014 OpenAIClient client, List<Page> pages, String question, int maxTokens) {

3015 String context = createContext(client, pages, question, maxTokens);

3016 var response =

3017 client

3018 .responses()

3019 .create(

3020 ResponseCreateParams.builder()

3021 .model("gpt-6-luna")

3022 .instructions(

3023 "Answer the question using only the supplied context. If the context doesn't answer the question, say \"I don't know.\"")

3024 .input("Context: " + context + "\n\nQuestion: " + question)

3025 .build());

3026 return response.output().stream()

3027 .flatMap(item -> item.message().stream())

3028 .flatMap(message -> message.content().stream())

3029 .flatMap(content -> content.outputText().stream())

3030 .map(text -> text.text())

3031 .collect(java.util.stream.Collectors.joining())

3032 .strip();

3033}

3034```

3035 

2558```csharp3036```csharp

2559private static async Task<string> AnswerQuestionAsync(EmbeddingClient embeddings, ResponsesClient responses, IEnumerable<Page> pages, string question)3037private static async Task<string> AnswerQuestionAsync(EmbeddingClient embeddings, ResponsesClient responses, IEnumerable<Page> pages, string question)

2560{3038{


2621}3099}

2622```3100```

2623 3101 

3102```java

3103System.out.println(answerQuestion(client, pages, "What is ChatGPT?", 1800));

3104System.out.println(answerQuestion(client, pages, "What did I have for breakfast today?", 1800));

3105```

3106 

2624```csharp3107```csharp

2625string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;3108string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

2626EmbeddingClient embeddings = new("text-embedding-3-small", key);3109EmbeddingClient embeddings = new("text-embedding-3-small", key);