SpyBara
Go Premium

Documentation 2026-08-19 18:02 UTC to 2026-08-20 23:59 UTC

72 files changed +11,071 −217. View all changes and history on the product overview
2026
Fri 21 03:58 Thu 20 23:59 Wed 19 18:02 Tue 18 04:58 Mon 17 22:57 Sat 15 01:01 Fri 14 20:01 Thu 13 22:00 Wed 12 02:57 Tue 11 19:59 Mon 10 19:00 Fri 7 00:58 Thu 6 21:58 Wed 5 18:01 Tue 4 22:59 Mon 3 18:01
Details

51}51}

52```52```

53 53 

54```java

55import com.openai.client.OpenAIClient;

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

57import com.openai.models.files.FileCreateParams;

58import com.openai.models.files.FilePurpose;

59import java.nio.file.Path;

60 

61var file =

62 client

63 .files()

64 .create(

65 FileCreateParams.builder()

66 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

67 .purpose(FilePurpose.ASSISTANTS)

68 .build());

69 

70System.out.println(file.id());

71```

72 

54```ruby73```ruby

55require "openai"74require "openai"

56require "pathname"75require "pathname"


111}130}

112```131```

113 132 

133```java

134import com.openai.client.OpenAIClient;

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

136import com.openai.models.beta.assistants.AssistantCreateParams;

137import com.openai.models.beta.assistants.CodeInterpreterTool;

138 

139String fileId = "file-BK7bzQj3FfZFXr7DbL6xJwfo";

140 

141var assistant =

142 client

143 .beta()

144 .assistants()

145 .create(

146 AssistantCreateParams.builder()

147 .name("Data visualizer")

148 .model("gpt-4o")

149 .description(

150 "You are great at creating beautiful data visualizations. You analyze data"

151 + " present in .csv files, understand trends, and come up with data"

152 + " visualizations relevant to those trends. You also share a brief text"

153 + " summary of the trends observed.")

154 .addTool(CodeInterpreterTool.builder().build())

155 .toolResources(

156 AssistantCreateParams.ToolResources.builder()

157 .codeInterpreter(

158 AssistantCreateParams.ToolResources.CodeInterpreter.builder()

159 .addFileId(fileId)

160 .build())

161 .build())

162 .build());

163 

164System.out.println(assistant.id());

165```

166 

114```ruby167```ruby

115require "openai"168require "openai"

116 169 


205}258}

206```259```

207 260 

261```java

262import com.openai.client.OpenAIClient;

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

264import com.openai.models.beta.assistants.CodeInterpreterTool;

265import com.openai.models.beta.threads.ThreadCreateParams;

266 

267String fileId = "file-ACq8OjcLQm2eIG0BvRM4z5qX";

268 

269var thread =

270 client

271 .beta()

272 .threads()

273 .create(

274 ThreadCreateParams.builder()

275 .addMessage(

276 ThreadCreateParams.Message.builder()

277 .role(ThreadCreateParams.Message.Role.USER)

278 .content(

279 "Create 3 data visualizations based on the trends in this file.")

280 .addAttachment(

281 ThreadCreateParams.Message.Attachment.builder()

282 .fileId(fileId)

283 .addTool(CodeInterpreterTool.builder().build())

284 .build())

285 .build())

286 .build());

287 

288System.out.println(thread.id());

289```

290 

208```ruby291```ruby

209require "openai"292require "openai"

210 293 


336}419}

337```420```

338 421 

422```java

423import com.openai.client.OpenAIClient;

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

425import com.openai.models.beta.threads.ThreadCreateParams;

426import com.openai.models.beta.threads.messages.ImageFile;

427import com.openai.models.beta.threads.messages.ImageFileContentBlock;

428import com.openai.models.beta.threads.messages.ImageUrl;

429import com.openai.models.beta.threads.messages.ImageUrlContentBlock;

430import com.openai.models.beta.threads.messages.MessageContentPartParam;

431import com.openai.models.beta.threads.messages.TextContentBlockParam;

432import com.openai.models.files.FileCreateParams;

433import com.openai.models.files.FilePurpose;

434import java.nio.file.Path;

435import java.util.List;

436 

437var file =

438 client

439 .files()

440 .create(

441 FileCreateParams.builder()

442 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

443 .purpose(FilePurpose.VISION)

444 .build());

445 

446var imageUrl =

447 ImageUrl.builder()

448 .url("https://openai-documentation.vercel.app/images/cat_and_otter.png")

449 .build();

450var thread =

451 client

452 .beta()

453 .threads()

454 .create(

455 ThreadCreateParams.builder()

456 .addMessage(

457 ThreadCreateParams.Message.builder()

458 .role(ThreadCreateParams.Message.Role.USER)

459 .content(

460 ThreadCreateParams.Message.Content.ofArrayOfContentParts(

461 List.of(

462 MessageContentPartParam.ofText(

463 TextContentBlockParam.builder()

464 .text(

465 "What is the difference between these images?")

466 .build()),

467 MessageContentPartParam.ofImageUrl(

468 ImageUrlContentBlock.builder()

469 .imageUrl(imageUrl)

470 .build()),

471 MessageContentPartParam.ofImageFile(

472 ImageFileContentBlock.builder()

473 .imageFile(

474 ImageFile.builder().fileId(file.id()).build())

475 .build()))))

476 .build())

477 .build());

478 

479System.out.println(thread.id());

480```

481 

339```ruby482```ruby

340require "openai"483require "openai"

341require "pathname"484require "pathname"


466}609}

467```610```

468 611 

612```java

613import com.openai.client.OpenAIClient;

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

615import com.openai.models.beta.threads.ThreadCreateParams;

616import com.openai.models.beta.threads.messages.ImageUrl;

617import com.openai.models.beta.threads.messages.ImageUrlContentBlock;

618import com.openai.models.beta.threads.messages.MessageContentPartParam;

619import com.openai.models.beta.threads.messages.TextContentBlockParam;

620import java.util.List;

621 

622var thread =

623 client

624 .beta()

625 .threads()

626 .create(

627 ThreadCreateParams.builder()

628 .addMessage(

629 ThreadCreateParams.Message.builder()

630 .role(ThreadCreateParams.Message.Role.USER)

631 .content(

632 ThreadCreateParams.Message.Content.ofArrayOfContentParts(

633 List.of(

634 MessageContentPartParam.ofText(

635 TextContentBlockParam.builder()

636 .text("What is this an image of?")

637 .build()),

638 MessageContentPartParam.ofImageUrl(

639 ImageUrlContentBlock.builder()

640 .imageUrl(

641 ImageUrl.builder()

642 .url(

643 "https://openai-documentation.vercel.app/images/cat_and_otter.png")

644 .detail(ImageUrl.Detail.HIGH)

645 .build())

646 .build()))))

647 .build())

648 .build());

649 

650System.out.println(thread.id());

651```

652 

469```ruby653```ruby

470require "openai"654require "openai"

471 655 


647fmt.Println(messageContent.Value)831fmt.Println(messageContent.Value)

648```832```

649 833 

834```java

835import com.openai.client.OpenAIClient;

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

837import com.openai.models.beta.threads.messages.MessageRetrieveParams;

838import java.nio.file.Files;

839import java.nio.file.Path;

840import java.nio.file.StandardCopyOption;

841import java.util.ArrayList;

842import java.util.regex.Matcher;

843import java.util.regex.Pattern;

844 

845String messageId = "msg_abc123";

846 

847String threadId = "thread_abc123";

848 

849var message =

850 client

851 .beta()

852 .threads()

853 .messages()

854 .retrieve(messageId, MessageRetrieveParams.builder().threadId(threadId).build());

855 

856var text =

857 message.content().stream()

858 .flatMap(content -> content.text().stream())

859 .findFirst()

860 .orElseThrow(() -> new IllegalStateException("No text content returned"))

861 .text();

862String rendered = text.value();

863var references = new ArrayList<String>();

864for (int index = 0; index < text.annotations().size(); index++) {

865 var annotation = text.annotations().get(index);

866 if (annotation.isFileCitation()) {

867 var citation = annotation.asFileCitation();

868 rendered =

869 rendered.replaceFirst(

870 Pattern.quote(citation.text()), Matcher.quoteReplacement(" [" + index + "]"));

871 var file = client.files().retrieve(citation.fileCitation().fileId());

872 references.add("[" + index + "] " + file.filename());

873 } else if (annotation.isFilePath()) {

874 var filePath = annotation.asFilePath();

875 rendered =

876 rendered.replaceFirst(

877 Pattern.quote(filePath.text()), Matcher.quoteReplacement(" [" + index + "]"));

878 String fileId = filePath.filePath().fileId();

879 var file = client.files().retrieve(fileId);

880 Path downloads = Path.of("downloads");

881 Files.createDirectories(downloads);

882 Path target = downloads.resolve(Path.of(file.filename()).getFileName()).normalize();

883 if (!target.startsWith(downloads)) throw new IllegalArgumentException("Unsafe filename");

884 try (var content = client.files().content(fileId)) {

885 Files.copy(content.body(), target, StandardCopyOption.REPLACE_EXISTING);

886 }

887 references.add("[" + index + "] Downloaded " + target);

888 }

889}

890System.out.println(rendered);

891references.forEach(System.out::println);

892```

893 

650```ruby894```ruby

651require "openai"895require "openai"

652require "pathname"896require "pathname"


711}955}

712```956```

713 957 

958```java

959import com.openai.client.OpenAIClient;

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

961import com.openai.models.beta.threads.runs.RunCreateParams;

962 

963String threadId = "thread_abc123";

964 

965String assistantId = "asst_ToSF7Gb04YMj8AMMm50ZLLtY";

966 

967var run =

968 client

969 .beta()

970 .threads()

971 .runs()

972 .create(threadId, RunCreateParams.builder().assistantId(assistantId).build());

973 

974System.out.println(run.status());

975```

976 

714```ruby977```ruby

715require "openai"978require "openai"

716 979 


766}1029}

767```1030```

768 1031 

1032```java

1033import com.openai.client.OpenAIClient;

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

1035import com.openai.models.beta.assistants.CodeInterpreterTool;

1036import com.openai.models.beta.assistants.FileSearchTool;

1037import com.openai.models.beta.threads.runs.RunCreateParams;

1038 

1039String threadId = "thread_abc123";

1040 

1041String assistantId = "asst_ToSF7Gb04YMj8AMMm50ZLLtY";

1042 

1043var run =

1044 client

1045 .beta()

1046 .threads()

1047 .runs()

1048 .create(

1049 threadId,

1050 RunCreateParams.builder()

1051 .assistantId(assistantId)

1052 .model("gpt-4o")

1053 .instructions("New instructions that override the Assistant instructions")

1054 .addTool(CodeInterpreterTool.builder().build())

1055 .addTool(FileSearchTool.builder().build())

1056 .build());

1057 

1058System.out.println(run.status());

1059```

1060 

769```ruby1061```ruby

770require "openai"1062require "openai"

771 1063 

Details

46}46}

47```47```

48 48 

49```java

50import com.openai.client.OpenAIClient;

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

52import com.openai.models.beta.assistants.AssistantCreateParams;

53import com.openai.models.beta.assistants.CodeInterpreterTool;

54 

55var assistant =

56 client

57 .beta()

58 .assistants()

59 .create(

60 AssistantCreateParams.builder()

61 .model("gpt-4o")

62 .instructions(

63 "You are a personal math tutor. When asked a math question, write and run"

64 + " code to answer the question.")

65 .addTool(CodeInterpreterTool.builder().build())

66 .build());

67 

68System.out.println(assistant.id());

69```

70 

49```ruby71```ruby

50require "openai"72require "openai"

51 73 


138}160}

139```161```

140 162 

163```java

164import com.openai.client.OpenAIClient;

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

166import com.openai.models.beta.assistants.AssistantCreateParams;

167import com.openai.models.beta.assistants.CodeInterpreterTool;

168import com.openai.models.files.FileCreateParams;

169import com.openai.models.files.FilePurpose;

170import java.nio.file.Path;

171 

172var file =

173 client

174 .files()

175 .create(

176 FileCreateParams.builder()

177 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

178 .purpose(FilePurpose.ASSISTANTS)

179 .build());

180var assistant =

181 client

182 .beta()

183 .assistants()

184 .create(

185 AssistantCreateParams.builder()

186 .model("gpt-4o")

187 .instructions("When asked a math question, write and run code to answer it.")

188 .addTool(CodeInterpreterTool.builder().build())

189 .toolResources(

190 AssistantCreateParams.ToolResources.builder()

191 .codeInterpreter(

192 AssistantCreateParams.ToolResources.CodeInterpreter.builder()

193 .addFileId(file.id())

194 .build())

195 .build())

196 .build());

197System.out.println(assistant.id());

198```

199 

141```ruby200```ruby

142require "openai"201require "openai"

143require "pathname"202require "pathname"


232}291}

233```292```

234 293 

294```java

295import com.openai.client.OpenAIClient;

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

297import com.openai.models.beta.assistants.CodeInterpreterTool;

298import com.openai.models.beta.threads.ThreadCreateParams;

299 

300String fileId = "file-ACq8OjcLQm2eIG0BvRM4z5qX";

301 

302var thread =

303 client

304 .beta()

305 .threads()

306 .create(

307 ThreadCreateParams.builder()

308 .addMessage(

309 ThreadCreateParams.Message.builder()

310 .role(ThreadCreateParams.Message.Role.USER)

311 .content(

312 "I need to solve the equation `3x + 11 = 14`. Can you help me?")

313 .addAttachment(

314 ThreadCreateParams.Message.Attachment.builder()

315 .fileId(fileId)

316 .addTool(CodeInterpreterTool.builder().build())

317 .build())

318 .build())

319 .build());

320 

321System.out.println(thread.id());

322```

323 

235```ruby324```ruby

236require "openai"325require "openai"

237 326 


355}444}

356```445```

357 446 

447```java

448import com.openai.client.OpenAIClient;

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

450import com.openai.core.http.HttpResponse;

451import java.io.IOException;

452import java.nio.file.Files;

453import java.nio.file.Path;

454import java.nio.file.StandardCopyOption;

455 

456String fileId = "file-abc123";

457 

458try (HttpResponse content = client.files().content(fileId)) {

459 Files.copy(content.body(), Path.of("my-image.png"), StandardCopyOption.REPLACE_EXISTING);

460}

461```

462 

358```ruby463```ruby

359require "openai"464require "openai"

360 465 

Details

170}170}

171```171```

172 172 

173```java

174import com.openai.client.OpenAIClient;

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

176import com.openai.core.JsonValue;

177import com.openai.models.FunctionDefinition;

178import com.openai.models.FunctionParameters;

179import com.openai.models.beta.assistants.AssistantCreateParams;

180import java.util.List;

181import java.util.Map;

182 

183var assistant =

184 client

185 .beta()

186 .assistants()

187 .create(

188 AssistantCreateParams.builder()

189 .model("gpt-4o")

190 .instructions(

191 "You are a weather bot. Use the provided functions to answer questions.")

192 .addFunctionTool(

193 FunctionDefinition.builder()

194 .name("get_current_temperature")

195 .description("Get the current temperature for a specific location")

196 .parameters(

197 FunctionParameters.builder()

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

199 .putAdditionalProperty(

200 "properties",

201 JsonValue.from(

202 Map.of(

203 "location",

204 Map.of(

205 "type", "string",

206 "description",

207 "The city and state, e.g., San Francisco, CA"),

208 "unit",

209 Map.of(

210 "type",

211 "string",

212 "enum",

213 List.of("Celsius", "Fahrenheit"),

214 "description",

215 "The temperature unit to use. Infer this from the user's location."))))

216 .putAdditionalProperty(

217 "required", JsonValue.from(List.of("location", "unit")))

218 .build())

219 .build())

220 .addFunctionTool(

221 FunctionDefinition.builder()

222 .name("get_rain_probability")

223 .description("Get the probability of rain for a specific location")

224 .parameters(

225 FunctionParameters.builder()

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

227 .putAdditionalProperty(

228 "properties",

229 JsonValue.from(

230 Map.of(

231 "location",

232 Map.of(

233 "type", "string",

234 "description",

235 "The city and state, e.g., San Francisco, CA"))))

236 .putAdditionalProperty(

237 "required", JsonValue.from(List.of("location")))

238 .build())

239 .build())

240 .build());

241 

242System.out.println(assistant.id());

243```

244 

173```ruby245```ruby

174require "openai"246require "openai"

175 247 


249}321}

250```322```

251 323 

324```java

325import com.openai.client.OpenAIClient;

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

327import com.openai.models.beta.threads.ThreadCreateParams;

328import com.openai.models.beta.threads.messages.MessageCreateParams;

329 

330var thread = client.beta().threads().create(ThreadCreateParams.builder().build());

331var message =

332 client

333 .beta()

334 .threads()

335 .messages()

336 .create(

337 thread.id(),

338 MessageCreateParams.builder()

339 .role(MessageCreateParams.Role.USER)

340 .content("What's the weather in San Francisco today, and will it rain?")

341 .build());

342 

343System.out.println(message.id());

344```

345 

252```ruby346```ruby

253require "openai"347require "openai"

254 348 


609}703}

610```704```

611 705 

706```java

707import com.openai.client.OpenAIClient;

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

709import com.openai.models.beta.threads.runs.Run;

710import com.openai.models.beta.threads.runs.RunCreateParams;

711import com.openai.models.beta.threads.runs.RunRetrieveParams;

712import com.openai.models.beta.threads.runs.RunStatus;

713import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams;

714import java.util.ArrayList;

715 

716String threadId = System.getenv("OPENAI_EXAMPLE_THREAD_ID");

717Run run =

718 client

719 .beta()

720 .threads()

721 .runs()

722 .create(

723 threadId,

724 RunCreateParams.builder()

725 .assistantId(System.getenv("OPENAI_EXAMPLE_ASSISTANT_ID"))

726 .build());

727run = poll(client, threadId, run);

728 

729if (run.status().equals(RunStatus.REQUIRES_ACTION)) {

730 var action =

731 run.requiredAction()

732 .orElseThrow(() -> new IllegalStateException("Run has no required action"));

733 var outputs = new ArrayList<RunSubmitToolOutputsParams.ToolOutput>();

734 for (var call : action.submitToolOutputs().toolCalls()) {

735 String output =

736 switch (call.function().name()) {

737 case "get_current_temperature" -> "57";

738 case "get_rain_probability" -> "0.06";

739 default -> null;

740 };

741 if (output != null) {

742 outputs.add(

743 RunSubmitToolOutputsParams.ToolOutput.builder()

744 .toolCallId(call.id())

745 .output(output)

746 .build());

747 }

748 }

749 if (outputs.isEmpty()) throw new IllegalStateException("No supported tool calls requested");

750 run =

751 client

752 .beta()

753 .threads()

754 .runs()

755 .submitToolOutputs(

756 run.id(),

757 RunSubmitToolOutputsParams.builder()

758 .threadId(threadId)

759 .toolOutputs(outputs)

760 .build());

761 run = poll(client, threadId, run);

762}

763 

764if (!run.status().equals(RunStatus.COMPLETED)) {

765 throw new IllegalStateException("Run ended with status: " + run.status());

766}

767client.beta().threads().messages().list(threadId).items().stream()

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

769 .flatMap(content -> content.text().stream())

770 .forEach(content -> System.out.println(content.text().value()));

771```

772 

612```ruby773```ruby

613require "openai"774require "openai"

614 775 


832}993}

833```994```

834 995 

996```java

997import com.openai.client.OpenAIClient;

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

999import com.openai.core.JsonValue;

1000import com.openai.models.FunctionDefinition;

1001import com.openai.models.FunctionParameters;

1002import com.openai.models.beta.assistants.AssistantCreateParams;

1003import java.util.List;

1004import java.util.Map;

1005 

1006var assistant =

1007 client

1008 .beta()

1009 .assistants()

1010 .create(

1011 AssistantCreateParams.builder()

1012 .model("gpt-4o-2024-08-06")

1013 .instructions(

1014 "You are a weather bot. Use the provided functions to answer questions.")

1015 .addFunctionTool(

1016 FunctionDefinition.builder()

1017 .name("get_current_temperature")

1018 .description("Get the current temperature for a specific location")

1019 .strict(true)

1020 .parameters(

1021 FunctionParameters.builder()

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

1023 .putAdditionalProperty(

1024 "properties",

1025 JsonValue.from(

1026 Map.of(

1027 "location",

1028 Map.of(

1029 "type", "string",

1030 "description",

1031 "The city and state, e.g., San Francisco, CA"),

1032 "unit",

1033 Map.of(

1034 "type",

1035 "string",

1036 "enum",

1037 List.of("Celsius", "Fahrenheit"),

1038 "description",

1039 "The temperature unit to use. Infer this from the user's location."))))

1040 .putAdditionalProperty(

1041 "required", JsonValue.from(List.of("location", "unit")))

1042 .putAdditionalProperty(

1043 "additionalProperties", JsonValue.from(false))

1044 .build())

1045 .build())

1046 .addFunctionTool(

1047 FunctionDefinition.builder()

1048 .name("get_rain_probability")

1049 .description("Get the probability of rain for a specific location")

1050 .strict(true)

1051 .parameters(

1052 FunctionParameters.builder()

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

1054 .putAdditionalProperty(

1055 "properties",

1056 JsonValue.from(

1057 Map.of(

1058 "location",

1059 Map.of(

1060 "type", "string",

1061 "description",

1062 "The city and state, e.g., San Francisco, CA"))))

1063 .putAdditionalProperty(

1064 "required", JsonValue.from(List.of("location")))

1065 .putAdditionalProperty(

1066 "additionalProperties", JsonValue.from(false))

1067 .build())

1068 .build())

1069 .build());

1070 

1071System.out.println(assistant.id());

1072```

1073 

835```ruby1074```ruby

836require "openai"1075require "openai"

837 1076 

Details

134print(f"{response.usage.prompt_tokens} prompt tokens used.")134print(f"{response.usage.prompt_tokens} prompt tokens used.")

135```135```

136 136 

137```java

138import com.openai.client.OpenAIClient;

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

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

141 

142ChatCompletionCreateParams params =

143 ChatCompletionCreateParams.builder()

144 .model("gpt-3.5-turbo-0613")

145 .addUserMessage("Translate this sentence into plain English.")

146 .temperature(0)

147 .build();

148 

149var completion = client.chat().completions().create(params);

150var usage =

151 completion.usage().orElseThrow(() -> new IllegalStateException("No usage returned"));

152System.out.println(usage.promptTokens() + " prompt tokens used.");

153```

154 

137 155 

138 156 

139To see how many tokens are in a text string without making an API call, use OpenAI’s [tiktoken](https://github.com/openai/tiktoken) Python library. Example code can be found in the OpenAI Cookbook’s guide on [how to count tokens with tiktoken](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken).157To see how many tokens are in a text string without making an API call, use OpenAI’s [tiktoken](https://github.com/openai/tiktoken) Python library. Example code can be found in the OpenAI Cookbook’s guide on [how to count tokens with tiktoken](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken).

guides/audio.md +88 −0

Details

171}171}

172```172```

173 173 

174```java

175import com.openai.client.OpenAIClient;

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

177import com.openai.models.chat.completions.ChatCompletionAudioParam;

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

179import java.io.IOException;

180import java.nio.file.Files;

181import java.nio.file.Path;

182import java.util.Base64;

183 

184ChatCompletionCreateParams params =

185 ChatCompletionCreateParams.builder()

186 .model("gpt-audio-1.5")

187 .addUserMessage("Is a golden retriever a good family dog?")

188 .addModality(ChatCompletionCreateParams.Modality.TEXT)

189 .addModality(ChatCompletionCreateParams.Modality.AUDIO)

190 .audio(

191 ChatCompletionAudioParam.builder()

192 .voice("alloy")

193 .format(ChatCompletionAudioParam.Format.WAV)

194 .build())

195 .store(true)

196 .build();

197 

198var message = client.chat().completions().create(params).choices().get(0).message();

199var audio =

200 message.audio().orElseThrow(() -> new IllegalStateException("No audio output returned"));

201Files.write(Path.of("dog.wav"), Base64.getDecoder().decode(audio.data()));

202message.content().ifPresent(System.out::println);

203```

204 

174```ruby205```ruby

175require "base64"206require "base64"

176require "openai"207require "openai"


321}352}

322```353```

323 354 

355```java

356import com.openai.client.OpenAIClient;

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

358import com.openai.models.chat.completions.ChatCompletionAudioParam;

359import com.openai.models.chat.completions.ChatCompletionContentPart;

360import com.openai.models.chat.completions.ChatCompletionContentPartInputAudio;

361import com.openai.models.chat.completions.ChatCompletionContentPartText;

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

363import com.openai.models.chat.completions.ChatCompletionUserMessageParam;

364import java.io.IOException;

365import java.nio.file.Files;

366import java.nio.file.Path;

367import java.util.Base64;

368import java.util.List;

369 

370String encodedAudio =

371 Base64.getEncoder()

372 .encodeToString(

373 Files.readAllBytes(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH"))));

374 

375ChatCompletionCreateParams params =

376 ChatCompletionCreateParams.builder()

377 .model("gpt-audio-1.5")

378 .addMessage(

379 ChatCompletionUserMessageParam.builder()

380 .contentOfArrayOfContentParts(

381 List.of(

382 ChatCompletionContentPart.ofText(

383 ChatCompletionContentPartText.builder()

384 .text("What is in this recording?")

385 .build()),

386 ChatCompletionContentPart.ofInputAudio(

387 ChatCompletionContentPartInputAudio.builder()

388 .inputAudio(

389 ChatCompletionContentPartInputAudio.InputAudio.builder()

390 .data(encodedAudio)

391 .format(

392 ChatCompletionContentPartInputAudio.InputAudio

393 .Format.WAV)

394 .build())

395 .build())))

396 .build())

397 .addModality(ChatCompletionCreateParams.Modality.TEXT)

398 .addModality(ChatCompletionCreateParams.Modality.AUDIO)

399 .audio(

400 ChatCompletionAudioParam.builder()

401 .voice("alloy")

402 .format(ChatCompletionAudioParam.Format.WAV)

403 .build())

404 .store(true)

405 .build();

406 

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

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

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

410```

411 

324```ruby412```ruby

325require "base64"413require "base64"

326require "openai"414require "openai"

Details

79}79}

80```80```

81 81 

82```java

83import com.openai.client.OpenAIClient;

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

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

86 

87ResponseCreateParams params =

88 ResponseCreateParams.builder()

89 .model("gpt-5.6")

90 .input("Write a detailed market analysis.")

91 .background(true)

92 .build();

93 

94var response = client.responses().create(params);

95System.out.println(response.status().orElseThrow());

96```

97 

82```ruby98```ruby

83require "openai"99require "openai"

84 100 


183}199}

184```200```

185 201 

202```java

203import com.openai.client.OpenAIClient;

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

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

206import com.openai.models.responses.ResponseStatus;

207 

208ResponseCreateParams params =

209 ResponseCreateParams.builder()

210 .model("gpt-5.6")

211 .input("Write a very long novel about otters in space.")

212 .background(true)

213 .build();

214 

215var response = client.responses().create(params);

216while (response.status().filter(ResponseStatus.QUEUED::equals).isPresent()

217 || response.status().filter(ResponseStatus.IN_PROGRESS::equals).isPresent()) {

218 System.out.println("Current status: " + response.status().orElseThrow());

219 Thread.sleep(1000);

220 response = client.responses().retrieve(response.id());

221}

222System.out.println("Final status: " + response.status().orElseThrow());

223response.output().stream()

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

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

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

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

228```

229 

186```ruby230```ruby

187require "openai"231require "openai"

188 232 


260}304}

261```305```

262 306 

307```java

308import com.openai.client.OpenAIClient;

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

310 

311String responseId = "resp_123";

312 

313var response = client.responses().cancel(responseId);

314 

315System.out.println(response.status());

316```

317 

263```ruby318```ruby

264require "openai"319require "openai"

265 320 


392}447}

393```448```

394 449 

450```java

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

452import com.openai.client.OpenAIClient;

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

454import com.openai.core.http.StreamResponse;

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

456import com.openai.models.responses.ResponseRetrieveParams;

457import com.openai.models.responses.ResponseStreamEvent;

458import java.util.concurrent.atomic.AtomicBoolean;

459import java.util.concurrent.atomic.AtomicLong;

460import java.util.concurrent.atomic.AtomicReference;

461 

462ResponseCreateParams params =

463 ResponseCreateParams.builder()

464 .model("gpt-5.6")

465 .input("Write a very long novel about otters in space.")

466 .background(true)

467 .build();

468 

469AtomicLong lastSequenceNumber = new AtomicLong(-1);

470AtomicReference<String> responseId = new AtomicReference<>("");

471AtomicBoolean streamCompleted = new AtomicBoolean(false);

472JsonMapper json = new JsonMapper();

473try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

474 stream.stream()

475 .forEach(

476 event -> {

477 lastSequenceNumber.set(json.valueToTree(event).path("sequence_number").asLong());

478 event

479 .created()

480 .ifPresent(

481 created -> {

482 responseId.set(created.response().id());

483 System.out.println("response.created");

484 });

485 event

486 .outputTextDelta()

487 .ifPresent(

488 delta -> {

489 System.out.println("response.output_text.delta");

490 });

491 event

492 .completed()

493 .ifPresent(

494 completed -> {

495 streamCompleted.set(true);

496 System.out.println("response.completed");

497 });

498 });

499}

500System.out.println(

501 "Response " + responseId.get() + "; last sequence number " + lastSequenceNumber.get());

502if (!streamCompleted.get()) {

503 try (StreamResponse<ResponseStreamEvent> resumed =

504 client

505 .responses()

506 .retrieveStreaming(

507 ResponseRetrieveParams.builder()

508 .responseId(responseId.get())

509 .startingAfter(lastSequenceNumber.get())

510 .build())) {

511 resumed.stream()

512 .forEach(

513 event ->

514 event.outputTextDelta().ifPresent(delta -> System.out.println(delta.delta())));

515 }

516}

517```

518 

395```ruby519```ruby

396require "openai"520require "openai"

397 521 

guides/batch.md +88 −0

Details

160}160}

161```161```

162 162 

163```java

164import com.openai.client.OpenAIClient;

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

166import com.openai.models.files.FileCreateParams;

167import com.openai.models.files.FilePurpose;

168import java.nio.file.Path;

169 

170var file =

171 client

172 .files()

173 .create(

174 FileCreateParams.builder()

175 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

176 .purpose(FilePurpose.BATCH)

177 .build());

178 

179System.out.println(file.id());

180```

181 

163```ruby182```ruby

164require "openai"183require "openai"

165require "pathname"184require "pathname"


237}256}

238```257```

239 258 

259```java

260import com.openai.client.OpenAIClient;

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

262import com.openai.models.batches.BatchCreateParams;

263 

264String fileId = "file-abc123";

265 

266var batch =

267 client

268 .batches()

269 .create(

270 BatchCreateParams.builder()

271 .inputFileId(fileId)

272 .endpoint(BatchCreateParams.Endpoint.V1_RESPONSES)

273 .completionWindow(BatchCreateParams.CompletionWindow._24H)

274 .build());

275 

276System.out.println(batch.id());

277```

278 

240```ruby279```ruby

241require "openai"280require "openai"

242 281 


331}370}

332```371```

333 372 

373```java

374import com.openai.client.OpenAIClient;

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

376 

377String batchId = "batch_abc123";

378 

379var batch = client.batches().retrieve(batchId);

380 

381System.out.println(batch.status());

382```

383 

334```ruby384```ruby

335require "openai"385require "openai"

336 386 


418}468}

419```469```

420 470 

471```java

472import com.openai.client.OpenAIClient;

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

474import com.openai.core.http.HttpResponse;

475import java.io.IOException;

476import java.nio.file.Files;

477import java.nio.file.Path;

478import java.nio.file.StandardCopyOption;

479 

480String fileId = "file-xyz123";

481 

482try (HttpResponse content = client.files().content(fileId)) {

483 Files.copy(

484 content.body(), Path.of("batch_output.jsonl"), StandardCopyOption.REPLACE_EXISTING);

485}

486```

487 

421```ruby488```ruby

422require "openai"489require "openai"

423 490 


499}566}

500```567```

501 568 

569```java

570import com.openai.client.OpenAIClient;

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

572 

573String batchId = "batch_abc123";

574 

575System.out.println(client.batches().cancel(batchId).status());

576```

577 

502```ruby578```ruby

503require "openai"579require "openai"

504 580 


567}643}

568```644```

569 645 

646```java

647import com.openai.client.OpenAIClient;

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

649import com.openai.models.batches.BatchListParams;

650 

651client

652 .batches()

653 .list(BatchListParams.builder().limit(10).build())

654 .autoPager()

655 .forEach(batch -> System.out.println(batch.id()));

656```

657 

570```ruby658```ruby

571require "openai"659require "openai"

572 660 

Details

99}99}

100```100```

101 101 

102```java

103import com.openai.client.OpenAIClient;

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

105import com.openai.models.Reasoning;

106import com.openai.models.ReasoningEffort;

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

108 

109String code =

110 """

111 def display_name(user):

112 return user.profile.name

113 

114 print(display_name(None))

115 """;

116 

117ResponseCreateParams params =

118 ResponseCreateParams.builder()

119 .model("gpt-5.6")

120 .input("Find the null pointer exception in this code:\n\n" + code)

121 .reasoning(Reasoning.builder().effort(ReasoningEffort.HIGH).build())

122 .build();

123 

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

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

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

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

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

129```

130 

102```ruby131```ruby

103require "openai"132require "openai"

104 133 

Details

139}139}

140```140```

141 141 

142```java

143import com.openai.client.OpenAIClient;

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

145import com.openai.core.JsonValue;

146import com.openai.models.responses.EasyInputMessage;

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

148import com.openai.models.responses.ResponseInputItem;

149import java.util.ArrayList;

150import java.util.List;

151import java.util.Map;

152 

153var conversation = new ArrayList<ResponseInputItem>();

154conversation.add(

155 ResponseInputItem.ofEasyInputMessage(

156 EasyInputMessage.builder()

157 .role(EasyInputMessage.Role.USER)

158 .content("Let's begin a long coding task.")

159 .build()));

160 

161ResponseCreateParams params =

162 ResponseCreateParams.builder()

163 .model("gpt-5.3-codex")

164 .inputOfResponse(conversation)

165 .store(false)

166 .putAdditionalBodyProperty(

167 "context_management",

168 JsonValue.from(List.of(Map.of("type", "compaction", "compact_threshold", 200000))))

169 .build();

170 

171var response = client.responses().create(params);

172response.output().stream()

173 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

174 .forEach(conversation::add);

175conversation.add(

176 ResponseInputItem.ofEasyInputMessage(

177 EasyInputMessage.builder()

178 .role(EasyInputMessage.Role.USER)

179 .content("Now implement the next step.")

180 .build()));

181 

182client

183 .responses()

184 .create(params.toBuilder().inputOfResponse(conversation).build())

185 .output()

186 .stream()

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

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

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

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

191```

192 

142```ruby193```ruby

143require "openai"194require "openai"

144 195 


292}343}

293```344```

294 345 

346```java

347import com.openai.client.OpenAIClient;

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

349import com.openai.models.responses.EasyInputMessage;

350import com.openai.models.responses.ResponseCompactParams;

351import com.openai.models.responses.ResponseCompactionItemParam;

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

353import com.openai.models.responses.ResponseInputItem;

354import java.util.ArrayList;

355 

356var compacted =

357 client

358 .responses()

359 .compact(

360 ResponseCompactParams.builder()

361 .model("gpt-5.6")

362 .input("Plan a trip to Kyoto.")

363 .build());

364var input = new ArrayList<ResponseInputItem>();

365for (var item : compacted.output()) {

366 item.message().map(ResponseInputItem::ofResponseOutputMessage).ifPresent(input::add);

367 item.reasoning().map(ResponseInputItem::ofReasoning).ifPresent(input::add);

368 item.compaction()

369 .map(

370 value ->

371 ResponseInputItem.ofCompaction(

372 ResponseCompactionItemParam.builder()

373 .id(value.id())

374 .encryptedContent(value.encryptedContent())

375 .build()))

376 .ifPresent(input::add);

377}

378input.add(

379 ResponseInputItem.ofEasyInputMessage(

380 EasyInputMessage.builder()

381 .role(EasyInputMessage.Role.USER)

382 .content("Add restaurant recommendations.")

383 .build()));

384 

385client

386 .responses()

387 .create(

388 ResponseCreateParams.builder()

389 .model("gpt-5.6")

390 .inputOfResponse(input)

391 .store(false)

392 .build())

393 .output()

394 .stream()

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

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

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

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

399```

400 

295```ruby401```ruby

296require "openai"402require "openai"

297 403 

Details

85}85}

86```86```

87 87 

88```java

89import com.openai.client.OpenAIClient;

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

91import com.openai.models.responses.EasyInputMessage;

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

93import com.openai.models.responses.ResponseInputItem;

94import java.util.List;

95 

96ResponseCreateParams params =

97 ResponseCreateParams.builder()

98 .model("gpt-5.6")

99 .inputOfResponse(

100 List.of(

101 ResponseInputItem.ofEasyInputMessage(

102 EasyInputMessage.builder()

103 .role(EasyInputMessage.Role.USER)

104 .content("Knock knock.")

105 .build()),

106 ResponseInputItem.ofEasyInputMessage(

107 EasyInputMessage.builder()

108 .role(EasyInputMessage.Role.ASSISTANT)

109 .content("Who's there?")

110 .build()),

111 ResponseInputItem.ofEasyInputMessage(

112 EasyInputMessage.builder()

113 .role(EasyInputMessage.Role.USER)

114 .content("Orange.")

115 .build())))

116 .build();

117 

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

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

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

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

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

123```

124 

88```ruby125```ruby

89require "openai"126require "openai"

90 127 


237}274}

238```275```

239 276 

277```java

278import com.openai.client.OpenAIClient;

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

280import com.openai.core.JsonValue;

281import com.openai.models.responses.EasyInputMessage;

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

283import com.openai.models.responses.ResponseInputItem;

284import java.util.ArrayList;

285 

286var history = new ArrayList<ResponseInputItem>();

287history.add(

288 ResponseInputItem.ofEasyInputMessage(

289 EasyInputMessage.builder()

290 .role(EasyInputMessage.Role.USER)

291 .content("Tell me a joke.")

292 .build()));

293 

294var first =

295 client

296 .responses()

297 .create(

298 ResponseCreateParams.builder()

299 .model("gpt-5.6")

300 .inputOfResponse(history)

301 .store(false)

302 .build());

303first.output().stream()

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

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

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

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

308first.output().stream()

309 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

310 .forEach(history::add);

311history.add(

312 ResponseInputItem.ofEasyInputMessage(

313 EasyInputMessage.builder()

314 .role(EasyInputMessage.Role.USER)

315 .content("Tell me another.")

316 .build()));

317 

318client

319 .responses()

320 .create(

321 ResponseCreateParams.builder()

322 .model("gpt-5.6")

323 .inputOfResponse(history)

324 .store(false)

325 .build())

326 .output()

327 .stream()

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

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

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

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

332```

333 

240```ruby334```ruby

241require "openai"335require "openai"

242 336 


290}384}

291```385```

292 386 

387```java

388import com.openai.client.OpenAIClient;

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

390 

391var conversation = client.conversations().create();

392 

393System.out.println(conversation.id());

394```

395 

293```ruby396```ruby

294conversation = client.conversations.create397conversation = client.conversations.create

295```398```


323fmt.Println(response.OutputText())426fmt.Println(response.OutputText())

324```427```

325 428 

429```java

430import com.openai.client.OpenAIClient;

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

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

433 

434var conversation = client.conversations().create();

435 

436var response =

437 client

438 .responses()

439 .create(

440 ResponseCreateParams.builder()

441 .model("gpt-5.6")

442 .conversation(conversation.id())

443 .input("What are the five Ds of dodgeball?")

444 .build());

445 

446response.output().stream()

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

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

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

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

451```

452 

326```ruby453```ruby

327response = client.responses.create(454response = client.responses.create(

328 model: "gpt-5.6",455 model: "gpt-5.6",


421}548}

422```549```

423 550 

551```java

552import com.openai.client.OpenAIClient;

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

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

555 

556var first =

557 client

558 .responses()

559 .create(

560 ResponseCreateParams.builder().model("gpt-5.6").input("Tell me a joke.").build());

561 

562first.output().stream()

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

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

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

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

567 

568var second =

569 client

570 .responses()

571 .create(

572 ResponseCreateParams.builder()

573 .model("gpt-5.6")

574 .input("Explain why this is funny.")

575 .previousResponseId(first.id())

576 .build());

577second.output().stream()

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

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

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

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

582```

583 

424```ruby584```ruby

425require "openai"585require "openai"

426 586 


527}687}

528```688```

529 689 

690```java

691import com.openai.client.OpenAIClient;

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

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

694 

695var first =

696 client

697 .responses()

698 .create(

699 ResponseCreateParams.builder().model("gpt-5.6").input("Tell me a joke.").build());

700 

701first.output().stream()

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

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

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

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

706 

707var second =

708 client

709 .responses()

710 .create(

711 ResponseCreateParams.builder()

712 .model("gpt-5.6")

713 .input("Explain why this is funny.")

714 .previousResponseId(first.id())

715 .build());

716second.output().stream()

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

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

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

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

721```

722 

530```ruby723```ruby

531require "openai"724require "openai"

532 725 

Details

130}130}

131```131```

132 132 

133```java

134import com.openai.client.OpenAIClient;

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

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

137import com.openai.models.responses.ResponseStatus;

138import com.openai.models.responses.Tool;

139import com.openai.models.responses.WebSearchTool;

140import java.util.List;

141 

142ResponseCreateParams params =

143 ResponseCreateParams.builder()

144 .model("o3-deep-research")

145 .input(

146 "Research the economic impact of semaglutide on global healthcare systems. Include measurable outcomes and cite primary sources.")

147 .background(true)

148 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

149 .addFileSearchTool(List.of(System.getenv("OPENAI_EXAMPLE_VECTOR_STORE_ID")))

150 .addCodeInterpreterTool(

151 Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder().build())

152 .build();

153 

154var response = client.responses().create(params);

155while (response.status().filter(ResponseStatus.QUEUED::equals).isPresent()

156 || response.status().filter(ResponseStatus.IN_PROGRESS::equals).isPresent()) {

157 Thread.sleep(1000);

158 response = client.responses().retrieve(response.id());

159}

160if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty()) {

161 throw new IllegalStateException(

162 "Research ended with status: " + response.status().orElseThrow());

163}

164 

165response.output().stream()

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

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

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

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

170```

171 

133```ruby172```ruby

134require "openai"173require "openai"

135 174 


349}388}

350```389```

351 390 

391```java

392import com.openai.client.OpenAIClient;

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

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

395 

396ResponseCreateParams params =

397 ResponseCreateParams.builder()

398 .model("gpt-5.6")

399 .input("Research surfboards for me. I'm interested in ...")

400 .instructions(

401 "Ask concise questions to gather all missing requirements. Do not conduct the research yet.")

402 .build();

403 

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

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

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

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

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

409```

410 

352```ruby411```ruby

353require "openai"412require "openai"

354 413 


630}689}

631```690```

632 691 

692```java

693import com.openai.client.OpenAIClient;

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

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

696 

697String researchInstructions =

698 """

699 You will be given a research task by a user. Your job is to produce a set of

700 instructions for a researcher that will complete the task. Do NOT complete the

701 task yourself, just provide instructions on how to complete it.

702 

703 GUIDELINES:

704 1. **Maximize Specificity and Detail**

705 - Include all known user preferences and explicitly list key attributes or

706 dimensions to consider.

707 - It is of utmost importance that all details from the user are included in

708 the instructions.

709 

710 2. **Fill in Unstated But Necessary Dimensions as Open-Ended**

711 - If certain attributes are essential for a meaningful output but the user

712 has not provided them, explicitly state that they are open-ended or default

713 to no specific constraint.

714 

715 3. **Avoid Unwarranted Assumptions**

716 - If the user has not provided a particular detail, do not invent one.

717 - Instead, state the lack of specification and guide the researcher to treat

718 it as flexible or accept all possible options.

719 

720 4. **Use the First Person**

721 - Phrase the request from the perspective of the user.

722 

723 5. **Tables**

724 - If you determine that including a table will help illustrate, organize, or

725 enhance the information in the research output, you must explicitly request

726 that the researcher provide them.

727 

728 Examples:

729 - Product Comparison (Consumer): When comparing different smartphone models,

730 request a table listing each model's features, price, and consumer ratings

731 side-by-side.

732 - Project Tracking (Work): When outlining project deliverables, create a table

733 showing tasks, deadlines, responsible team members, and status updates.

734 - Budget Planning (Consumer): When creating a personal or household budget,

735 request a table detailing income sources, monthly expenses, and savings goals.

736 - Competitor Analysis (Work): When evaluating competitor products, request a

737 table with key metrics, such as market share, pricing, and main differentiators.

738 

739 6. **Headers and Formatting**

740 - You should include the expected output format in the prompt.

741 - If the user is asking for content that would be best returned in a

742 structured format (e.g. a report, plan, etc.), ask the researcher to format

743 as a report with the appropriate headers and formatting that ensures clarity

744 and structure.

745 

746 7. **Language**

747 - If the user input is in a language other than English, tell the researcher

748 to respond in this language, unless the user query explicitly asks for the

749 response in a different language.

750 

751 8. **Sources**

752 - If specific sources should be prioritized, specify them in the prompt.

753 - For product and travel research, prefer linking directly to official or

754 primary websites (e.g., official brand sites, manufacturer pages, or

755 reputable e-commerce platforms like Amazon for user reviews) rather than

756 aggregator sites or SEO-heavy blogs.

757 - For academic or scientific queries, prefer linking directly to the original

758 paper or official journal publication rather than survey papers or secondary

759 summaries.

760 - If the query is in a specific language, prioritize sources published in that

761 language.

762 """;

763 

764ResponseCreateParams params =

765 ResponseCreateParams.builder()

766 .model("gpt-5.6")

767 .input("Research surfboards for me. I'm interested in ...")

768 .instructions(researchInstructions)

769 .build();

770 

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

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

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

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

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

776```

777 

633```ruby778```ruby

634require "openai"779require "openai"

635 780 


797}942}

798```943```

799 944 

945```java

946import com.openai.client.OpenAIClient;

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

948import com.openai.models.Reasoning;

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

950import com.openai.models.responses.ResponseStatus;

951import com.openai.models.responses.Tool;

952 

953ResponseCreateParams params =

954 ResponseCreateParams.builder()

955 .model("o3-deep-research")

956 .input("What patterns appear in our closed-lost Salesforce opportunities?")

957 .instructions("Produce a source-backed deep research report.")

958 .reasoning(Reasoning.builder().summary(Reasoning.Summary.AUTO).build())

959 .background(true)

960 .addTool(

961 Tool.Mcp.builder()

962 .serverLabel("mycompany_mcp_server")

963 .serverUrl(System.getenv("OPENAI_MCP_SERVER_URL"))

964 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

965 .build())

966 .build();

967 

968var response = client.responses().create(params);

969while (response.status().filter(ResponseStatus.QUEUED::equals).isPresent()

970 || response.status().filter(ResponseStatus.IN_PROGRESS::equals).isPresent()) {

971 Thread.sleep(1000);

972 response = client.responses().retrieve(response.id());

973}

974if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty()) {

975 throw new IllegalStateException(

976 "Research ended with status: " + response.status().orElseThrow());

977}

978 

979response.output().stream()

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

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

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

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

984```

985 

800```ruby986```ruby

801require "openai"987require "openai"

802 988 

Details

150}150}

151```151```

152 152 

153```java

154import com.openai.client.OpenAIClient;

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

156import com.openai.core.JsonValue;

157import com.openai.models.Reasoning;

158import com.openai.models.ReasoningEffort;

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

160 

161ResponseCreateParams params =

162 ResponseCreateParams.builder()

163 .model("gpt-5.6")

164 .input(

165 "Our CI job started failing after a dependency bump. Error: TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'. Identify the likeliest root cause and the smallest safe fix.")

166 .reasoning(

167 Reasoning.builder()

168 .effort(ReasoningEffort.XHIGH)

169 .putAdditionalProperty("mode", JsonValue.from("pro"))

170 .build())

171 .build();

172 

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

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

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

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

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

178```

179 

153```ruby180```ruby

154require "openai"181require "openai"

155 182 


267}294}

268```295```

269 296 

297```java

298import com.openai.client.OpenAIClient;

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

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

301import com.openai.models.responses.ResponseTextConfig;

302 

303ResponseCreateParams params =

304 ResponseCreateParams.builder()

305 .model("gpt-5.6")

306 .input(

307 "Summarize this incident for the next on-call engineer: checkout latency spiked from 220 ms to 4.8 s, only us-east-1 was affected, rollback is complete, and the likely trigger was a cache stampede.")

308 .text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())

309 .build();

310 

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

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

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

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

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

316```

317 

270```ruby318```ruby

271require "openai"319require "openai"

272 320 


553}601}

554```602```

555 603 

604```java

605import com.openai.client.OpenAIClient;

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

607import com.openai.core.JsonValue;

608import com.openai.models.responses.NamespaceTool;

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

610import com.openai.models.responses.ToolSearchTool;

611import java.util.List;

612import java.util.Map;

613 

614ResponseCreateParams params =

615 ResponseCreateParams.builder()

616 .model("gpt-5.6")

617 .input(

618 "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.")

619 .addTool(

620 namespace(

621 "billing",

622 "Billing tools for invoices, payments, taxes, and credits.",

623 "lookup_invoice",

624 "Look up invoice state, taxes, credits, and payment attempts.",

625 "invoice_id"))

626 .addTool(

627 namespace(

628 "crm",

629 "CRM tools for account ownership, plans, health, and payment history.",

630 "get_account",

631 "Fetch account owner, plan, health, and payment history.",

632 "account_id"))

633 .addTool(ToolSearchTool.builder().execution(ToolSearchTool.Execution.SERVER).build())

634 .build();

635 

636client.responses().create(params).output().forEach(System.out::println);

637 

638private static NamespaceTool namespace(

639 String name,

640 String description,

641 String function,

642 String functionDescription,

643 String argument) {

644 return NamespaceTool.builder()

645 .name(name)

646 .description(description)

647 .addTool(

648 NamespaceTool.Tool.Function.builder()

649 .name(function)

650 .description(functionDescription)

651 .deferLoading(true)

652 .strict(true)

653 .parameters(

654 JsonValue.from(

655 Map.of(

656 "type",

657 "object",

658 "properties",

659 Map.of(argument, Map.of("type", "string")),

660 "required",

661 List.of(argument),

662 "additionalProperties",

663 false)))

664 .build())

665 .build();

666}

667```

668 

556```ruby669```ruby

557require "openai"670require "openai"

558 671 


834}947}

835```948```

836 949 

950```java

951import com.openai.client.OpenAIClient;

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

953import com.openai.models.responses.EasyInputMessage;

954import com.openai.models.responses.ResponseCompactParams;

955import com.openai.models.responses.ResponseCompactionItemParam;

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

957import com.openai.models.responses.ResponseInputItem;

958import java.util.ArrayList;

959 

960var compacted =

961 client

962 .responses()

963 .compact(

964 ResponseCompactParams.builder()

965 .model("gpt-5.6")

966 .input("Find the cache invalidation bug in this debugging session.")

967 .build());

968var input = new ArrayList<ResponseInputItem>();

969for (var item : compacted.output()) {

970 item.message().map(ResponseInputItem::ofResponseOutputMessage).ifPresent(input::add);

971 item.reasoning().map(ResponseInputItem::ofReasoning).ifPresent(input::add);

972 item.compaction()

973 .map(

974 value ->

975 ResponseInputItem.ofCompaction(

976 ResponseCompactionItemParam.builder()

977 .id(value.id())

978 .encryptedContent(value.encryptedContent())

979 .build()))

980 .ifPresent(input::add);

981}

982input.add(

983 ResponseInputItem.ofEasyInputMessage(

984 EasyInputMessage.builder()

985 .role(EasyInputMessage.Role.USER)

986 .content(

987 "We found the bad cache invalidation path. Write the fix plan and the verification checklist.")

988 .build()));

989 

990client

991 .responses()

992 .create(

993 ResponseCreateParams.builder()

994 .model("gpt-5.6")

995 .inputOfResponse(input)

996 .store(false)

997 .build())

998 .output()

999 .stream()

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

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

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

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

1004```

1005 

837```ruby1006```ruby

838require "openai"1007require "openai"

839 1008 


970}1139}

971```1140```

972 1141 

1142```java

1143import com.openai.client.OpenAIClient;

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

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

1146 

1147ResponseCreateParams params =

1148 ResponseCreateParams.builder()

1149 .model("gpt-5.6")

1150 .instructions(

1151 "You are the support agent for Acme.\n"

1152 + "Follow the Acme support policy and escalation rubric.\n"

1153 + "Use the same tone, safety rules, and tool plan for each ticket.")

1154 .input("Summarize the current escalation for the on-call lead.")

1155 .promptCacheKey("tenant-acme-support-agent")

1156 .build();

1157 

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

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

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

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

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

1163```

1164 

973```ruby1165```ruby

974require "openai"1166require "openai"

975 1167 


1147}1339}

1148```1340```

1149 1341 

1342```java

1343import com.openai.client.OpenAIClient;

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

1345import com.openai.core.JsonValue;

1346import com.openai.models.Reasoning;

1347import com.openai.models.responses.EasyInputMessage;

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

1349import com.openai.models.responses.ResponseIncludable;

1350import com.openai.models.responses.ResponseInputItem;

1351import java.util.ArrayList;

1352 

1353var history = new ArrayList<ResponseInputItem>();

1354history.add(

1355 ResponseInputItem.ofEasyInputMessage(

1356 EasyInputMessage.builder()

1357 .role(EasyInputMessage.Role.USER)

1358 .content("Investigate why invoice INV-1043 has mismatched tax totals.")

1359 .build()));

1360 

1361var first =

1362 client

1363 .responses()

1364 .create(

1365 ResponseCreateParams.builder()

1366 .model("gpt-5.6")

1367 .inputOfResponse(history)

1368 .store(false)

1369 .reasoning(

1370 Reasoning.builder()

1371 .effort(com.openai.models.ReasoningEffort.MEDIUM)

1372 .putAdditionalProperty("context", JsonValue.from("current_turn"))

1373 .build())

1374 .addInclude(ResponseIncludable.of("reasoning.encrypted_content"))

1375 .build());

1376first.output().stream()

1377 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

1378 .forEach(history::add);

1379history.add(

1380 ResponseInputItem.ofEasyInputMessage(

1381 EasyInputMessage.builder()

1382 .role(EasyInputMessage.Role.USER)

1383 .content("Now write the customer-facing explanation in plain English.")

1384 .build()));

1385 

1386client

1387 .responses()

1388 .create(

1389 ResponseCreateParams.builder()

1390 .model("gpt-5.6")

1391 .inputOfResponse(history)

1392 .store(false)

1393 .reasoning(

1394 Reasoning.builder()

1395 .effort(com.openai.models.ReasoningEffort.MEDIUM)

1396 .putAdditionalProperty("context", JsonValue.from("all_turns"))

1397 .build())

1398 .build())

1399 .output()

1400 .stream()

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

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

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

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

1405```

1406 

1150```ruby1407```ruby

1151require "openai"1408require "openai"

1152 1409 


1314}1571}

1315```1572```

1316 1573 

1574```java

1575import com.openai.client.OpenAIClient;

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

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

1578import com.openai.models.responses.ResponseStatus;

1579import com.openai.models.responses.Tool;

1580 

1581String fileId = "file_abc123";

1582 

1583ResponseCreateParams params =

1584 ResponseCreateParams.builder()

1585 .model("gpt-5.6")

1586 .input("Analyze this large log bundle and cluster the primary failure modes.")

1587 .background(true)

1588 .store(false)

1589 .addCodeInterpreterTool(

1590 Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder()

1591 .addFileId(fileId)

1592 .build())

1593 .build();

1594 

1595var response = client.responses().create(params);

1596while (response.status().filter(ResponseStatus.QUEUED::equals).isPresent()

1597 || response.status().filter(ResponseStatus.IN_PROGRESS::equals).isPresent()) {

1598 Thread.sleep(1000);

1599 response = client.responses().retrieve(response.id());

1600}

1601if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty()) {

1602 throw new IllegalStateException(

1603 "Research ended with status: " + response.status().orElseThrow());

1604}

1605 

1606response.output().stream()

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

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

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

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

1611```

1612 

1317```ruby1613```ruby

1318require "openai"1614require "openai"

1319 1615 

Details

160}160}

161```161```

162 162 

163```java

164import com.openai.client.OpenAIClient;

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

166import com.openai.models.finetuning.jobs.JobCreateParams;

167import com.openai.models.finetuning.methods.DpoHyperparameters;

168import com.openai.models.finetuning.methods.DpoMethod;

169 

170String fileId = "file-all-about-the-weather";

171 

172var job =

173 client

174 .fineTuning()

175 .jobs()

176 .create(

177 JobCreateParams.builder()

178 .model("gpt-4.1-mini-2025-04-14")

179 .trainingFile(fileId)

180 .method(

181 JobCreateParams.Method.builder()

182 .type(JobCreateParams.Method.Type.DPO)

183 .dpo(

184 DpoMethod.builder()

185 .hyperparameters(DpoHyperparameters.builder().beta(0.1).build())

186 .build())

187 .build())

188 .build());

189 

190System.out.println(job.id());

191```

192 

163```ruby193```ruby

164require "openai"194require "openai"

165 195 

Details

75}75}

76```76```

77 77 

78```java

79import com.openai.client.OpenAIClient;

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

81import com.openai.models.embeddings.EmbeddingCreateParams;

82 

83var embedding =

84 client

85 .embeddings()

86 .create(

87 EmbeddingCreateParams.builder()

88 .model("text-embedding-3-small")

89 .input("The food was delicious and the waiter...")

90 .build());

91 

92System.out.println(embedding.data().get(0).embedding());

93```

94 

78```ruby95```ruby

79require "openai"96require "openai"

80 97 


177df.to_csv("output/embedded_1k_reviews.csv", index=False)194df.to_csv("output/embedded_1k_reviews.csv", index=False)

178```195```

179 196 

197```java

198import com.openai.client.OpenAIClient;

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

200import com.openai.models.embeddings.EmbeddingCreateParams;

201import java.io.IOException;

202import java.nio.file.Files;

203import java.nio.file.Path;

204import java.util.List;

205 

206static String csvField(String value) {

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

208}

209 

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

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

212Files.createDirectories(output.getParent());

213try (var writer = Files.newBufferedWriter(output)) {

214 writer.write("combined,ada_embedding\n");

215 for (String review : reviews) {

216 var embedding =

217 client

218 .embeddings()

219 .create(

220 EmbeddingCreateParams.builder()

221 .model("text-embedding-3-small")

222 .inputOfArrayOfStrings(List.of(review.replace("\n", " ")))

223 .build())

224 .data()

225 .get(0)

226 .embedding();

227 writer.write(csvField(review) + "," + csvField(embedding.toString()) + "\n");

228 }

229}

230System.out.println(output);

231```

232 

180 233 

181To load the data from a saved file, you can run the following:234To load the data from a saved file, you can run the following:

182 235 


225print(norm_dim)278print(norm_dim)

226```279```

227 280 

281```java

282import com.openai.client.OpenAIClient;

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

284import com.openai.models.embeddings.EmbeddingCreateParams;

285import java.util.List;

286 

287private static List<Double> normalizeL2(List<Float> embedding) {

288 double norm = Math.sqrt(embedding.stream().mapToDouble(value -> value * value).sum());

289 return embedding.stream().map(value -> norm == 0 ? 0.0 : value / norm).toList();

290}

291 

292var embedding =

293 client

294 .embeddings()

295 .create(

296 EmbeddingCreateParams.builder()

297 .model("text-embedding-3-small")

298 .input("Testing 123")

299 .encodingFormat(EmbeddingCreateParams.EncodingFormat.FLOAT)

300 .build());

301 

302List<Float> shortened = embedding.data().get(0).embedding().subList(0, 256);

303System.out.println(normalizeL2(shortened));

304```

305 

228 306 

229Dynamically changing the dimensions enables very flexible usage. For example, when using a vector data store that only supports embeddings up to 1024 dimensions long, developers can now still use our best embedding model `text-embedding-3-large` and specify a value of 1024 for the `dimensions` API parameter, which will shorten the embedding down from 3072 dimensions, trading off some accuracy in exchange for the smaller vector size.307Dynamically changing the dimensions enables very flexible usage. For example, when using a vector data store that only supports embeddings up to 1024 dimensions long, developers can now still use our best embedding model `text-embedding-3-large` and specify a value of 1024 for the `dimensions` API parameter, which will shorten the embedding down from 3072 dimensions, trading off some accuracy in exchange for the smaller vector size.

230 308 


262print(response.choices[0].message.content)340print(response.choices[0].message.content)

263```341```

264 342 

343```java

344import com.openai.client.OpenAIClient;

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

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

347 

348String article =

349 "At the 2022 Winter Olympics, Great Britain won women's curling and Sweden won men's curling.";

350String question =

351 "Use the below article on the 2022 Winter Olympics to answer the subsequent question. "

352 + "If the answer cannot be found, write \"I don't know.\"\n\n"

353 + "Article:\n"

354 + article

355 + "\n\nQuestion: Which athletes won the gold medal in curling at the 2022 Winter Olympics?";

356 

357ChatCompletionCreateParams params =

358 ChatCompletionCreateParams.builder()

359 .model("gpt-4.1-mini")

360 .addSystemMessage("You answer questions about the 2022 Winter Olympics.")

361 .addUserMessage(question)

362 .temperature(0)

363 .build();

364 

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

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

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

368```

369 

265 370 

266Text search using embeddings371Text search using embeddings

267 372 


285res = search_reviews(df, "delicious beans", n=3)390res = search_reviews(df, "delicious beans", n=3)

286```391```

287 392 

393```java

394import com.openai.client.OpenAIClient;

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

396import com.openai.models.embeddings.EmbeddingCreateParams;

397import java.util.Comparator;

398import java.util.List;

399import java.util.stream.IntStream;

400 

401List<String> reviews =

402 List.of(

403 "A rich cup of coffee.",

404 "Smooth beans in tomato sauce.",

405 "Dark chocolate with orange.");

406var reviewEmbeddings =

407 client

408 .embeddings()

409 .create(

410 EmbeddingCreateParams.builder()

411 .model("text-embedding-3-small")

412 .inputOfArrayOfStrings(reviews)

413 .build())

414 .data();

415List<Float> query =

416 client

417 .embeddings()

418 .create(

419 EmbeddingCreateParams.builder()

420 .model("text-embedding-3-small")

421 .inputOfArrayOfStrings(List.of("delicious beans"))

422 .build())

423 .data()

424 .get(0)

425 .embedding();

426 

427IntStream.range(0, reviews.size())

428 .boxed()

429 .sorted(

430 Comparator.comparingDouble(

431 (Integer index) ->

432 cosineSimilarity(query, reviewEmbeddings.get(index).embedding()))

433 .reversed())

434 .limit(3)

435 .map(reviews::get)

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

437```

438 

288 439 

289Code search using embeddings440Code search using embeddings

290 441 


316res = search_functions(df, "Completions API tests", n=3)467res = search_functions(df, "Completions API tests", n=3)

317```468```

318 469 

470```java

471import com.openai.client.OpenAIClient;

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

473import com.openai.models.embeddings.EmbeddingCreateParams;

474import java.util.Comparator;

475import java.util.List;

476import java.util.stream.IntStream;

477 

478List<String> functions =

479 List.of("def add(a, b): return a + b", "def complete(prompt): return prompt");

480var functionEmbeddings =

481 client

482 .embeddings()

483 .create(

484 EmbeddingCreateParams.builder()

485 .model("text-embedding-3-small")

486 .inputOfArrayOfStrings(functions)

487 .build())

488 .data();

489List<Float> query =

490 client

491 .embeddings()

492 .create(

493 EmbeddingCreateParams.builder()

494 .model("text-embedding-3-small")

495 .input("Completions API tests")

496 .build())

497 .data()

498 .get(0)

499 .embedding();

500IntStream.range(0, functions.size())

501 .boxed()

502 .sorted(

503 Comparator.comparingDouble(

504 (Integer index) ->

505 cosineSimilarity(query, functionEmbeddings.get(index).embedding()))

506 .reversed())

507 .map(functions::get)

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

509```

510 

319 511 

320Recommendations using embeddings512Recommendations using embeddings

321 513 


354 return indices_of_nearest_neighbors546 return indices_of_nearest_neighbors

355```547```

356 548 

549```java

550import com.openai.client.OpenAIClient;

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

552import com.openai.models.embeddings.EmbeddingCreateParams;

553import java.util.Comparator;

554import java.util.List;

555import java.util.stream.IntStream;

556 

557List<String> strings =

558 List.of(

559 "A cheetah is a fast land animal.",

560 "A peregrine falcon is a fast bird.",

561 "A tortoise moves slowly.");

562 

563var embeddings =

564 client

565 .embeddings()

566 .create(

567 EmbeddingCreateParams.builder()

568 .model("text-embedding-3-small")

569 .inputOfArrayOfStrings(strings)

570 .build())

571 .data();

572 

573List<Float> query = embeddings.get(0).embedding();

574var nearestNeighbors =

575 IntStream.range(0, embeddings.size())

576 .boxed()

577 .sorted(

578 Comparator.comparingDouble(

579 (Integer index) -> {

580 List<Float> candidate = embeddings.get(index).embedding();

581 double dotProduct = 0;

582 double queryMagnitude = 0;

583 double candidateMagnitude = 0;

584 for (int dimension = 0; dimension < query.size(); dimension++) {

585 dotProduct += query.get(dimension) * candidate.get(dimension);

586 queryMagnitude += query.get(dimension) * query.get(dimension);

587 candidateMagnitude += candidate.get(dimension) * candidate.get(dimension);

588 }

589 return 1 - dotProduct / Math.sqrt(queryMagnitude * candidateMagnitude);

590 }))

591 .toList();

592 

593System.out.println(nearestNeighbors);

594```

595 

357 596 

358Data visualization in 2D597Data visualization in 2D

359 598 


489)728)

490```729```

491 730 

731```java

732import com.openai.client.OpenAIClient;

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

734import com.openai.models.embeddings.EmbeddingCreateParams;

735import java.util.List;

736 

737var embeddings =

738 client

739 .embeddings()

740 .create(

741 EmbeddingCreateParams.builder()

742 .model("text-embedding-3-small")

743 .inputOfArrayOfStrings(List.of("negative", "positive", "Sample Review"))

744 .build())

745 .data();

746 

747List<Float> review = embeddings.get(2).embedding();

748double negative = cosineSimilarity(review, embeddings.get(0).embedding());

749double positive = cosineSimilarity(review, embeddings.get(1).embedding());

750System.out.println(positive > negative ? "positive" : "negative");

751```

752 

492 753 

493Obtaining user and product embeddings for cold-start recommendation754Obtaining user and product embeddings for cold-start recommendation

494 755 

Details

291}291}

292```292```

293 293 

294```java

295import com.openai.client.OpenAIClient;

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

297import com.openai.errors.OpenAIServiceException;

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

299 

300try {

301 var response =

302 client

303 .responses()

304 .create(

305 ResponseCreateParams.builder().model("gpt-5.6").input("Say hello.").build());

306 

307 response.output().stream()

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

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

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

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

312} catch (OpenAIServiceException error) {

313 System.err.println(error.getMessage());

314}

315```

316 

294```ruby317```ruby

295require "openai"318require "openai"

296 319 

guides/evals.md +52 −0

Details

109}109}

110```110```

111 111 

112```java

113import com.openai.client.OpenAIClient;

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

115import com.openai.models.responses.EasyInputMessage;

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

117import com.openai.models.responses.ResponseInputItem;

118import java.util.List;

119 

120ResponseCreateParams params =

121 ResponseCreateParams.builder()

122 .model("gpt-5.6")

123 .inputOfResponse(

124 List.of(

125 ResponseInputItem.ofEasyInputMessage(

126 EasyInputMessage.builder()

127 .role(EasyInputMessage.Role.DEVELOPER)

128 .content(

129 "You are an expert in categorizing IT support tickets. Categorize each request as Hardware, Software, or Other. Respond with only one of those words.")

130 .build()),

131 ResponseInputItem.ofEasyInputMessage(

132 EasyInputMessage.builder()

133 .role(EasyInputMessage.Role.USER)

134 .content("My monitor won't turn on - help!")

135 .build())))

136 .build();

137 

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

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

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

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

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

143```

144 

112```ruby145```ruby

113require "openai"146require "openai"

114 147 


410}443}

411```444```

412 445 

446```java

447import com.openai.client.OpenAIClient;

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

449import com.openai.models.files.FileCreateParams;

450import com.openai.models.files.FilePurpose;

451import java.nio.file.Path;

452 

453var file =

454 client

455 .files()

456 .create(

457 FileCreateParams.builder()

458 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

459 .purpose(FilePurpose.EVALS)

460 .build());

461 

462System.out.println(file.id());

463```

464 

413```ruby465```ruby

414require "openai"466require "openai"

415require "pathname"467require "pathname"

Details

69}69}

70```70```

71 71 

72```java

73import com.openai.client.OpenAIClient;

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

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

76 

77ResponseCreateParams params =

78 ResponseCreateParams.builder()

79 .model("gpt-5.6-sol")

80 .input("What does 'fit check for my napalm era' mean?")

81 .serviceTier(ResponseCreateParams.ServiceTier.of("fast"))

82 .build();

83 

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

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

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

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

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

89```

90 

72```ruby91```ruby

73require "openai"92require "openai"

74 93 

Details

189}189}

190```190```

191 191 

192```java

193import com.openai.client.OpenAIClient;

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

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

196import com.openai.models.responses.ResponseInputFile;

197import com.openai.models.responses.ResponseInputItem;

198import java.util.List;

199 

200ResponseCreateParams params =

201 ResponseCreateParams.builder()

202 .model("gpt-5.6")

203 .inputOfResponse(

204 List.of(

205 ResponseInputItem.ofMessage(

206 ResponseInputItem.Message.builder()

207 .role(ResponseInputItem.Message.Role.USER)

208 .addInputTextContent(

209 "Analyze the letter and provide a summary of the key points.")

210 .addContent(

211 ResponseInputFile.builder()

212 .fileUrl(

213 "https://www.berkshirehathaway.com/letters/2024ltr.pdf")

214 .build())

215 .build())))

216 .build();

217 

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

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

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

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

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

223```

224 

192```csharp225```csharp

193using OpenAI.Responses;226using OpenAI.Responses;

194#pragma warning disable OPENAI001227#pragma warning disable OPENAI001


399}432}

400```433```

401 434 

435```java

436import com.openai.client.OpenAIClient;

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

438import com.openai.models.files.FileCreateParams;

439import com.openai.models.files.FilePurpose;

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

441import com.openai.models.responses.ResponseInputFile;

442import com.openai.models.responses.ResponseInputItem;

443import java.nio.file.Path;

444import java.util.List;

445 

446var file =

447 client

448 .files()

449 .create(

450 FileCreateParams.builder()

451 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

452 .purpose(FilePurpose.USER_DATA)

453 .build());

454 

455var response =

456 client

457 .responses()

458 .create(

459 ResponseCreateParams.builder()

460 .model("gpt-5.6")

461 .inputOfResponse(

462 List.of(

463 ResponseInputItem.ofMessage(

464 ResponseInputItem.Message.builder()

465 .role(ResponseInputItem.Message.Role.USER)

466 .addContent(

467 ResponseInputFile.builder().fileId(file.id()).build())

468 .addInputTextContent("What is the first dragon in the book?")

469 .build())))

470 .build());

471response.output().stream()

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

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

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

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

476```

477 

402```csharp478```csharp

403using OpenAI.Files;479using OpenAI.Files;

404using OpenAI.Responses;480using OpenAI.Responses;


616}692}

617```693```

618 694 

695```java

696import com.openai.client.OpenAIClient;

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

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

699import com.openai.models.responses.ResponseInputFile;

700import com.openai.models.responses.ResponseInputItem;

701import java.io.IOException;

702import java.nio.file.Files;

703import java.nio.file.Path;

704import java.util.Base64;

705import java.util.List;

706 

707String pdfData =

708 Base64.getEncoder()

709 .encodeToString(Files.readAllBytes(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH"))));

710ResponseCreateParams params =

711 ResponseCreateParams.builder()

712 .model("gpt-5.6")

713 .inputOfResponse(

714 List.of(

715 ResponseInputItem.ofMessage(

716 ResponseInputItem.Message.builder()

717 .role(ResponseInputItem.Message.Role.USER)

718 .addContent(

719 ResponseInputFile.builder()

720 .filename("document.pdf")

721 .fileData("data:application/pdf;base64," + pdfData)

722 .build())

723 .addInputTextContent("Summarize this document.")

724 .build())))

725 .build();

726 

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

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

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

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

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

732```

733 

619```ruby734```ruby

620require "base64"735require "base64"

621require "openai"736require "openai"

Details

118}118}

119```119```

120 120 

121```java

122import com.openai.client.OpenAIClient;

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

124import com.openai.models.finetuning.jobs.JobCreateParams;

125import com.openai.models.finetuning.methods.SupervisedHyperparameters;

126import com.openai.models.finetuning.methods.SupervisedMethod;

127 

128String fileId = "file-abc123";

129 

130var job =

131 client

132 .fineTuning()

133 .jobs()

134 .create(

135 JobCreateParams.builder()

136 .model("gpt-4.1-mini-2025-04-14")

137 .trainingFile(fileId)

138 .method(

139 JobCreateParams.Method.builder()

140 .type(JobCreateParams.Method.Type.SUPERVISED)

141 .supervised(

142 SupervisedMethod.builder()

143 .hyperparameters(

144 SupervisedHyperparameters.builder().nEpochs(2).build())

145 .build())

146 .build())

147 .build());

148 

149System.out.println(job.id());

150```

151 

121```ruby152```ruby

122require "openai"153require "openai"

123 154 

Details

82}82}

83```83```

84 84 

85```java

86import com.openai.client.OpenAIClient;

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

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

89import java.time.Duration;

90 

91client = client.withOptions(options -> options.timeout(Duration.ofMinutes(15)));

92 

93ResponseCreateParams params =

94 ResponseCreateParams.builder()

95 .model("gpt-5.6")

96 .input("<very long text of book here>")

97 .instructions("List and describe all the metaphors used in this book.")

98 .serviceTier(ResponseCreateParams.ServiceTier.FLEX)

99 .build();

100 

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

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

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

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

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

106```

107 

85```ruby108```ruby

86require "openai"109require "openai"

87 110 

Details

304}304}

305```305```

306 306 

307```java

308import com.openai.client.OpenAIClient;

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

310import com.openai.core.JsonValue;

311import com.openai.models.responses.FunctionTool;

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

313import com.openai.models.responses.ResponseInputItem;

314import java.util.List;

315import java.util.Map;

316 

317FunctionTool horoscope =

318 FunctionTool.builder()

319 .name("get_horoscope")

320 .description("Get today's horoscope for an astrological sign.")

321 .parameters(

322 FunctionTool.Parameters.builder()

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

324 .putAdditionalProperty(

325 "properties",

326 JsonValue.from(

327 Map.of(

328 "sign",

329 Map.of(

330 "type", "string",

331 "description",

332 "An astrological sign like Taurus or Aquarius"))))

333 .putAdditionalProperty("required", JsonValue.from(List.of("sign")))

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

335 .build())

336 .strict(true)

337 .build();

338 

339var firstResponse =

340 client

341 .responses()

342 .create(

343 ResponseCreateParams.builder()

344 .model("gpt-5.6")

345 .input("What is my horoscope? I am an Aquarius.")

346 .addTool(horoscope)

347 .build());

348 

349var functionCall =

350 firstResponse.output().stream()

351 .flatMap(item -> item.functionCall().stream())

352 .filter(call -> call.name().equals("get_horoscope"))

353 .findFirst()

354 .orElseThrow(() -> new IllegalStateException("The model did not call get_horoscope"));

355 

356record HoroscopeArguments(String sign) {}

357 

358String sign = functionCall.arguments(HoroscopeArguments.class).sign();

359ResponseCreateParams followUp =

360 ResponseCreateParams.builder()

361 .model("gpt-5.6")

362 .instructions("Respond only with a horoscope generated by a tool.")

363 .previousResponseId(firstResponse.id())

364 .inputOfResponse(

365 List.of(

366 ResponseInputItem.ofFunctionCallOutput(

367 ResponseInputItem.FunctionCallOutput.builder()

368 .callId(functionCall.callId())

369 .output(sign + ": Embrace an unexpected opportunity today.")

370 .build())))

371 .addTool(horoscope)

372 .build();

373 

374client.responses().create(followUp).output().stream()

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

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

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

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

379```

380 

307```ruby381```ruby

308require "json"382require "json"

309require "openai"383require "openai"


578}652}

579```653```

580 654 

655```java

656import com.openai.client.OpenAIClient;

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

658import com.openai.core.JsonValue;

659import com.openai.models.responses.EasyInputMessage;

660import com.openai.models.responses.FunctionTool;

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

662import com.openai.models.responses.ResponseInputItem;

663import java.util.ArrayList;

664import java.util.List;

665import java.util.Map;

666 

667response.output().stream()

668 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

669 .forEach(input::add);

670response.output().stream()

671 .flatMap(item -> item.functionCall().stream())

672 .forEach(

673 call -> {

674 String result;

675 if (call.name().equals("get_weather")) {

676 record Coordinates(double latitude, double longitude) {}

677 

678 Coordinates coordinates = call.arguments(Coordinates.class);

679 result =

680 JsonValue.from(

681 Map.of(

682 "latitude", coordinates.latitude(),

683 "longitude", coordinates.longitude(),

684 "temperature_c", 18))

685 .toString();

686 } else if (call.name().equals("send_email")) {

687 record Email(String to, String body) {}

688 

689 Email message = call.arguments(Email.class);

690 result = JsonValue.from(Map.of("to", message.to(), "status", "sent")).toString();

691 } else {

692 throw new IllegalArgumentException("Unknown function: " + call.name());

693 }

694 var output =

695 ResponseInputItem.ofFunctionCallOutput(

696 ResponseInputItem.FunctionCallOutput.builder()

697 .callId(call.callId())

698 .output(result)

699 .build());

700 input.add(output);

701 System.out.println(call.callId() + " " + result);

702 });

703```

704 

581```ruby705```ruby

582input.concat(response.output)706input.concat(response.output)

583 707 


700}824}

701```825```

702 826 

827```java

828import com.openai.client.OpenAIClient;

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

830import com.openai.core.JsonValue;

831import com.openai.models.responses.EasyInputMessage;

832import com.openai.models.responses.FunctionTool;

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

834import com.openai.models.responses.ResponseFunctionToolCall;

835import com.openai.models.responses.ResponseInputItem;

836import java.util.List;

837import java.util.Map;

838 

839FunctionTool weather =

840 FunctionTool.builder()

841 .name("get_weather")

842 .description("Get the weather for a city.")

843 .parameters(

844 FunctionTool.Parameters.builder()

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

846 .putAdditionalProperty(

847 "properties", JsonValue.from(Map.of("city", Map.of("type", "string"))))

848 .putAdditionalProperty("required", JsonValue.from(List.of("city")))

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

850 .build())

851 .strict(true)

852 .build();

853 

854ResponseCreateParams params =

855 ResponseCreateParams.builder()

856 .model("gpt-5.6")

857 .inputOfResponse(

858 List.of(

859 ResponseInputItem.ofEasyInputMessage(

860 EasyInputMessage.builder()

861 .role(EasyInputMessage.Role.USER)

862 .content("What is the weather like in Paris?")

863 .build()),

864 ResponseInputItem.ofFunctionCall(

865 ResponseFunctionToolCall.builder()

866 .callId("call_weather")

867 .name("get_weather")

868 .arguments("{\"city\":\"Paris\"}")

869 .build()),

870 ResponseInputItem.ofFunctionCallOutput(

871 ResponseInputItem.FunctionCallOutput.builder()

872 .callId("call_weather")

873 .output("{\"city\":\"Paris\",\"temperature_c\":18}")

874 .build())))

875 .addTool(weather)

876 .build();

877 

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

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

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

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

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

883```

884 

703```ruby885```ruby

704require "openai"886require "openai"

705 887 


1021}1203}

1022```1204```

1023 1205 

1206```java

1207import com.openai.client.OpenAIClient;

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

1209import com.openai.core.JsonValue;

1210import com.openai.core.http.StreamResponse;

1211import com.openai.models.responses.FunctionTool;

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

1213import com.openai.models.responses.ResponseStreamEvent;

1214import java.util.List;

1215import java.util.Map;

1216 

1217FunctionTool weather =

1218 FunctionTool.builder()

1219 .name("get_weather")

1220 .description("Get the weather for a city.")

1221 .parameters(

1222 FunctionTool.Parameters.builder()

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

1224 .putAdditionalProperty(

1225 "properties", JsonValue.from(Map.of("city", Map.of("type", "string"))))

1226 .putAdditionalProperty("required", JsonValue.from(List.of("city")))

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

1228 .build())

1229 .strict(true)

1230 .build();

1231ResponseCreateParams params =

1232 ResponseCreateParams.builder()

1233 .model("gpt-5.6")

1234 .input("What is the weather in Paris?")

1235 .addTool(weather)

1236 .build();

1237 

1238try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

1239 stream.stream()

1240 .forEach(

1241 event -> {

1242 System.out.println(event);

1243 event

1244 .outputItemAdded()

1245 .ifPresent(added -> System.out.println("response.output_item.added: " + added));

1246 event

1247 .functionCallArgumentsDelta()

1248 .ifPresent(

1249 delta ->

1250 System.out.println("response.function_call_arguments.delta: " + delta));

1251 });

1252}

1253```

1254 

1024```ruby1255```ruby

1025require "openai"1256require "openai"

1026 1257 


1158}1389}

1159```1390```

1160 1391 

1392```java

1393import com.openai.client.OpenAIClient;

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

1395import com.openai.core.JsonValue;

1396import com.openai.core.http.StreamResponse;

1397import com.openai.models.responses.FunctionTool;

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

1399import com.openai.models.responses.ResponseFunctionToolCall;

1400import com.openai.models.responses.ResponseStreamEvent;

1401import java.util.LinkedHashMap;

1402import java.util.List;

1403import java.util.Map;

1404 

1405FunctionTool weather =

1406 FunctionTool.builder()

1407 .name("get_weather")

1408 .description("Get the weather for a city.")

1409 .parameters(

1410 FunctionTool.Parameters.builder()

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

1412 .putAdditionalProperty(

1413 "properties", JsonValue.from(Map.of("location", Map.of("type", "string"))))

1414 .putAdditionalProperty("required", JsonValue.from(List.of("location")))

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

1416 .build())

1417 .strict(true)

1418 .build();

1419ResponseCreateParams params =

1420 ResponseCreateParams.builder()

1421 .model("gpt-5.6")

1422 .input("What is the weather in Paris?")

1423 .addTool(weather)

1424 .build();

1425 

1426Map<Long, ResponseFunctionToolCall> toolCalls = new LinkedHashMap<>();

1427try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

1428 stream.stream()

1429 .forEach(

1430 event -> {

1431 event

1432 .outputItemAdded()

1433 .ifPresent(

1434 added ->

1435 added

1436 .item()

1437 .functionCall()

1438 .ifPresent(call -> toolCalls.put(added.outputIndex(), call)));

1439 event

1440 .functionCallArgumentsDelta()

1441 .ifPresent(

1442 delta ->

1443 toolCalls.computeIfPresent(

1444 delta.outputIndex(),

1445 (ignored, call) ->

1446 call.toBuilder()

1447 .arguments(call.arguments() + delta.delta())

1448 .build()));

1449 });

1450}

1451toolCalls.values().forEach(System.out::println);

1452```

1453 

1161```ruby1454```ruby

1162require "openai"1455require "openai"

1163 1456 


1299}1592}

1300```1593```

1301 1594 

1595```java

1596import com.openai.client.OpenAIClient;

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

1598import com.openai.models.responses.CustomTool;

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

1600 

1601ResponseCreateParams params =

1602 ResponseCreateParams.builder()

1603 .model("gpt-5.6")

1604 .input("Use code_exec to print hello world.")

1605 .addTool(

1606 CustomTool.builder()

1607 .name("code_exec")

1608 .description("Executes arbitrary Python code.")

1609 .build())

1610 .build();

1611 

1612client.responses().create(params).output().forEach(System.out::println);

1613```

1614 

1302```ruby1615```ruby

1303require "openai"1616require "openai"

1304 1617 


1462}1775}

1463```1776```

1464 1777 

1778```java

1779import com.openai.client.OpenAIClient;

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

1781import com.openai.models.CustomToolInputFormat;

1782import com.openai.models.responses.CustomTool;

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

1784 

1785String grammar =

1786 """

1787 start: expr

1788 expr: term (SP ADD SP term)*

1789 term: INT

1790 SP: " "

1791 ADD: "+"

1792 %import common.INT

1793 """;

1794 

1795ResponseCreateParams params =

1796 ResponseCreateParams.builder()

1797 .model("gpt-5.6")

1798 .input("Use math_exp to add four plus four.")

1799 .addTool(

1800 CustomTool.builder()

1801 .name("math_exp")

1802 .description("Creates valid mathematical expressions.")

1803 .format(

1804 CustomToolInputFormat.Grammar.builder()

1805 .syntax(CustomToolInputFormat.Grammar.Syntax.LARK)

1806 .definition(grammar)

1807 .build())

1808 .build())

1809 .build();

1810 

1811client.responses().create(params).output().forEach(System.out::println);

1812```

1813 

1465```ruby1814```ruby

1466require "openai"1815require "openai"

1467 1816 


1684}2033}

1685```2034```

1686 2035 

2036```java

2037import com.openai.client.OpenAIClient;

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

2039import com.openai.models.CustomToolInputFormat;

2040import com.openai.models.responses.CustomTool;

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

2042 

2043String grammar =

2044 "^(January|February|March|April|May|June|July|August|September|October|November|December) "

2045 + "\\d{1,2}(st|nd|rd|th)? \\d{4} at (0?[1-9]|1[0-2])(AM|PM)$";

2046 

2047ResponseCreateParams params =

2048 ResponseCreateParams.builder()

2049 .model("gpt-5.6")

2050 .input("Use timestamp to save August 7th 2025 at 10AM.")

2051 .addTool(

2052 CustomTool.builder()

2053 .name("timestamp")

2054 .description("Saves a timestamp in date and time format.")

2055 .format(

2056 CustomToolInputFormat.Grammar.builder()

2057 .syntax(CustomToolInputFormat.Grammar.Syntax.REGEX)

2058 .definition(grammar)

2059 .build())

2060 .build())

2061 .build();

2062 

2063client.responses().create(params).output().forEach(System.out::println);

2064```

2065 

1687```ruby2066```ruby

1688require "openai"2067require "openai"

1689 2068 

Details

141}141}

142```142```

143 143 

144```java

145import com.openai.client.OpenAIClient;

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

147import com.openai.models.images.ImageGenerateParams;

148import java.io.IOException;

149import java.nio.file.Files;

150import java.nio.file.Path;

151import java.util.Base64;

152 

153var images =

154 client

155 .images()

156 .generate(

157 ImageGenerateParams.builder()

158 .model("gpt-image-2")

159 .prompt("A watercolor robot reading in a library")

160 .build());

161 

162Files.write(

163 Path.of("generated-image.png"),

164 Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));

165```

166 

144```ruby167```ruby

145require "base64"168require "base64"

146require "openai"169require "openai"


277}300}

278```301```

279 302 

303```java

304import com.openai.client.OpenAIClient;

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

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

307import com.openai.models.responses.Tool;

308import java.nio.file.Files;

309import java.nio.file.Path;

310import java.util.Base64;

311 

312ResponseCreateParams params =

313 ResponseCreateParams.builder()

314 .model("gpt-5.6")

315 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

316 .addTool(Tool.ImageGeneration.builder().build())

317 .build();

318 

319var image =

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

321 .flatMap(item -> item.imageGenerationCall().stream())

322 .findFirst()

323 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

324String encoded =

325 image.result().orElseThrow(() -> new IllegalStateException("No image returned"));

326Files.write(Path.of("otter.png"), Base64.getDecoder().decode(encoded));

327```

328 

280```ruby329```ruby

281require "base64"330require "base64"

282require "openai"331require "openai"


399}448}

400```449```

401 450 

451```java

452import com.openai.client.OpenAIClient;

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

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

455import com.openai.models.responses.Tool;

456import java.io.IOException;

457import java.nio.file.Files;

458import java.nio.file.Path;

459import java.util.Base64;

460 

461ResponseCreateParams params =

462 ResponseCreateParams.builder()

463 .model("gpt-5.6")

464 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

465 .addTool(

466 Tool.ImageGeneration.builder().action(Tool.ImageGeneration.Action.GENERATE).build())

467 .build();

468 

469String imageResult =

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

471 .flatMap(item -> item.imageGenerationCall().stream())

472 .flatMap(call -> call.result().stream())

473 .findFirst()

474 .orElseThrow(() -> new IllegalStateException("No generated image returned"));

475Path output = Path.of(System.getenv().getOrDefault("OPENAI_EXAMPLE_OUTPUT_PATH", "otter.png"));

476Files.write(output, Base64.getDecoder().decode(imageResult));

477System.out.println(output);

478```

479 

402```ruby480```ruby

403require "base64"481require "base64"

404require "openai"482require "openai"


580}658}

581```659```

582 660 

661```java

662import com.openai.client.OpenAIClient;

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

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

665import com.openai.models.responses.Tool;

666import java.nio.file.Files;

667import java.nio.file.Path;

668import java.util.Base64;

669 

670var first =

671 client

672 .responses()

673 .create(

674 ResponseCreateParams.builder()

675 .model("gpt-5.6")

676 .input(

677 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

678 .addTool(Tool.ImageGeneration.builder().build())

679 .build());

680var firstImage =

681 first.output().stream()

682 .flatMap(item -> item.imageGenerationCall().stream())

683 .findFirst()

684 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

685Files.write(

686 Path.of("cat_and_otter.png"),

687 Base64.getDecoder()

688 .decode(

689 firstImage

690 .result()

691 .orElseThrow(() -> new IllegalStateException("No image returned"))));

692 

693var second =

694 client

695 .responses()

696 .create(

697 ResponseCreateParams.builder()

698 .model("gpt-5.6")

699 .input("Now make it look realistic.")

700 .previousResponseId(first.id())

701 .addTool(Tool.ImageGeneration.builder().build())

702 .build());

703var secondImage =

704 second.output().stream()

705 .flatMap(item -> item.imageGenerationCall().stream())

706 .findFirst()

707 .orElseThrow(

708 () -> new IllegalStateException("No follow-up image generation call returned"));

709Files.write(

710 Path.of("cat_and_otter_realistic.png"),

711 Base64.getDecoder()

712 .decode(

713 secondImage

714 .result()

715 .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));

716```

717 

583```ruby718```ruby

584require "base64"719require "base64"

585require "openai"720require "openai"


810}945}

811```946```

812 947 

948```java

949import com.openai.client.OpenAIClient;

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

951import com.openai.core.JsonValue;

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

953import com.openai.models.responses.ResponseInputItem;

954import com.openai.models.responses.Tool;

955import java.nio.file.Files;

956import java.nio.file.Path;

957import java.util.Base64;

958import java.util.List;

959import java.util.Map;

960 

961var first =

962 client

963 .responses()

964 .create(

965 ResponseCreateParams.builder()

966 .model("gpt-5.6")

967 .input(

968 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

969 .addTool(Tool.ImageGeneration.builder().build())

970 .build());

971var firstImage =

972 first.output().stream()

973 .flatMap(item -> item.imageGenerationCall().stream())

974 .findFirst()

975 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

976Files.write(

977 Path.of("cat_and_otter.png"),

978 Base64.getDecoder()

979 .decode(

980 firstImage

981 .result()

982 .orElseThrow(() -> new IllegalStateException("No image returned"))));

983 

984var second =

985 client

986 .responses()

987 .create(

988 ResponseCreateParams.builder()

989 .model("gpt-5.6")

990 .inputOfResponse(

991 List.of(

992 ResponseInputItem.ofMessage(

993 ResponseInputItem.Message.builder()

994 .role(ResponseInputItem.Message.Role.USER)

995 .addInputTextContent("Now make it look realistic.")

996 .build()),

997 JsonValue.from(

998 Map.of("type", "image_generation_call", "id", firstImage.id()))

999 .convert(ResponseInputItem.class)))

1000 .addTool(Tool.ImageGeneration.builder().build())

1001 .build());

1002var secondImage =

1003 second.output().stream()

1004 .flatMap(item -> item.imageGenerationCall().stream())

1005 .findFirst()

1006 .orElseThrow(

1007 () -> new IllegalStateException("No follow-up image generation call returned"));

1008Files.write(

1009 Path.of("cat_and_otter_realistic.png"),

1010 Base64.getDecoder()

1011 .decode(

1012 secondImage

1013 .result()

1014 .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));

1015```

1016 

813```ruby1017```ruby

814require "base64"1018require "base64"

815require "openai"1019require "openai"


1032}1236}

1033```1237```

1034 1238 

1239```java

1240import com.openai.client.OpenAIClient;

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

1242import com.openai.core.http.StreamResponse;

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

1244import com.openai.models.responses.ResponseStreamEvent;

1245import com.openai.models.responses.Tool;

1246import java.io.IOException;

1247import java.nio.file.Files;

1248import java.nio.file.Path;

1249import java.util.Base64;

1250 

1251ResponseCreateParams params =

1252 ResponseCreateParams.builder()

1253 .model("gpt-5.6")

1254 .input("Generate an image of a river made of white owl feathers.")

1255 .addTool(Tool.ImageGeneration.builder().partialImages(2).build())

1256 .build();

1257 

1258try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

1259 var events = stream.stream().iterator();

1260 while (events.hasNext()) {

1261 ResponseStreamEvent event = events.next();

1262 if (event.imageGenerationCallPartialImage().isPresent()) {

1263 var partial = event.imageGenerationCallPartialImage().orElseThrow();

1264 Files.write(

1265 Path.of("river-partial-" + partial.partialImageIndex() + ".png"),

1266 Base64.getDecoder().decode(partial.partialImageB64()));

1267 }

1268 if (event.completed().isPresent()) {

1269 var image =

1270 event.completed().orElseThrow().response().output().stream()

1271 .flatMap(item -> item.imageGenerationCall().stream())

1272 .findFirst()

1273 .orElseThrow(() -> new IllegalStateException("No generated image returned"));

1274 Files.write(

1275 Path.of("river-final.png"),

1276 Base64.getDecoder()

1277 .decode(

1278 image

1279 .result()

1280 .orElseThrow(

1281 () -> new IllegalStateException("No final image returned"))));

1282 }

1283 }

1284}

1285```

1286 

1035```ruby1287```ruby

1036require "base64"1288require "base64"

1037require "openai"1289require "openai"


1309}1561}

1310```1562```

1311 1563 

1564```java

1565import com.openai.client.OpenAIClient;

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

1567import com.openai.models.files.FileCreateParams;

1568import com.openai.models.files.FilePurpose;

1569import java.nio.file.Path;

1570 

1571var file =

1572 client

1573 .files()

1574 .create(

1575 FileCreateParams.builder()

1576 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

1577 .purpose(FilePurpose.VISION)

1578 .build());

1579 

1580System.out.println(file.id());

1581```

1582 

1312```ruby1583```ruby

1313require "openai"1584require "openai"

1314require "pathname"1585require "pathname"


1593}1864}

1594```1865```

1595 1866 

1867```java

1868import com.openai.client.OpenAIClient;

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

1870import com.openai.models.files.FileCreateParams;

1871import com.openai.models.files.FilePurpose;

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

1873import com.openai.models.responses.ResponseInputImage;

1874import com.openai.models.responses.ResponseInputItem;

1875import com.openai.models.responses.Tool;

1876import java.nio.file.Files;

1877import java.nio.file.Path;

1878import java.util.Base64;

1879import java.util.List;

1880 

1881Path lotionImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"));

1882Path soapImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_2"));

1883Path bathBombImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_3"));

1884Path incenseImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_4"));

1885String lotionBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(lotionImage));

1886String soapBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(soapImage));

1887var firstFile =

1888 client

1889 .files()

1890 .create(

1891 FileCreateParams.builder().file(bathBombImage).purpose(FilePurpose.VISION).build());

1892var secondFile =

1893 client

1894 .files()

1895 .create(

1896 FileCreateParams.builder().file(incenseImage).purpose(FilePurpose.VISION).build());

1897String prompt =

1898 """

1899 Generate a photorealistic image of a gift basket on a white background

1900 labeled 'Relax & Unwind' with a ribbon and handwriting-like font,

1901 containing all the items in the reference pictures.

1902 """;

1903var input =

1904 ResponseInputItem.ofMessage(

1905 ResponseInputItem.Message.builder()

1906 .role(ResponseInputItem.Message.Role.USER)

1907 .addInputTextContent(prompt)

1908 .addContent(

1909 ResponseInputImage.builder()

1910 .detail(ResponseInputImage.Detail.AUTO)

1911 .imageUrl("data:image/png;base64," + lotionBase64)

1912 .build())

1913 .addContent(

1914 ResponseInputImage.builder()

1915 .detail(ResponseInputImage.Detail.AUTO)

1916 .imageUrl("data:image/png;base64," + soapBase64)

1917 .build())

1918 .addContent(

1919 ResponseInputImage.builder()

1920 .detail(ResponseInputImage.Detail.AUTO)

1921 .fileId(firstFile.id())

1922 .build())

1923 .addContent(

1924 ResponseInputImage.builder()

1925 .detail(ResponseInputImage.Detail.AUTO)

1926 .fileId(secondFile.id())

1927 .build())

1928 .build());

1929var response =

1930 client

1931 .responses()

1932 .create(

1933 ResponseCreateParams.builder()

1934 .model("gpt-5.6")

1935 .inputOfResponse(List.of(input))

1936 .addTool(Tool.ImageGeneration.builder().build())

1937 .build());

1938var image =

1939 response.output().stream()

1940 .flatMap(item -> item.imageGenerationCall().stream())

1941 .findFirst()

1942 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

1943Files.write(

1944 Path.of("gift-basket.png"),

1945 Base64.getDecoder()

1946 .decode(

1947 image.result().orElseThrow(() -> new IllegalStateException("No image returned"))));

1948```

1949 

1596```ruby1950```ruby

1597require "base64"1951require "base64"

1598require "openai"1952require "openai"


1787}2141}

1788```2142```

1789 2143 

2144```java

2145import com.openai.client.OpenAIClient;

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

2147import com.openai.core.MultipartField;

2148import com.openai.models.images.ImageEditParams;

2149import java.io.IOException;

2150import java.io.InputStream;

2151import java.nio.file.Files;

2152import java.nio.file.Path;

2153import java.util.Base64;

2154import java.util.List;

2155 

2156Path lotion = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"));

2157Path soap = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_2"));

2158Path bathBomb = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_3"));

2159Path incense = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_4"));

2160try (InputStream lotionImage = Files.newInputStream(lotion);

2161 InputStream bathBombImage = Files.newInputStream(bathBomb);

2162 InputStream incenseImage = Files.newInputStream(incense);

2163 InputStream soapImage = Files.newInputStream(soap)) {

2164 var images =

2165 client

2166 .images()

2167 .edit(

2168 ImageEditParams.builder()

2169 .model("gpt-image-2")

2170 .image(

2171 MultipartField.<ImageEditParams.Image>builder()

2172 .value(

2173 ImageEditParams.Image.ofInputStreams(

2174 List.of(lotionImage, bathBombImage, incenseImage, soapImage)))

2175 .contentType("image/png")

2176 .filename("gift-basket-reference.png")

2177 .build())

2178 .prompt(

2179 """

2180 Generate a photorealistic image of a gift basket on a white background

2181 labeled 'Relax & Unwind' with a ribbon and handwriting-like font,

2182 containing all the items in the reference pictures.

2183 """)

2184 .build());

2185 

2186 Files.write(

2187 Path.of("gift-basket.png"),

2188 Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));

2189}

2190```

2191 

1790```ruby2192```ruby

1791require "base64"2193require "base64"

1792require "openai"2194require "openai"


2034}2436}

2035```2437```

2036 2438 

2439```java

2440import com.openai.client.OpenAIClient;

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

2442import com.openai.models.files.FileCreateParams;

2443import com.openai.models.files.FilePurpose;

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

2445import com.openai.models.responses.ResponseInputImage;

2446import com.openai.models.responses.ResponseInputItem;

2447import com.openai.models.responses.Tool;

2448import java.io.IOException;

2449import java.nio.file.Files;

2450import java.nio.file.Path;

2451import java.util.Base64;

2452import java.util.List;

2453 

2454var image =

2455 client

2456 .files()

2457 .create(

2458 FileCreateParams.builder()

2459 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

2460 .purpose(FilePurpose.VISION)

2461 .build());

2462 

2463var mask =

2464 client

2465 .files()

2466 .create(

2467 FileCreateParams.builder()

2468 .file(Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_MASK_PATH")))

2469 .purpose(FilePurpose.VISION)

2470 .build());

2471 

2472var response =

2473 client

2474 .responses()

2475 .create(

2476 ResponseCreateParams.builder()

2477 .model("gpt-5.6")

2478 .inputOfResponse(

2479 List.of(

2480 ResponseInputItem.ofMessage(

2481 ResponseInputItem.Message.builder()

2482 .role(ResponseInputItem.Message.Role.USER)

2483 .addInputTextContent("Add a flamingo to the pool.")

2484 .addContent(

2485 ResponseInputImage.builder()

2486 .detail(ResponseInputImage.Detail.AUTO)

2487 .fileId(image.id())

2488 .build())

2489 .build())))

2490 .addTool(

2491 Tool.ImageGeneration.builder()

2492 .inputImageMask(

2493 Tool.ImageGeneration.InputImageMask.builder()

2494 .fileId(mask.id())

2495 .build())

2496 .build())

2497 .build());

2498 

2499String imageResult =

2500 response.output().stream()

2501 .flatMap(item -> item.imageGenerationCall().stream())

2502 .flatMap(call -> call.result().stream())

2503 .findFirst()

2504 .orElseThrow(() -> new IllegalStateException("No generated image returned"));

2505Files.write(Path.of("lounge.png"), Base64.getDecoder().decode(imageResult));

2506```

2507 

2037```ruby2508```ruby

2038require "base64"2509require "base64"

2039require "openai"2510require "openai"


2163}2634}

2164```2635```

2165 2636 

2637```java

2638import com.openai.client.OpenAIClient;

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

2640import com.openai.core.MultipartField;

2641import com.openai.models.images.ImageEditParams;

2642import java.io.IOException;

2643import java.io.InputStream;

2644import java.nio.file.Files;

2645import java.nio.file.Path;

2646import java.util.Base64;

2647 

2648Path imagePath = Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH"));

2649Path maskPath = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_MASK_PATH"));

2650try (InputStream image = Files.newInputStream(imagePath);

2651 InputStream mask = Files.newInputStream(maskPath)) {

2652 var images =

2653 client

2654 .images()

2655 .edit(

2656 ImageEditParams.builder()

2657 .model("gpt-image-2")

2658 .image(

2659 MultipartField.<ImageEditParams.Image>builder()

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

2661 .contentType("image/png")

2662 .filename(imagePath.getFileName().toString())

2663 .build())

2664 .prompt("A sunlit indoor lounge area with a pool containing a flamingo")

2665 .mask(

2666 MultipartField.<InputStream>builder()

2667 .value(mask)

2668 .contentType("image/png")

2669 .filename(maskPath.getFileName().toString())

2670 .build())

2671 .build());

2672 

2673 Files.write(

2674 Path.of("lounge.png"),

2675 Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));

2676}

2677```

2678 

2166```ruby2679```ruby

2167require "openai"2680require "openai"

2168require "pathname"2681require "pathname"


2316- **Quality**: Rendering quality (for example, `low`, `medium`, `high`)2829- **Quality**: Rendering quality (for example, `low`, `medium`, `high`)

2317- **Format**: File output format2830- **Format**: File output format

2318- **Compression**: Compression level (0-100%) for JPEG and WebP formats2831- **Compression**: Compression level (0-100%) for JPEG and WebP formats

2319- **Background**: Opaque or automatic2832- **Background**: Transparent, opaque, or automatic

2320 2833 

2321`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.2834`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.

2322 2835 

2323`gpt-image-2` doesn't currently support transparent backgrounds. Requests with2836Transparent backgrounds are available in preview for `gpt-image-2`. Set

2324 `background: "transparent"` aren't supported for this model.2837 `background: "transparent"` to request one. Use `png` (the default) or `webp`;

2838 `jpeg` isn't supported with transparent backgrounds.

2325 2839 

2326### Size and quality options2840### Size and quality options

2327 2841 


2614}3128}

2615```3129```

2616 3130 

3131```java

3132import com.openai.client.OpenAIClient;

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

3134import com.openai.errors.BadRequestException;

3135import com.openai.models.images.ImageGenerateParams;

3136import java.util.List;

3137import java.util.Map;

3138 

3139try {

3140 var images =

3141 client

3142 .images()

3143 .generate(

3144 ImageGenerateParams.builder()

3145 .model("gpt-image-2")

3146 .prompt("Create a poster humiliating my coworker with insulting captions")

3147 .build());

3148 

3149 System.out.println(images.data().orElseThrow().get(0).b64Json().orElseThrow());

3150} catch (BadRequestException error) {

3151 if (!error.code().orElse("").equals("moderation_blocked")) {

3152 throw error;

3153 }

3154 Map<?, ?> body = error.body().convert(Map.class);

3155 Object detailsValue = body.get("moderation_details");

3156 Map<?, ?> details = detailsValue instanceof Map<?, ?> values ? values : Map.of();

3157 Object categories = details.get("categories");

3158 Object stage = details.get("moderation_stage");

3159 

3160 String hint = "This request did not meet safety requirements.";

3161 if (categories instanceof List<?> values && values.contains("harassment")) {

3162 hint = "Remove abusive or targeting language and focus on neutral visual details.";

3163 } else if ("input".equals(stage)) {

3164 hint = "Revise the prompt or input images, then submit the request again.";

3165 } else if ("output".equals(stage)) {

3166 hint = "Change the prompt and generate again; the generated result was blocked.";

3167 }

3168 System.err.println("Image generation blocked (" + error.code().orElseThrow() + "): " + hint);

3169}

3170```

3171 

2617```ruby3172```ruby

2618require "openai"3173require "openai"

2619 3174 

Details

132}132}

133```133```

134 134 

135```java

136import com.openai.client.OpenAIClient;

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

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

139import com.openai.models.responses.Tool;

140import java.io.IOException;

141import java.nio.file.Files;

142import java.nio.file.Path;

143import java.util.Base64;

144 

145ResponseCreateParams params =

146 ResponseCreateParams.builder()

147 .model("gpt-5.6")

148 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

149 .addTool(Tool.ImageGeneration.builder().build())

150 .build();

151 

152String imageResult =

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

154 .flatMap(item -> item.imageGenerationCall().stream())

155 .flatMap(call -> call.result().stream())

156 .findFirst()

157 .orElseThrow(() -> new IllegalStateException("No generated image returned"));

158Files.write(Path.of("cat_and_otter.png"), Base64.getDecoder().decode(imageResult));

159```

160 

135```ruby161```ruby

136require "base64"162require "base64"

137require "openai"163require "openai"


292}318}

293```319```

294 320 

321```java

322import com.openai.client.OpenAIClient;

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

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

325import com.openai.models.responses.ResponseInputImage;

326import com.openai.models.responses.ResponseInputItem;

327import java.util.List;

328 

329ResponseInputItem imageInput =

330 ResponseInputItem.ofMessage(

331 ResponseInputItem.Message.builder()

332 .role(ResponseInputItem.Message.Role.USER)

333 .addInputTextContent("What's in this image?")

334 .addContent(

335 ResponseInputImage.builder()

336 .detail(ResponseInputImage.Detail.AUTO)

337 .imageUrl(

338 "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg")

339 .build())

340 .build());

341 

342ResponseCreateParams params =

343 ResponseCreateParams.builder()

344 .model("gpt-5.6")

345 .inputOfResponse(List.of(imageInput))

346 .build();

347 

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

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

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

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

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

353```

354 

295```csharp355```csharp

296using OpenAI.Responses;356using OpenAI.Responses;

297#pragma warning disable OPENAI001357#pragma warning disable OPENAI001


502}562}

503```563```

504 564 

565```java

566import com.openai.client.OpenAIClient;

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

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

569import com.openai.models.responses.ResponseInputImage;

570import com.openai.models.responses.ResponseInputItem;

571import java.io.IOException;

572import java.nio.file.Files;

573import java.nio.file.Path;

574import java.util.Base64;

575import java.util.List;

576 

577String imageBase64 =

578 Base64.getEncoder()

579 .encodeToString(

580 Files.readAllBytes(Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"))));

581 

582ResponseInputItem imageInput =

583 ResponseInputItem.ofMessage(

584 ResponseInputItem.Message.builder()

585 .role(ResponseInputItem.Message.Role.USER)

586 .addInputTextContent("What's in this image?")

587 .addContent(

588 ResponseInputImage.builder()

589 .detail(ResponseInputImage.Detail.AUTO)

590 .imageUrl("data:image/png;base64," + imageBase64)

591 .build())

592 .build());

593 

594ResponseCreateParams params =

595 ResponseCreateParams.builder()

596 .model("gpt-5.6")

597 .inputOfResponse(List.of(imageInput))

598 .build();

599 

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

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

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

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

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

605```

606 

505```csharp607```csharp

506using OpenAI.Responses;608using OpenAI.Responses;

507#pragma warning disable OPENAI001609#pragma warning disable OPENAI001


718}820}

719```821```

720 822 

823```java

824import com.openai.client.OpenAIClient;

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

826import com.openai.models.files.FileCreateParams;

827import com.openai.models.files.FilePurpose;

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

829import com.openai.models.responses.ResponseInputImage;

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

831import java.nio.file.Path;

832import java.util.List;

833 

834var file =

835 client

836 .files()

837 .create(

838 FileCreateParams.builder()

839 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

840 .purpose(FilePurpose.VISION)

841 .build());

842 

843var response =

844 client

845 .responses()

846 .create(

847 ResponseCreateParams.builder()

848 .model("gpt-5.6")

849 .inputOfResponse(

850 List.of(

851 ResponseInputItem.ofMessage(

852 ResponseInputItem.Message.builder()

853 .role(ResponseInputItem.Message.Role.USER)

854 .addInputTextContent("What's in this image?")

855 .addContent(

856 ResponseInputImage.builder()

857 .detail(ResponseInputImage.Detail.AUTO)

858 .fileId(file.id())

859 .build())

860 .build())))

861 .build());

862response.output().stream()

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

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

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

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

867```

868 

721```csharp869```csharp

722using OpenAI.Files;870using OpenAI.Files;

723using OpenAI.Responses;871using OpenAI.Responses;

Details

255response.to_dict()["output"]255response.to_dict()["output"]

256```256```

257 257 

258```java

259import com.openai.client.OpenAIClient;

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

261import com.openai.core.JsonValue;

262import com.openai.models.responses.FunctionTool;

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

264import java.util.List;

265import java.util.Map;

266 

267String agentInstructions =

268 """

269 You will be tasked to fix an issue from an open-source repository.

270 

271 Your thinking should be thorough and so it's fine if it's very long. You can think step by step before and after each action you decide to take.

272 

273 You MUST iterate and keep going until the problem is solved.

274 

275 You already have everything you need to solve this problem in the /testbed folder, even without internet connection. I want you to fully solve this autonomously before coming back to me.

276 

277 Only terminate your turn when you are sure that the problem is solved. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.

278 

279 THE PROBLEM CAN DEFINITELY BE SOLVED WITHOUT THE INTERNET.

280 

281 Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.

282 

283 You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.

284 

285 # Workflow

286 

287 ## High-Level Problem Solving Strategy

288 

289 1. Understand the problem deeply. Carefully read the issue and think critically about what is required.

290 2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.

291 3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps.

292 4. Implement the fix incrementally. Make small, testable code changes.

293 5. Debug as needed. Use debugging techniques to isolate and resolve issues.

294 6. Test frequently. Run tests after each change to verify correctness.

295 7. Iterate until the root cause is fixed and all tests pass.

296 8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.

297 

298 Refer to the detailed sections below for more information on each step.

299 

300 ## 1. Deeply Understand the Problem

301 Carefully read the issue and think hard about a plan to solve it before coding.

302 

303 ## 2. Codebase Investigation

304 - Explore relevant files and directories.

305 - Search for key functions, classes, or variables related to the issue.

306 - Read and understand relevant code snippets.

307 - Identify the root cause of the problem.

308 - Validate and update your understanding continuously as you gather more context.

309 

310 ## 3. Develop a Detailed Plan

311 - Outline a specific, simple, and verifiable sequence of steps to fix the problem.

312 - Break down the fix into small, incremental changes.

313 

314 ## 4. Making Code Changes

315 - Before editing, always read the relevant file contents or section to ensure complete context.

316 - If a patch is not applied correctly, attempt to reapply it.

317 - Make small, testable, incremental changes that logically follow from your investigation and plan.

318 

319 ## 5. Debugging

320 - Make code changes only if you have high confidence they can solve the problem

321 - When debugging, try to determine the root cause rather than addressing symptoms

322 - Debug for as long as needed to identify the root cause and identify a fix

323 - Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening

324 - To test hypotheses, you can also add test statements or functions

325 - Revisit your assumptions if unexpected behavior occurs.

326 

327 ## 6. Testing

328 - Run tests frequently using `!python3 run_tests.py` (or equivalent).

329 - After each change, verify correctness by running relevant tests.

330 - If tests fail, analyze failures and revise your patch.

331 - Write additional tests if needed to capture important behaviors or edge cases.

332 - Ensure all tests pass before finalizing.

333 

334 ## 7. Final Verification

335 - Confirm the root cause is fixed.

336 - Review your solution for logic correctness and robustness.

337 - Iterate until you are extremely confident the fix is complete and all tests pass.

338 

339 ## 8. Final Reflection and Additional Testing

340 - Reflect carefully on the original intent of the user and the problem statement.

341 - Think about potential edge cases or scenarios that may not be covered by existing tests.

342 - Write additional tests that would need to pass to fully validate the correctness of your solution.

343 - Run these new tests and ensure they all pass.

344 - Be aware that there are additional hidden tests that must also pass for the solution to be successful.

345 - Do not assume the task is complete just because the visible tests pass; continue refining until you are confident the fix is robust and comprehensive.

346 """;

347String pythonToolDescription =

348 """

349 This function is used to execute Python code or terminal commands in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 60.0 seconds. Internet access for this session is disabled. Do not make external web requests or API calls as they will fail. Just as in a Jupyter notebook, you may also execute terminal commands by calling this function with a terminal command, prefaced with an exclamation mark.

350 

351 In addition, for the purposes of this task, you can call this function with an `apply_patch` command as input. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":

352 

353 %%bash

354 apply_patch <<"EOF"

355 *** Begin Patch

356 [YOUR_PATCH]

357 *** End Patch

358 EOF

359 

360 Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.

361 

362 *** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.

363 For each snippet of code that needs to be changed, repeat the following:

364 [context_before] -> See below for further instructions on context.

365 - [old_code] -> Precede the old code with a minus sign.

366 + [new_code] -> Precede the new, replacement code with a plus sign.

367 [context_after] -> See below for further instructions on context.

368 

369 For instructions on [context_before] and [context_after]:

370 - By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change's [context_after] lines in the second change's [context_before] lines.

371 - If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:

372 @@ class BaseClass

373 [3 lines of pre-context]

374 - [old_code]

375 + [new_code]

376 [3 lines of post-context]

377 

378 - If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:

379 

380 @@ class BaseClass

381 @@ def method():

382 [3 lines of pre-context]

383 - [old_code]

384 + [new_code]

385 [3 lines of post-context]

386 

387 Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.

388 

389 %%bash

390 apply_patch <<"EOF"

391 *** Begin Patch

392 *** Update File: pygorithm/searching/binary_search.py

393 @@ class BaseClass

394 @@ def search():

395 - pass

396 + raise NotImplementedError()

397 

398 @@ class Subclass

399 @@ def search():

400 - pass

401 + raise NotImplementedError()

402 

403 *** End Patch

404 EOF

405 

406 File references can only be relative, NEVER ABSOLUTE. After the apply_patch command is run, Python will always say "Done!", regardless of whether the patch was successfully applied or not. However, you can determine if there are issues or errors by looking at any warnings or logging lines printed BEFORE the "Done!" is output.

407 """;

408 

409ResponseCreateParams params =

410 ResponseCreateParams.builder()

411 .model("gpt-4.1-2025-04-14")

412 .instructions(agentInstructions)

413 .input("Please answer the following question:\nBug: Typerror...")

414 .addTool(

415 FunctionTool.builder()

416 .name("python")

417 .description(pythonToolDescription)

418 .parameters(

419 FunctionTool.Parameters.builder()

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

421 .putAdditionalProperty(

422 "properties",

423 JsonValue.from(

424 Map.of(

425 "input",

426 Map.of(

427 "type", "string",

428 "description",

429 "The Python code, terminal command, or apply_patch command to execute."))))

430 .putAdditionalProperty("required", JsonValue.from(List.of("input")))

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

432 .build())

433 .strict(true)

434 .build())

435 .build();

436 

437client.responses().create(params).output().forEach(System.out::println);

438```

439 

258```ruby440```ruby

259require "openai"441require "openai"

260 442 


481response.to_dict()["output"]663response.to_dict()["output"]

482```664```

483 665 

666```java

667import com.openai.client.OpenAIClient;

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

669import com.openai.core.JsonValue;

670import com.openai.models.responses.FunctionTool;

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

672import java.util.List;

673import java.util.Map;

674 

675String customerServiceInstructions =

676 """

677 You are a helpful customer service agent working for NewTelco, helping a user efficiently fulfill their request while adhering closely to provided guidelines.

678 

679 # Instructions

680 - Always greet the user with "Hi, you've reached NewTelco, how can I help you?"

681 - Always call a tool before answering factual questions about the company, its offerings or products, or a user's account. Only use retrieved context and never rely on your own knowledge for any of these questions.

682 - However, if you don't have enough information to properly call the tool, ask the user for the information you need.

683 - Escalate to a human if the user requests.

684 - Do not discuss prohibited topics (politics, religion, controversial current events, medical, legal, or financial advice, personal conversations, internal company operations, or criticism of any people or company).

685 - Rely on sample phrases whenever appropriate, but never repeat a sample phrase in the same conversation. Feel free to vary the sample phrases to avoid sounding repetitive and make it more appropriate for the user.

686 - Always follow the provided output format for new messages, including citations for any factual statements from retrieved policy documents.

687 - If you're going to call a tool, always message the user with an appropriate message before and after calling the tool.

688 - Maintain a professional and concise tone in all responses, and use emojis between sentences.

689 - If you've resolved the user's request, ask if there's anything else you can help with

690 

691 # Precise Response Steps (for each response)

692 1. If necessary, call tools to fulfill the user's desired action. Always message the user before and after calling a tool to keep them in the loop.

693 2. In your response to the user

694 a. Use active listening and echo back what you heard the user ask for.

695 b. Respond appropriately given the above guidelines.

696 

697 # Sample Phrases

698 ## Deflecting a Prohibited Topic

699 - "I'm sorry, but I'm unable to discuss that topic. Is there something else I can help you with?"

700 - "That's not something I'm able to provide information on, but I'm happy to help with any other questions you may have."

701 

702 ## Before calling a tool

703 - "To help you with that, I'll just need to verify your information."

704 - "Let me check that for you—one moment, please."

705 - "I'll retrieve the latest details for you now."

706 

707 ## After calling a tool

708 - "Okay, here's what I found: [response]"

709 - "So here's what I found: [response]"

710 

711 # Output Format

712 - Always include your final response to the user.

713 - When providing factual information from retrieved context, always include citations immediately after the relevant statement(s). Use the following citation format:

714 - For a single source: [NAME](ID)

715 - For multiple sources: [NAME](ID), [NAME](ID)

716 - Only provide information about this company, its policies, its products, or the customer's account, and only if it is based on information provided in context. Do not answer questions outside this scope.

717 

718 # Example

719 ## User

720 Can you tell me about your family plan options?

721 

722 ## Assistant Response 1

723 ### Message

724 "Hi, you've reached NewTelco, how can I help you? 😊🎉

725 

726 You'd like to know about our family plan options. 🤝 Let me check that for you—one moment, please. 🚀"

727 

728 ### Tool Calls

729 lookup_policy_document(topic="family plan options")

730 

731 // After tool call, the assistant would follow up with:

732 

733 ## Assistant Response 2 (after tool call)

734 ### Message

735 "Okay, here's what I found: 🎉 Our family plan allows up to 5 lines with shared data and a 10% discount for each additional line [Family Plan Policy](ID-010). 📱 Is there anything else I can help you with today? 😊"

736 """;

737 

738ResponseCreateParams params =

739 ResponseCreateParams.builder()

740 .model("gpt-4.1-2025-04-14")

741 .instructions(customerServiceInstructions)

742 .input("How much will it cost for international service? I'm traveling to France.")

743 .addTool(

744 customerServiceTool(

745 "lookup_policy_document",

746 "Tool to look up internal documents and policies by topic or keyword.",

747 "topic",

748 "The topic or keyword to search for in company policies or documents."))

749 .addTool(

750 customerServiceTool(

751 "get_user_account_info",

752 "Tool to get user account information",

753 "phone_number",

754 "Formatted as '(xxx) xxx-xxxx'"))

755 .build();

756 

757client.responses().create(params).output().forEach(System.out::println);

758 

759private static FunctionTool customerServiceTool(

760 String name, String description, String parameter, String parameterDescription) {

761 return FunctionTool.builder()

762 .name(name)

763 .description(description)

764 .strict(true)

765 .parameters(

766 FunctionTool.Parameters.builder()

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

768 .putAdditionalProperty(

769 "properties",

770 JsonValue.from(

771 Map.of(

772 parameter,

773 Map.of("type", "string", "description", parameterDescription))))

774 .putAdditionalProperty("required", JsonValue.from(List.of(parameter)))

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

776 .build())

777 .build();

778}

779```

780 

484```ruby781```ruby

485require "openai"782require "openai"

486 783 

Details

320)320)

321```321```

322 322 

323```java

324import com.openai.client.OpenAIClient;

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

326import com.openai.models.responses.ApplyPatchTool;

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

328 

329ResponseCreateParams params =

330 ResponseCreateParams.builder()

331 .model("gpt-5.1")

332 .input("Update the README title and fix the failing test.")

333 .addTool(ApplyPatchTool.builder().build())

334 .build();

335 

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

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

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

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

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

341```

342 

323 343 

324When the model decides to execute an apply_patch tool, you will receive an apply_patch_call function type within the response stream. Within the operation object, you’ll receive a type field (with one of `create_file`, `update_file`, or `delete_file`) and the diff to implement.344When the model decides to execute an apply_patch tool, you will receive an apply_patch_call function type within the response stream. Within the operation object, you’ll receive a type field (with one of `create_file`, `update_file`, or `delete_file`) and the diff to implement.

325 345 

Details

112}112}

113```113```

114 114 

115```java

116import com.openai.client.OpenAIClient;

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

118import com.openai.models.Reasoning;

119import com.openai.models.ReasoningEffort;

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

121 

122ResponseCreateParams params =

123 ResponseCreateParams.builder()

124 .model("gpt-5.2")

125 .input("Explain the bug and propose a fix.")

126 .reasoning(Reasoning.builder().effort(ReasoningEffort.NONE).build())

127 .build();

128 

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

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

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

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

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

134```

135 

115```ruby136```ruby

116require "openai"137require "openai"

117 138 


207}228}

208```229```

209 230 

231```java

232import com.openai.client.OpenAIClient;

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

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

235import com.openai.models.responses.ResponseTextConfig;

236 

237ResponseCreateParams params =

238 ResponseCreateParams.builder()

239 .model("gpt-5.2")

240 .input("Explain the bug and propose a fix.")

241 .text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())

242 .build();

243 

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

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

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

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

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

249```

250 

210```ruby251```ruby

211require "openai"252require "openai"

212 253 


704print(json.dumps(compacted_response.model_dump(), indent=2))745print(json.dumps(compacted_response.model_dump(), indent=2))

705```746```

706 747 

748```java

749import com.openai.client.OpenAIClient;

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

751import com.openai.core.JsonValue;

752import com.openai.models.responses.EasyInputMessage;

753import com.openai.models.responses.ResponseCompactParams;

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

755import com.openai.models.responses.ResponseInputItem;

756import java.util.ArrayList;

757 

758var input = new ArrayList<ResponseInputItem>();

759input.add(

760 ResponseInputItem.ofEasyInputMessage(

761 EasyInputMessage.builder()

762 .role(EasyInputMessage.Role.USER)

763 .content("Write a very long poem about a dog.")

764 .build()));

765var response =

766 client

767 .responses()

768 .create(ResponseCreateParams.builder().model("gpt-5.2").inputOfResponse(input).build());

769response.output().stream()

770 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

771 .forEach(input::add);

772var compacted =

773 client

774 .responses()

775 .compact(

776 ResponseCompactParams.builder()

777 .model("gpt-5.2")

778 .inputOfResponseInputItems(input)

779 .build());

780System.out.println(compacted.output());

781```

782 

707```ruby783```ruby

708require "openai"784require "openai"

709 785 

Details

115}115}

116```116```

117 117 

118```java

119import com.openai.client.OpenAIClient;

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

121import com.openai.models.Reasoning;

122import com.openai.models.ReasoningEffort;

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

124 

125ResponseCreateParams params =

126 ResponseCreateParams.builder()

127 .model("gpt-5.4")

128 .input("Explain the bug and propose a fix.")

129 .reasoning(Reasoning.builder().effort(ReasoningEffort.NONE).build())

130 .build();

131 

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

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

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

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

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

137```

138 

118```ruby139```ruby

119require "openai"140require "openai"

120 141 


210}231}

211```232```

212 233 

234```java

235import com.openai.client.OpenAIClient;

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

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

238import com.openai.models.responses.ResponseTextConfig;

239 

240ResponseCreateParams params =

241 ResponseCreateParams.builder()

242 .model("gpt-5.4")

243 .input("Explain the bug and propose a fix.")

244 .text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())

245 .build();

246 

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

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

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

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

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

252```

253 

213```ruby254```ruby

214require "openai"255require "openai"

215 256 


486}527}

487```528```

488 529 

530```java

531import com.openai.client.OpenAIClient;

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

533import com.openai.models.Reasoning;

534import com.openai.models.ReasoningEffort;

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

536 

537ResponseCreateParams params =

538 ResponseCreateParams.builder()

539 .model("gpt-5.4")

540 .input("Explain the bug and propose a fix.")

541 .reasoning(Reasoning.builder().effort(ReasoningEffort.MEDIUM).build())

542 .build();

543 

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

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

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

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

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

549```

550 

489```ruby551```ruby

490require "openai"552require "openai"

491 553 

Details

220}220}

221```221```

222 222 

223```java

224import com.openai.client.OpenAIClient;

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

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

227import com.openai.models.responses.EasyInputMessage;

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

229import com.openai.models.responses.ResponseInputItem;

230import java.util.List;

231 

232var completion =

233 client

234 .chat()

235 .completions()

236 .create(

237 ChatCompletionCreateParams.builder()

238 .model("gpt-5.6")

239 .addSystemMessage("You are a helpful assistant.")

240 .addUserMessage("Hello!")

241 .build());

242completion.choices().stream()

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

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

245 

246var response =

247 client

248 .responses()

249 .create(

250 ResponseCreateParams.builder()

251 .model("gpt-5.6")

252 .inputOfResponse(

253 List.of(

254 ResponseInputItem.ofEasyInputMessage(

255 EasyInputMessage.builder()

256 .role(EasyInputMessage.Role.SYSTEM)

257 .content("You are a helpful assistant.")

258 .build()),

259 ResponseInputItem.ofEasyInputMessage(

260 EasyInputMessage.builder()

261 .role(EasyInputMessage.Role.USER)

262 .content("Hello!")

263 .build())))

264 .build());

265response.output().stream()

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

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

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

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

270```

271 

223```ruby272```ruby

224require "openai"273require "openai"

225 274 


330}379}

331```380```

332 381 

382```java

383import com.openai.client.OpenAIClient;

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

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

386 

387ChatCompletionCreateParams params =

388 ChatCompletionCreateParams.builder()

389 .model("gpt-5.6")

390 .addSystemMessage("You are a helpful assistant.")

391 .addUserMessage("Hello!")

392 .build();

393 

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

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

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

397```

398 

333```ruby399```ruby

334require "openai"400require "openai"

335 401 


421}487}

422```488```

423 489 

490```java

491import com.openai.client.OpenAIClient;

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

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

494 

495ResponseCreateParams params =

496 ResponseCreateParams.builder()

497 .model("gpt-5.6")

498 .input("Hello!")

499 .instructions("You are a helpful assistant.")

500 .build();

501 

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

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

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

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

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

507```

508 

424```ruby509```ruby

425require "openai"510require "openai"

426 511 


544}629}

545```630```

546 631 

632```java

633import com.openai.client.OpenAIClient;

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

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

636 

637var params =

638 ChatCompletionCreateParams.builder()

639 .model("gpt-5.6")

640 .addSystemMessage("You are a helpful assistant.")

641 .addUserMessage("What is the capital of France?")

642 .build();

643var first = client.chat().completions().create(params);

644 

645var second =

646 client

647 .chat()

648 .completions()

649 .create(

650 params.toBuilder()

651 .addAssistantMessage(first.choices().get(0).message().content().orElseThrow())

652 .addUserMessage("And its population?")

653 .build());

654second.choices().stream()

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

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

657```

658 

547```ruby659```ruby

548require "openai"660require "openai"

549 661 


669}781}

670```782```

671 783 

784```java

785import com.openai.client.OpenAIClient;

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

787import com.openai.core.JsonValue;

788import com.openai.models.responses.EasyInputMessage;

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

790import com.openai.models.responses.ResponseInputItem;

791import java.util.ArrayList;

792 

793var history = new ArrayList<ResponseInputItem>();

794history.add(

795 ResponseInputItem.ofEasyInputMessage(

796 EasyInputMessage.builder()

797 .role(EasyInputMessage.Role.USER)

798 .content("What is the capital of France?")

799 .build()));

800 

801var first =

802 client

803 .responses()

804 .create(

805 ResponseCreateParams.builder().model("gpt-5.6").inputOfResponse(history).build());

806first.output().stream()

807 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

808 .forEach(history::add);

809history.add(

810 ResponseInputItem.ofEasyInputMessage(

811 EasyInputMessage.builder()

812 .role(EasyInputMessage.Role.USER)

813 .content("And its population?")

814 .build()));

815 

816client

817 .responses()

818 .create(ResponseCreateParams.builder().model("gpt-5.6").inputOfResponse(history).build())

819 .output()

820 .stream()

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

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

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

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

825```

826 

672```ruby827```ruby

673require "openai"828require "openai"

674 829 


758}913}

759```914```

760 915 

916```java

917import com.openai.client.OpenAIClient;

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

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

920 

921var first =

922 client

923 .responses()

924 .create(

925 ResponseCreateParams.builder()

926 .model("gpt-5.6")

927 .input("What is the capital of France?")

928 .store(true)

929 .build());

930 

931var second =

932 client

933 .responses()

934 .create(

935 ResponseCreateParams.builder()

936 .model("gpt-5.6")

937 .input("And its population?")

938 .previousResponseId(first.id())

939 .store(true)

940 .build());

941second.output().stream()

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

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

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

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

946```

947 

761```ruby948```ruby

762require "openai"949require "openai"

763 950 


983}1170}

984```1171```

985 1172 

1173```java

1174import com.openai.client.OpenAIClient;

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

1176import com.openai.core.JsonValue;

1177import com.openai.models.ReasoningEffort;

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

1179import java.util.List;

1180import java.util.Map;

1181 

1182ChatCompletionCreateParams params =

1183 ChatCompletionCreateParams.builder()

1184 .model("gpt-5.6")

1185 .reasoningEffort(ReasoningEffort.MEDIUM)

1186 .addUserMessage("Jane, 54 years old")

1187 .putAdditionalBodyProperty(

1188 "response_format",

1189 JsonValue.from(

1190 Map.of(

1191 "type",

1192 "json_schema",

1193 "json_schema",

1194 Map.of(

1195 "name",

1196 "person",

1197 "strict",

1198 true,

1199 "schema",

1200 Map.of(

1201 "type",

1202 "object",

1203 "properties",

1204 Map.of(

1205 "name",

1206 Map.of("type", "string", "minLength", 1),

1207 "age",

1208 Map.of("type", "number", "minimum", 0, "maximum", 130)),

1209 "required",

1210 List.of("name", "age"),

1211 "additionalProperties",

1212 false)))))

1213 .build();

1214 

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

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

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

1218```

1219 

986```ruby1220```ruby

987require "openai"1221require "openai"

988 1222 


1151}1385}

1152```1386```

1153 1387 

1388```java

1389import com.openai.client.OpenAIClient;

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

1391import com.openai.core.JsonValue;

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

1393import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

1394import com.openai.models.responses.ResponseTextConfig;

1395import java.util.List;

1396import java.util.Map;

1397 

1398ResponseCreateParams params =

1399 ResponseCreateParams.builder()

1400 .model("gpt-5.6")

1401 .input("Jane, 54 years old")

1402 .text(

1403 ResponseTextConfig.builder()

1404 .format(

1405 ResponseFormatTextJsonSchemaConfig.builder()

1406 .name("person")

1407 .strict(true)

1408 .schema(

1409 ResponseFormatTextJsonSchemaConfig.Schema.builder()

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

1411 .putAdditionalProperty(

1412 "properties",

1413 JsonValue.from(

1414 Map.of(

1415 "name",

1416 Map.of("type", "string", "minLength", 1),

1417 "age",

1418 Map.of(

1419 "type", "number", "minimum", 0, "maximum",

1420 130))))

1421 .putAdditionalProperty(

1422 "required", JsonValue.from(List.of("name", "age")))

1423 .putAdditionalProperty(

1424 "additionalProperties", JsonValue.from(false))

1425 .build())

1426 .build())

1427 .build())

1428 .build();

1429 

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

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

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

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

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

1435```

1436 

1154```ruby1437```ruby

1155require "openai"1438require "openai"

1156 1439 


1337}1620}

1338```1621```

1339 1622 

1623```java

1624import com.openai.client.OpenAIClient;

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

1626import com.openai.core.JsonValue;

1627import com.openai.models.FunctionParameters;

1628import com.openai.models.ReasoningEffort;

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

1630import java.util.List;

1631import java.util.Map;

1632 

1633ChatCompletionCreateParams params =

1634 ChatCompletionCreateParams.builder()

1635 .model("gpt-5.6")

1636 .reasoningEffort(ReasoningEffort.NONE)

1637 .addSystemMessage("You are a helpful assistant.")

1638 .addUserMessage("Who is the current president of France?")

1639 .addFunction(

1640 ChatCompletionCreateParams.Function.builder()

1641 .name("web_search")

1642 .description("Search the web for information")

1643 .parameters(

1644 FunctionParameters.builder()

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

1646 .putAdditionalProperty(

1647 "properties",

1648 JsonValue.from(Map.of("query", Map.of("type", "string"))))

1649 .putAdditionalProperty("required", JsonValue.from(List.of("query")))

1650 .build())

1651 .build())

1652 .build();

1653 

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

1655 .map(choice -> choice.message())

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

1657```

1658 

1340```ruby1659```ruby

1341require "openai"1660require "openai"

1342 1661 


1429}1748}

1430```1749```

1431 1750 

1751```java

1752import com.openai.client.OpenAIClient;

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

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

1755import com.openai.models.responses.WebSearchTool;

1756 

1757ResponseCreateParams params =

1758 ResponseCreateParams.builder()

1759 .model("gpt-5.6")

1760 .input("Who is the current president of France?")

1761 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

1762 .build();

1763 

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

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

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

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

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

1769```

1770 

1432```ruby1771```ruby

1433require "openai"1772require "openai"

1434 1773 

Details

134}134}

135```135```

136 136 

137```java

138import com.openai.client.OpenAIClient;

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

140import com.openai.core.JsonValue;

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

142import java.util.ArrayList;

143import java.util.List;

144import java.util.Map;

145 

146ResponseCreateParams params =

147 ResponseCreateParams.builder()

148 .model("gpt-5.6")

149 .input(

150 "A user asks for instructions to make a harmful weapon. Draft a brief refusal and offer a safer alternative.")

151 .putAdditionalBodyProperty(

152 "moderation", JsonValue.from(Map.of("model", "omni-moderation-latest")))

153 .build();

154 

155var response = client.responses().create(params);

156JsonValue moderation = response._additionalProperties().get("moderation");

157if (moderation == null) {

158 throw new IllegalStateException("The response did not include moderation results");

159}

160Map<?, ?> results = moderation.convert(Map.class);

161List<Boolean> flags = new ArrayList<>();

162for (String side : List.of("input", "output")) {

163 if (!(results.get(side) instanceof Map<?, ?> result)) {

164 throw new IllegalStateException("Missing " + side + " moderation result");

165 }

166 if ("error".equals(result.get("type"))) {

167 throw new IllegalStateException(String.valueOf(result.get("message")));

168 }

169 if (!"moderation_result".equals(result.get("type"))) {

170 throw new IllegalStateException("Unexpected " + side + " moderation result type");

171 }

172 if (!(result.get("flagged") instanceof Boolean flagged)) {

173 throw new IllegalStateException("Missing " + side + " moderation flag");

174 }

175 flags.add(flagged);

176}

177flags.forEach(System.out::println);

178```

179 

137```ruby180```ruby

138require "openai"181require "openai"

139 182 


227}270}

228```271```

229 272 

273```java

274import com.openai.client.OpenAIClient;

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

276import com.openai.models.moderations.ModerationCreateParams;

277 

278var moderation =

279 client

280 .moderations()

281 .create(

282 ModerationCreateParams.builder()

283 .model("omni-moderation-latest")

284 .input("Text to classify goes here.")

285 .build());

286 

287System.out.println(moderation.results().get(0).flagged());

288```

289 

230```ruby290```ruby

231require "openai"291require "openai"

232 292 


340}400}

341```401```

342 402 

403```java

404import com.openai.client.OpenAIClient;

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

406import com.openai.models.moderations.ModerationCreateParams;

407import com.openai.models.moderations.ModerationImageUrlInput;

408import com.openai.models.moderations.ModerationMultiModalInput;

409import com.openai.models.moderations.ModerationTextInput;

410import java.util.List;

411 

412var moderation =

413 client

414 .moderations()

415 .create(

416 ModerationCreateParams.builder()

417 .model("omni-moderation-latest")

418 .inputOfModerationMultiModalArray(

419 List.of(

420 ModerationMultiModalInput.ofText(

421 ModerationTextInput.builder()

422 .text("Text to classify goes here.")

423 .build()),

424 ModerationMultiModalInput.ofImageUrl(

425 ModerationImageUrlInput.builder()

426 .imageUrl(

427 ModerationImageUrlInput.ImageUrl.builder()

428 .url(

429 "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg")

430 .build())

431 .build())))

432 .build());

433 

434System.out.println(moderation.results().get(0).flagged());

435```

436 

343```ruby437```ruby

344require "openai"438require "openai"

345 439 

Details

149}149}

150```150```

151 151 

152```java

153import com.openai.client.OpenAIClient;

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

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

156import com.openai.models.chat.completions.ChatCompletionPredictionContent;

157 

158String code =

159 """

160 class User {

161 firstName: string = "";

162 lastName: string = "";

163 username: string = "";

164 }

165 

166 export default User;

167 """;

168String refactorPrompt =

169 "Replace the \"username\" property with an \"email\" property. "

170 + "Respond only with code, and with no markdown formatting.";

171 

172ChatCompletionCreateParams params =

173 ChatCompletionCreateParams.builder()

174 .model("gpt-4.1")

175 .addUserMessage(refactorPrompt)

176 .addUserMessage(code)

177 .prediction(ChatCompletionPredictionContent.builder().content(code).build())

178 .store(true)

179 .build();

180 

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

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

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

184```

185 

152```ruby186```ruby

153require "openai"187require "openai"

154 188 


369}403}

370```404```

371 405 

406```java

407import com.openai.client.OpenAIClient;

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

409import com.openai.core.http.StreamResponse;

410import com.openai.models.chat.completions.ChatCompletionChunk;

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

412import com.openai.models.chat.completions.ChatCompletionPredictionContent;

413 

414String code =

415 """

416 class User {

417 firstName: string = "";

418 lastName: string = "";

419 username: string = "";

420 }

421 

422 export default User;

423 """;

424String refactorPrompt =

425 "Replace the \"username\" property with an \"email\" property. "

426 + "Respond only with code, and with no markdown formatting.";

427 

428ChatCompletionCreateParams params =

429 ChatCompletionCreateParams.builder()

430 .model("gpt-4.1")

431 .addUserMessage(refactorPrompt)

432 .addUserMessage(code)

433 .prediction(ChatCompletionPredictionContent.builder().content(code).build())

434 .store(true)

435 .build();

436 

437try (StreamResponse<ChatCompletionChunk> stream =

438 client.chat().completions().createStreaming(params)) {

439 stream.stream()

440 .flatMap(chunk -> chunk.choices().stream())

441 .flatMap(choice -> choice.delta().content().stream())

442 .forEach(System.out::print);

443}

444```

445 

372```ruby446```ruby

373require "openai"447require "openai"

374 448 

Details

254}254}

255```255```

256 256 

257```java

258import com.openai.client.OpenAIClient;

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

260import com.openai.models.Reasoning;

261import com.openai.models.ReasoningEffort;

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

263 

264String semicolonsDevMsg = "Talk like a pirate.";

265 

266String semicolonsPrompt = "Are semicolons optional in JavaScript?";

267 

268ResponseCreateParams params =

269 ResponseCreateParams.builder()

270 .model("gpt-5.6")

271 .input(semicolonsPrompt)

272 .instructions(semicolonsDevMsg)

273 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

274 .build();

275 

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

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

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

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

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

281```

282 

257```ruby283```ruby

258require "openai"284require "openai"

259 285 


364}390}

365```391```

366 392 

393```java

394import com.openai.client.OpenAIClient;

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

396import com.openai.models.Reasoning;

397import com.openai.models.ReasoningEffort;

398import com.openai.models.responses.EasyInputMessage;

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

400import com.openai.models.responses.ResponseInputItem;

401import java.util.List;

402 

403String semicolonsDevMsg = "Talk like a pirate.";

404 

405String semicolonsPrompt = "Are semicolons optional in JavaScript?";

406 

407ResponseCreateParams params =

408 ResponseCreateParams.builder()

409 .model("gpt-5.6")

410 .input(

411 ResponseCreateParams.Input.ofResponse(

412 List.of(

413 ResponseInputItem.ofEasyInputMessage(

414 EasyInputMessage.builder()

415 .role(EasyInputMessage.Role.DEVELOPER)

416 .content(semicolonsDevMsg)

417 .build()),

418 ResponseInputItem.ofEasyInputMessage(

419 EasyInputMessage.builder()

420 .role(EasyInputMessage.Role.USER)

421 .content(semicolonsPrompt)

422 .build()))))

423 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

424 .build();

425 

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

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

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

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

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

431```

432 

367```ruby433```ruby

368require "openai"434require "openai"

369 435 


565}631}

566```632```

567 633 

634```java

635import com.openai.client.OpenAIClient;

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

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

638 

639ResponseCreateParams params =

640 ResponseCreateParams.builder()

641 .model("gpt-5.6")

642 .instructions(

643 "You are a coding assistant. Answer with concise JavaScript examples and use semicolons.")

644 .input("How would I declare a variable for a last name?")

645 .build();

646 

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

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

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

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

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

652```

653 

568```ruby654```ruby

569require "openai"655require "openai"

570 656 

Details

97 return completion.choices[0].message.content97 return completion.choices[0].message.content

98````98````

99 99 

100````java

101import com.openai.client.OpenAIClient;

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

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

104 

105String metaPrompt =

106 """

107 Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.

108 

109 # Guidelines

110 

111 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

112 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.

113 - Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!

114 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.

115 - Conclusion, classifications, or results should ALWAYS appear last.

116 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

117 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

118 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

119 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.

120 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.

121 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

122 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)

123 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.

124 - JSON should never be wrapped in code blocks (```) unless explicitly requested.

125 

126 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

127 

128 [Concise instruction describing the task - this should be the first line in the prompt, no section header]

129 

130 [Additional details as needed.]

131 

132 [Optional sections with headings or bullet points for detailed steps.]

133 

134 # Steps [optional]

135 

136 [optional: a detailed breakdown of the steps necessary to accomplish the task]

137 

138 # Output Format

139 

140 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]

141 

142 # Examples [optional]

143 

144 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]

145 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]

146 

147 # Notes [optional]

148 

149 [optional: edge cases, details, and an area to call or repeat out specific important considerations]

150 """

151 .strip();

152 

153ChatCompletionCreateParams params =

154 ChatCompletionCreateParams.builder()

155 .model("gpt-5.6")

156 .addSystemMessage(metaPrompt)

157 .addUserMessage(

158 "Task, Goal, or Current Prompt:\nWrite a concise product launch announcement.")

159 .build();

160 

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

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

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

164````

165 

100 166

101 167 

102 168


167 return completion.choices[0].message.content233 return completion.choices[0].message.content

168```234```

169 235 

236```java

237import com.openai.client.OpenAIClient;

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

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

240 

241String metaPrompt =

242 """

243 Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.

244 

245 # Guidelines

246 

247 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

248 - Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.

249 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.

250 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.

251 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

252 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

253 - It is very important that any examples included reflect the short, conversational output responses of the model.

254 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.

255 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.

256 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.

257 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

258 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.

259 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

260 

261 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

262 

263 [Concise instruction describing the task - this should be the first line in the prompt, no section header]

264 

265 [Additional details as needed.]

266 

267 [Optional sections with headings or bullet points for detailed steps.]

268 

269 # Examples [optional]

270 

271 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]

272 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]

273 

274 # Notes [optional]

275 

276 [optional: edge cases, details, and an area to call or repeat out specific important considerations]

277 """

278 .strip();

279 

280ChatCompletionCreateParams params =

281 ChatCompletionCreateParams.builder()

282 .model("gpt-5.6")

283 .addSystemMessage(metaPrompt)

284 .addUserMessage(

285 "Task, Goal, or Current Prompt:\n"

286 + "Create a friendly voice assistant for a bike shop.")

287 .build();

288 

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

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

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

292```

293 

170 294 

171 295 

172### Prompt edits296### Prompt edits


268 return completion.choices[0].message.content392 return completion.choices[0].message.content

269````393````

270 394 

395````java

396import com.openai.client.OpenAIClient;

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

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

399 

400String metaPrompt =

401 """

402 Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.

403 

404 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:

405 <reasoning>

406 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)

407 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?

408 - Identify: (max 10 words) if so, which section(s) utilize reasoning?

409 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?

410 - Ordering: (before/after) is the chain of though located before or after

411 - Structure: (yes/no) does the input prompt have a well defined structure

412 - Examples: (yes/no) does the input prompt have few-shot examples

413 - Representative: (1-5) if present, how representative are the examples?

414 - Complexity: (1-5) how complex is the input prompt?

415 - Task: (1-5) how complex is the implied task?

416 - Necessity: ()

417 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)

418 - Prioritization: (list) what 1-3 categories are the MOST important to address.

419 - Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed

420 </reasoning>

421 

422 # Guidelines

423 

424 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

425 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.

426 - Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!

427 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.

428 - Conclusion, classifications, or results should ALWAYS appear last.

429 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

430 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

431 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

432 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.

433 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.

434 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

435 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)

436 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.

437 - JSON should never be wrapped in code blocks (```) unless explicitly requested.

438 

439 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

440 

441 [Concise instruction describing the task - this should be the first line in the prompt, no section header]

442 

443 [Additional details as needed.]

444 

445 [Optional sections with headings or bullet points for detailed steps.]

446 

447 # Steps [optional]

448 

449 [optional: a detailed breakdown of the steps necessary to accomplish the task]

450 

451 # Output Format

452 

453 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]

454 

455 # Examples [optional]

456 

457 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]

458 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]

459 

460 # Notes [optional]

461 

462 [optional: edge cases, details, and an area to call or repeat out specific important considerations]

463 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]

464 """

465 .strip();

466 

467ChatCompletionCreateParams params =

468 ChatCompletionCreateParams.builder()

469 .model("gpt-5.6")

470 .addSystemMessage(metaPrompt)

471 .addUserMessage(

472 "Task, Goal, or Current Prompt:\nMake this product launch announcement clearer and more concise.")

473 .build();

474 

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

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

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

478````

479 

271 480

272 481 

273 482


357 return completion.choices[0].message.content566 return completion.choices[0].message.content

358```567```

359 568 

569```java

570import com.openai.client.OpenAIClient;

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

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

573 

574String metaPrompt =

575 """

576 Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.

577 

578 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:

579 <reasoning>

580 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)

581 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?

582 - Identify: (max 10 words) if so, which section(s) utilize reasoning?

583 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?

584 - Ordering: (before/after) is the chain of though located before or after

585 - Structure: (yes/no) does the input prompt have a well defined structure

586 - Examples: (yes/no) does the input prompt have few-shot examples

587 - Representative: (1-5) if present, how representative are the examples?

588 - Complexity: (1-5) how complex is the input prompt?

589 - Task: (1-5) how complex is the implied task?

590 - Necessity: ()

591 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)

592 - Prioritization: (list) what 1-3 categories are the MOST important to address.

593 - Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed

594 </reasoning>

595 

596 # Guidelines

597 

598 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

599 - Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.

600 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.

601 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.

602 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

603 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

604 - It is very important that any examples included reflect the short, conversational output responses of the model.

605 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.

606 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.

607 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.

608 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

609 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.

610 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

611 

612 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

613 

614 [Concise instruction describing the task - this should be the first line in the prompt, no section header]

615 

616 [Additional details as needed.]

617 

618 [Optional sections with headings or bullet points for detailed steps.]

619 

620 # Examples [optional]

621 

622 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]

623 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]

624 

625 # Notes [optional]

626 

627 [optional: edge cases, details, and an area to call or repeat out specific important considerations]

628 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]

629 """

630 .strip();

631 

632ChatCompletionCreateParams params =

633 ChatCompletionCreateParams.builder()

634 .model("gpt-5.6")

635 .addSystemMessage(metaPrompt)

636 .addUserMessage(

637 "Task, Goal, or Current Prompt:\nMake this voice assistant prompt warmer and more direct.")

638 .build();

639 

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

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

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

643```

644 

360 645 

361 646 

362## Schemas647## Schemas


676 return json.loads(completion.choices[0].message.content)961 return json.loads(completion.choices[0].message.content)

677```962```

678 963 

964```java

965import com.openai.client.OpenAIClient;

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

967import com.openai.core.JsonValue;

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

969import java.util.List;

970import java.util.Map;

971 

972String metaPrompt =

973 """

974 # Instructions

975 Return a valid schema for the described JSON.

976 

977 You must also make sure:

978 - all fields in an object are set as required

979 - I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED

980 - all objects must have additionalProperties set to false

981 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties

982 - all objects must have properties defined

983 - field order matters. any form of "thinking" or "explanation" should come before the conclusion

984 - $defs must be defined under the schema param

985 

986 Notable keywords NOT supported include:

987 - For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties

988 - For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems

989 

990 Other notes:

991 - definitions and recursion are supported

992 - only if necessary to include references e.g. "$defs", it must be inside the "schema" object

993 

994 # Examples

995 Input: Generate a math reasoning schema with steps and a final answer.

996 Output: {

997 "name": "math_reasoning",

998 "type": "object",

999 "properties": {

1000 "steps": {

1001 "type": "array",

1002 "description": "A sequence of steps involved in solving the math problem.",

1003 "items": {

1004 "type": "object",

1005 "properties": {

1006 "explanation": {

1007 "type": "string",

1008 "description": "Description of the reasoning or method used in this step."

1009 },

1010 "output": {

1011 "type": "string",

1012 "description": "Result or outcome of this specific step."

1013 }

1014 },

1015 "required": [

1016 "explanation",

1017 "output"

1018 ],

1019 "additionalProperties": false

1020 }

1021 },

1022 "final_answer": {

1023 "type": "string",

1024 "description": "The final solution or answer to the math problem."

1025 }

1026 },

1027 "required": [

1028 "steps",

1029 "final_answer"

1030 ],

1031 "additionalProperties": false

1032 }

1033 

1034 Input: Give me a linked list

1035 Output: {

1036 "name": "linked_list",

1037 "type": "object",

1038 "properties": {

1039 "linked_list": {

1040 "$ref": "#/$defs/linked_list_node",

1041 "description": "The head node of the linked list."

1042 }

1043 },

1044 "$defs": {

1045 "linked_list_node": {

1046 "type": "object",

1047 "description": "Defines a node in a singly linked list.",

1048 "properties": {

1049 "value": {

1050 "type": "number",

1051 "description": "The value stored in this node."

1052 },

1053 "next": {

1054 "anyOf": [

1055 {

1056 "$ref": "#/$defs/linked_list_node"

1057 },

1058 {

1059 "type": "null"

1060 }

1061 ],

1062 "description": "Reference to the next node; null if it is the last node."

1063 }

1064 },

1065 "required": [

1066 "value",

1067 "next"

1068 ],

1069 "additionalProperties": false

1070 }

1071 },

1072 "required": [

1073 "linked_list"

1074 ],

1075 "additionalProperties": false

1076 }

1077 

1078 Input: Dynamically generated UI

1079 Output: {

1080 "name": "ui",

1081 "type": "object",

1082 "properties": {

1083 "type": {

1084 "type": "string",

1085 "description": "The type of the UI component",

1086 "enum": [

1087 "div",

1088 "button",

1089 "header",

1090 "section",

1091 "field",

1092 "form"

1093 ]

1094 },

1095 "label": {

1096 "type": "string",

1097 "description": "The label of the UI component, used for buttons or form fields"

1098 },

1099 "children": {

1100 "type": "array",

1101 "description": "Nested UI components",

1102 "items": {

1103 "$ref": "#"

1104 }

1105 },

1106 "attributes": {

1107 "type": "array",

1108 "description": "Arbitrary attributes for the UI component, suitable for any element",

1109 "items": {

1110 "type": "object",

1111 "properties": {

1112 "name": {

1113 "type": "string",

1114 "description": "The name of the attribute, for example onClick or className"

1115 },

1116 "value": {

1117 "type": "string",

1118 "description": "The value of the attribute"

1119 }

1120 },

1121 "required": [

1122 "name",

1123 "value"

1124 ],

1125 "additionalProperties": false

1126 }

1127 }

1128 },

1129 "required": [

1130 "type",

1131 "label",

1132 "children",

1133 "attributes"

1134 ],

1135 "additionalProperties": false

1136 }

1137 """

1138 .strip();

1139Map<String, Object> metaSchema =

1140 Map.ofEntries(

1141 Map.entry("name", "metaschema"),

1142 Map.entry(

1143 "schema",

1144 Map.ofEntries(

1145 Map.entry("type", "object"),

1146 Map.entry(

1147 "properties",

1148 Map.ofEntries(

1149 Map.entry(

1150 "name",

1151 Map.ofEntries(

1152 Map.entry("type", "string"),

1153 Map.entry("description", "The name of the schema"))),

1154 Map.entry(

1155 "type",

1156 Map.ofEntries(

1157 Map.entry("type", "string"),

1158 Map.entry(

1159 "enum",

1160 List.of(

1161 "object", "array", "string", "number", "boolean",

1162 "null")))),

1163 Map.entry(

1164 "properties",

1165 Map.ofEntries(

1166 Map.entry("type", "object"),

1167 Map.entry(

1168 "additionalProperties",

1169 Map.ofEntries(

1170 Map.entry("$ref", "#/$defs/schema_definition"))))),

1171 Map.entry(

1172 "items",

1173 Map.ofEntries(

1174 Map.entry(

1175 "anyOf",

1176 List.of(

1177 Map.ofEntries(

1178 Map.entry("$ref", "#/$defs/schema_definition")),

1179 Map.ofEntries(

1180 Map.entry("type", "array"),

1181 Map.entry(

1182 "items",

1183 Map.ofEntries(

1184 Map.entry(

1185 "$ref",

1186 "#/$defs/schema_definition")))))))),

1187 Map.entry(

1188 "required",

1189 Map.ofEntries(

1190 Map.entry("type", "array"),

1191 Map.entry(

1192 "items", Map.ofEntries(Map.entry("type", "string"))))),

1193 Map.entry(

1194 "additionalProperties",

1195 Map.ofEntries(Map.entry("type", "boolean"))))),

1196 Map.entry("required", List.of("type")),

1197 Map.entry("additionalProperties", false),

1198 Map.entry(

1199 "if",

1200 Map.ofEntries(

1201 Map.entry(

1202 "properties",

1203 Map.ofEntries(

1204 Map.entry(

1205 "type", Map.ofEntries(Map.entry("const", "object"))))))),

1206 Map.entry("then", Map.ofEntries(Map.entry("required", List.of("properties")))),

1207 Map.entry(

1208 "$defs",

1209 Map.ofEntries(

1210 Map.entry(

1211 "schema_definition",

1212 Map.ofEntries(

1213 Map.entry("type", "object"),

1214 Map.entry(

1215 "properties",

1216 Map.ofEntries(

1217 Map.entry(

1218 "type",

1219 Map.ofEntries(

1220 Map.entry("type", "string"),

1221 Map.entry(

1222 "enum",

1223 List.of(

1224 "object", "array", "string", "number",

1225 "boolean", "null")))),

1226 Map.entry(

1227 "properties",

1228 Map.ofEntries(

1229 Map.entry("type", "object"),

1230 Map.entry(

1231 "additionalProperties",

1232 Map.ofEntries(

1233 Map.entry(

1234 "$ref",

1235 "#/$defs/schema_definition"))))),

1236 Map.entry(

1237 "items",

1238 Map.ofEntries(

1239 Map.entry(

1240 "anyOf",

1241 List.of(

1242 Map.ofEntries(

1243 Map.entry(

1244 "$ref",

1245 "#/$defs/schema_definition")),

1246 Map.ofEntries(

1247 Map.entry("type", "array"),

1248 Map.entry(

1249 "items",

1250 Map.ofEntries(

1251 Map.entry(

1252 "$ref",

1253 "#/$defs/schema_definition")))))))),

1254 Map.entry(

1255 "required",

1256 Map.ofEntries(

1257 Map.entry("type", "array"),

1258 Map.entry(

1259 "items",

1260 Map.ofEntries(

1261 Map.entry("type", "string"))))),

1262 Map.entry(

1263 "additionalProperties",

1264 Map.ofEntries(Map.entry("type", "boolean"))))),

1265 Map.entry("required", List.of("type")),

1266 Map.entry("additionalProperties", false),

1267 Map.entry(

1268 "if",

1269 Map.ofEntries(

1270 Map.entry(

1271 "properties",

1272 Map.ofEntries(

1273 Map.entry(

1274 "type",

1275 Map.ofEntries(

1276 Map.entry("const", "object"))))))),

1277 Map.entry(

1278 "then",

1279 Map.ofEntries(

1280 Map.entry("required", List.of("properties")))))))))));

1281 

1282ChatCompletionCreateParams params =

1283 ChatCompletionCreateParams.builder()

1284 .model("gpt-5.6-terra")

1285 .addSystemMessage(metaPrompt)

1286 .addUserMessage("Description:\nDescribe a calendar event.")

1287 .putAdditionalBodyProperty(

1288 "response_format",

1289 JsonValue.from(Map.of("type", "json_schema", "json_schema", metaSchema)))

1290 .build();

1291 

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

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

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

1295```

1296 

679 1297

680 1298 

681 1299


894 1512 

895 return json.loads(completion.choices[0].message.content)1513 return json.loads(completion.choices[0].message.content)

896```1514```

1515 

1516```java

1517import com.openai.client.OpenAIClient;

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

1519import com.openai.core.JsonValue;

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

1521import java.util.List;

1522import java.util.Map;

1523 

1524String metaPrompt =

1525 """

1526 # Instructions

1527 Return a valid schema for the described function.

1528 

1529 Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.

1530 Make sure that every property, no matter how short, has a type and description correctly nested inside it.

1531 

1532 # Examples

1533 Input: Assign values to NN hyperparameters

1534 Output: {

1535 "name": "set_hyperparameters",

1536 "description": "Assign values to NN hyperparameters",

1537 "parameters": {

1538 "type": "object",

1539 "required": [

1540 "learning_rate",

1541 "epochs"

1542 ],

1543 "properties": {

1544 "epochs": {

1545 "type": "number",

1546 "description": "Number of complete passes through dataset"

1547 },

1548 "learning_rate": {

1549 "type": "number",

1550 "description": "Speed of model learning"

1551 }

1552 }

1553 }

1554 }

1555 

1556 Input: Plans a motion path for the robot

1557 Output: {

1558 "name": "plan_motion",

1559 "description": "Plans a motion path for the robot",

1560 "parameters": {

1561 "type": "object",

1562 "required": [

1563 "start_position",

1564 "end_position"

1565 ],

1566 "properties": {

1567 "end_position": {

1568 "type": "object",

1569 "properties": {

1570 "x": {

1571 "type": "number",

1572 "description": "End X coordinate"

1573 },

1574 "y": {

1575 "type": "number",

1576 "description": "End Y coordinate"

1577 }

1578 }

1579 },

1580 "obstacles": {

1581 "type": "array",

1582 "description": "Array of obstacle coordinates",

1583 "items": {

1584 "type": "object",

1585 "properties": {

1586 "x": {

1587 "type": "number",

1588 "description": "Obstacle X coordinate"

1589 },

1590 "y": {

1591 "type": "number",

1592 "description": "Obstacle Y coordinate"

1593 }

1594 }

1595 }

1596 },

1597 "start_position": {

1598 "type": "object",

1599 "properties": {

1600 "x": {

1601 "type": "number",

1602 "description": "Start X coordinate"

1603 },

1604 "y": {

1605 "type": "number",

1606 "description": "Start Y coordinate"

1607 }

1608 }

1609 }

1610 }

1611 }

1612 }

1613 

1614 Input: Calculates various technical indicators

1615 Output: {

1616 "name": "technical_indicator",

1617 "description": "Calculates various technical indicators",

1618 "parameters": {

1619 "type": "object",

1620 "required": [

1621 "ticker",

1622 "indicators"

1623 ],

1624 "properties": {

1625 "indicators": {

1626 "type": "array",

1627 "description": "List of technical indicators to calculate",

1628 "items": {

1629 "type": "string",

1630 "description": "Technical indicator",

1631 "enum": [

1632 "RSI",

1633 "MACD",

1634 "Bollinger_Bands",

1635 "Stochastic_Oscillator"

1636 ]

1637 }

1638 },

1639 "period": {

1640 "type": "number",

1641 "description": "Time period for the analysis"

1642 },

1643 "ticker": {

1644 "type": "string",

1645 "description": "Stock ticker symbol"

1646 }

1647 }

1648 }

1649 }

1650 """

1651 .strip();

1652Map<String, Object> schemaDefinition =

1653 Map.of(

1654 "type", "object",

1655 "properties",

1656 Map.of(

1657 "type",

1658 Map.of(

1659 "type",

1660 "string",

1661 "enum",

1662 List.of("object", "array", "string", "number", "boolean", "null")),

1663 "properties",

1664 Map.of(

1665 "type",

1666 "object",

1667 "additionalProperties",

1668 Map.of("$ref", "#/$defs/schema_definition")),

1669 "items",

1670 Map.of(

1671 "anyOf",

1672 List.of(

1673 Map.of("$ref", "#/$defs/schema_definition"),

1674 Map.of(

1675 "type",

1676 "array",

1677 "items",

1678 Map.of("$ref", "#/$defs/schema_definition")))),

1679 "required", Map.of("type", "array", "items", Map.of("type", "string")),

1680 "additionalProperties", Map.of("type", "boolean")),

1681 "required", List.of("type"),

1682 "additionalProperties", false,

1683 "if", Map.of("properties", Map.of("type", Map.of("const", "object"))),

1684 "then", Map.of("required", List.of("properties")));

1685Map<String, Object> functionSchema =

1686 Map.of(

1687 "type", "object",

1688 "properties",

1689 Map.of(

1690 "name", Map.of("type", "string", "description", "The name of the function"),

1691 "description",

1692 Map.of(

1693 "type",

1694 "string",

1695 "description",

1696 "A description of what the function does"),

1697 "parameters",

1698 Map.of(

1699 "$ref",

1700 "#/$defs/schema_definition",

1701 "description",

1702 "A JSON schema that defines the function's parameters")),

1703 "required", List.of("name", "description", "parameters"),

1704 "additionalProperties", false,

1705 "$defs", Map.of("schema_definition", schemaDefinition));

1706 

1707ChatCompletionCreateParams params =

1708 ChatCompletionCreateParams.builder()

1709 .model("gpt-5.6-terra")

1710 .addSystemMessage(metaPrompt)

1711 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")

1712 .putAdditionalBodyProperty(

1713 "response_format",

1714 JsonValue.from(

1715 Map.of(

1716 "type",

1717 "json_schema",

1718 "json_schema",

1719 Map.of("name", "function-metaschema", "schema", functionSchema))))

1720 .build();

1721 

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

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

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

1725```

Details

81}81}

82```82```

83 83 

84```java

85import com.openai.client.OpenAIClient;

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

87import com.openai.core.JsonValue;

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

89import com.openai.models.responses.ResponsePrompt;

90 

91String promptId = "pmpt_123";

92 

93ResponseCreateParams params =

94 ResponseCreateParams.builder()

95 .prompt(

96 ResponsePrompt.builder()

97 .id(promptId)

98 .version("1")

99 .variables(

100 ResponsePrompt.Variables.builder()

101 .putAdditionalProperty("customer_name", JsonValue.from("Acme"))

102 .putAdditionalProperty("issue", JsonValue.from("billing question"))

103 .build())

104 .build())

105 .build();

106 

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

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

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

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

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

112```

113 

84```ruby114```ruby

85require "openai"115require "openai"

86 116 


194}224}

195```225```

196 226 

227```java

228import com.openai.client.OpenAIClient;

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

230import com.openai.models.responses.EasyInputMessage;

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

232import com.openai.models.responses.ResponseInputItem;

233import java.util.List;

234 

235ResponseCreateParams params =

236 ResponseCreateParams.builder()

237 .model("gpt-5.6")

238 .inputOfResponse(

239 List.of(

240 ResponseInputItem.ofEasyInputMessage(

241 EasyInputMessage.builder()

242 .role(EasyInputMessage.Role.SYSTEM)

243 .content(

244 "You are a helpful support assistant. Be concise, accurate, and friendly.")

245 .build()),

246 ResponseInputItem.ofEasyInputMessage(

247 EasyInputMessage.builder()

248 .role(EasyInputMessage.Role.USER)

249 .content(

250 "Customer name: Acme. Issue: billing question. Write a response to the customer.")

251 .build())))

252 .build();

253 

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

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

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

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

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

259```

260 

197```ruby261```ruby

198require "openai"262require "openai"

199 263 


346}410}

347```411```

348 412 

413```java

414import com.openai.client.OpenAIClient;

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

416import com.openai.models.responses.EasyInputMessage;

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

418import com.openai.models.responses.ResponseInputItem;

419import java.util.List;

420 

421private static List<ResponseInputItem> buildSupportPrompt(String customerName, String issue) {

422 return List.of(

423 ResponseInputItem.ofEasyInputMessage(

424 EasyInputMessage.builder()

425 .role(EasyInputMessage.Role.SYSTEM)

426 .content(

427 "You are a helpful support assistant. Be concise, accurate, and friendly. Do not invent policy details.")

428 .build()),

429 ResponseInputItem.ofEasyInputMessage(

430 EasyInputMessage.builder()

431 .role(EasyInputMessage.Role.USER)

432 .content(

433 "Customer name: "

434 + customerName

435 + ". Issue: "

436 + issue

437 + ". Write a response to the customer.")

438 .build()));

439}

440 

441ResponseCreateParams params =

442 ResponseCreateParams.builder()

443 .model("gpt-5.6")

444 .inputOfResponse(buildSupportPrompt("Acme", "billing question"))

445 .build();

446 

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

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

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

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

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

452```

453 

349```ruby454```ruby

350require "openai"455require "openai"

351 456 

Details

235```235```

236 236 

237 237 

238While the model response is being generated, the server will emit a number of lifecycle events during the process. You can listen for these events, such as [`response.output_text.delta`](https://developers.openai.com/api/reference/resources/realtime), to provide realtime feedback to users as the response is generated. A full listing of the events emitted by there server are found below under **related server events**. They are provided in the rough order of when they are emitted, along with relevant client-side events for text generation.238While the model response is being generated, the server will emit a number of lifecycle events during the process. You can listen for these events, such as [`response.output_text.delta`](https://developers.openai.com/api/reference/resources/realtime), to provide realtime feedback to users as the response is generated. A full listing of the events emitted by the server is found below under **related server events**. They are provided in the rough order of when they are emitted, along with relevant client-side events for text generation.

239 239 

240<table>240<table>

241 <tr>241 <tr>


295 295 

296### Handling audio with WebRTC296### Handling audio with WebRTC

297 297 

298If you are connecting to the Realtime API using WebRTC, the Realtime API is acting as a [peer connection](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection) to your client. Audio output from the model is delivered to your client as a [remote media stream](hhttps://developer.mozilla.org/en-US/docs/Web/API/MediaStream). Audio input to the model is collected using audio devices ([`getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)), and media streams are added as tracks to to the peer connection.298If you are connecting to the Realtime API using WebRTC, the Realtime API is acting as a [peer connection](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection) to your client. Audio output from the model is delivered to your client as a [remote media stream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream). Audio input to the model is collected using audio devices ([`getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)), and media streams are added as tracks to the peer connection.

299 299 

300The example code from the [WebRTC connection guide](https://developers.openai.com/api/docs/guides/realtime-webrtc) shows a basic example of configuring both local and remote audio using browser APIs:300The example code from the [WebRTC connection guide](https://developers.openai.com/api/docs/guides/realtime-webrtc) shows a basic example of configuring both local and remote audio using browser APIs:

301 301 

Details

93}93}

94```94```

95 95 

96```java

97import com.openai.client.OpenAIClient;

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

99import com.openai.models.Reasoning;

100import com.openai.models.ReasoningEffort;

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

102 

103String prompt =

104 """

105 Write a bash script that takes a matrix represented as a string with format

106 '[1,2],[3,4],[5,6]' and prints the transpose in the same format.

107 """

108 .strip();

109 

110ResponseCreateParams params =

111 ResponseCreateParams.builder()

112 .model("gpt-5.6")

113 .input(prompt)

114 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

115 .build();

116 

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

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

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

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

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

122```

123 

96```ruby124```ruby

97require "openai"125require "openai"

98 126 


326}354}

327```355```

328 356 

357```java

358import com.openai.client.OpenAIClient;

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

360import com.openai.models.Reasoning;

361import com.openai.models.ReasoningEffort;

362import com.openai.models.responses.Response;

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

364import com.openai.models.responses.ResponseStatus;

365 

366ResponseCreateParams params =

367 ResponseCreateParams.builder()

368 .model("gpt-5.6")

369 .input(

370 "Write a bash script that takes a matrix represented as a string with format "

371 + "'[1,2],[3,4],[5,6]' and prints the transpose in the same format.")

372 .maxOutputTokens(300)

373 .reasoning(Reasoning.builder().effort(ReasoningEffort.MEDIUM).build())

374 .build();

375 

376var response = client.responses().create(params);

377if (response.status().filter(ResponseStatus.INCOMPLETE::equals).isPresent()

378 && response

379 .incompleteDetails()

380 .flatMap(Response.IncompleteDetails::reason)

381 .filter(Response.IncompleteDetails.Reason.MAX_OUTPUT_TOKENS::equals)

382 .isPresent()) {

383 System.out.println("Ran out of tokens");

384 response.output().stream()

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

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

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

388 .forEach(text -> System.out.println("Partial output: " + text.text()));

389}

390```

391 

329```ruby392```ruby

330require "openai"393require "openai"

331 394 


475}538}

476```539```

477 540 

541```java

542import com.openai.client.OpenAIClient;

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

544import com.openai.core.JsonValue;

545import com.openai.models.Reasoning;

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

547 

548var first =

549 client

550 .responses()

551 .create(

552 ResponseCreateParams.builder()

553 .model("gpt-5.6")

554 .input("Inspect this repository and identify the likely bug.")

555 .reasoning(

556 Reasoning.builder()

557 .putAdditionalProperty("context", JsonValue.from("current_turn"))

558 .build())

559 .build());

560 

561var second =

562 client

563 .responses()

564 .create(

565 ResponseCreateParams.builder()

566 .model("gpt-5.6")

567 .input("Now patch the bug and explain the change.")

568 .previousResponseId(first.id())

569 .reasoning(

570 Reasoning.builder()

571 .putAdditionalProperty("context", JsonValue.from("all_turns"))

572 .build())

573 .build());

574second.output().stream()

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

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

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

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

579```

580 

478```ruby581```ruby

479require "openai"582require "openai"

480 583 


658}761}

659```762```

660 763 

764```java

765import com.openai.client.OpenAIClient;

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

767import com.openai.core.JsonValue;

768import com.openai.models.Reasoning;

769import com.openai.models.responses.EasyInputMessage;

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

771import com.openai.models.responses.ResponseInputItem;

772import java.util.ArrayList;

773 

774var history = new ArrayList<ResponseInputItem>();

775history.add(

776 ResponseInputItem.ofEasyInputMessage(

777 EasyInputMessage.builder()

778 .role(EasyInputMessage.Role.USER)

779 .content("Inspect this repository and identify the likely bug.")

780 .build()));

781 

782var first =

783 client

784 .responses()

785 .create(

786 ResponseCreateParams.builder()

787 .model("gpt-5.6")

788 .inputOfResponse(history)

789 .store(false)

790 .reasoning(

791 Reasoning.builder()

792 .putAdditionalProperty("context", JsonValue.from("current_turn"))

793 .build())

794 .build());

795first.output().stream()

796 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))

797 .forEach(history::add);

798history.add(

799 ResponseInputItem.ofEasyInputMessage(

800 EasyInputMessage.builder()

801 .role(EasyInputMessage.Role.USER)

802 .content("Now patch the bug and explain the change.")

803 .build()));

804 

805client

806 .responses()

807 .create(

808 ResponseCreateParams.builder()

809 .model("gpt-5.6")

810 .inputOfResponse(history)

811 .store(false)

812 .reasoning(

813 Reasoning.builder()

814 .putAdditionalProperty("context", JsonValue.from("all_turns"))

815 .build())

816 .build())

817 .output()

818 .stream()

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

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

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

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

823```

824 

661```ruby825```ruby

662require "openai"826require "openai"

663 827 


760}924}

761```925```

762 926 

927```java

928import com.openai.client.OpenAIClient;

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

930import com.openai.models.Reasoning;

931import com.openai.models.ReasoningEffort;

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

933 

934ResponseCreateParams params =

935 ResponseCreateParams.builder()

936 .model("gpt-5.6")

937 .input("What is the capital of France?")

938 .reasoning(

939 Reasoning.builder()

940 .effort(ReasoningEffort.LOW)

941 .summary(Reasoning.Summary.AUTO)

942 .build())

943 .build();

944 

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

946 .flatMap(item -> item.reasoning().stream())

947 .flatMap(reasoning -> reasoning.summary().stream())

948 .forEach(summary -> System.out.println(summary.text()));

949```

950 

763```ruby951```ruby

764require "openai"952require "openai"

765 953 


931}1119}

932```1120```

933 1121 

1122```java

1123import com.openai.client.OpenAIClient;

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

1125import com.openai.models.responses.EasyInputMessage;

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

1127import com.openai.models.responses.ResponseInputItem;

1128import java.util.List;

1129 

1130ResponseCreateParams params =

1131 ResponseCreateParams.builder()

1132 .model("gpt-5.6")

1133 .inputOfResponse(

1134 List.of(

1135 ResponseInputItem.ofEasyInputMessage(

1136 EasyInputMessage.builder()

1137 .role(EasyInputMessage.Role.ASSISTANT)

1138 .phase(EasyInputMessage.Phase.COMMENTARY)

1139 .content(

1140 "I'll inspect the logs and then summarize root cause and remediation.")

1141 .build()),

1142 ResponseInputItem.ofEasyInputMessage(

1143 EasyInputMessage.builder()

1144 .role(EasyInputMessage.Role.ASSISTANT)

1145 .phase(EasyInputMessage.Phase.FINAL_ANSWER)

1146 .content("Root cause: cache invalidation race.")

1147 .build()),

1148 ResponseInputItem.ofEasyInputMessage(

1149 EasyInputMessage.builder()

1150 .role(EasyInputMessage.Role.USER)

1151 .content("Great—now give me a rollout-safe fix plan.")

1152 .build())))

1153 .build();

1154 

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

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

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

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

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

1160```

1161 

934```ruby1162```ruby

935require "openai"1163require "openai"

936 1164 


1115}1343}

1116```1344```

1117 1345 

1346```java

1347import com.openai.client.OpenAIClient;

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

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

1350 

1351String prompt =

1352 """

1353 Instructions:

1354 - Given the React component below, change it so that nonfiction books have red text.

1355 - Return only the code in your reply.

1356 - Do not include any additional formatting, such as markdown code blocks.

1357 

1358 const books = [

1359 { title: 'Dune', category: 'fiction', id: 1 },

1360 { title: 'Frankenstein', category: 'fiction', id: 2 },

1361 { title: 'Moneyball', category: 'nonfiction', id: 3 },

1362 ];

1363 """

1364 .strip();

1365 

1366ResponseCreateParams params =

1367 ResponseCreateParams.builder().model("gpt-5.6").input(prompt).build();

1368 

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

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

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

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

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

1374```

1375 

1118```ruby1376```ruby

1119require "openai"1377require "openai"

1120 1378 


1246}1504}

1247```1505```

1248 1506 

1507```java

1508import com.openai.client.OpenAIClient;

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

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

1511 

1512String prompt =

1513 """

1514 I want to build a Python app that looks up user questions in a database where

1515 they are mapped to answers. If there is a close match, it retrieves the answer.

1516 Otherwise, it asks the user for an answer and stores the question and answer.

1517 Plan the directory structure, then return each file in full.

1518 """

1519 .strip();

1520 

1521ResponseCreateParams params =

1522 ResponseCreateParams.builder().model("gpt-5.6").input(prompt).build();

1523 

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

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

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

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

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

1529```

1530 

1249```ruby1531```ruby

1250require "openai"1532require "openai"

1251 1533 


1354}1636}

1355```1637```

1356 1638 

1639```java

1640import com.openai.client.OpenAIClient;

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

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

1643 

1644String prompt =

1645 """

1646 What are three compounds we should consider investigating to advance research

1647 into new antibiotics? Why should we consider them?

1648 """

1649 .strip();

1650 

1651ResponseCreateParams params =

1652 ResponseCreateParams.builder().model("gpt-5.6").input(prompt).build();

1653 

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

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

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

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

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

1659```

1660 

1357```ruby1661```ruby

1358require "openai"1662require "openai"

1359 1663 

Details

80}80}

81```81```

82 82 

83```java

84import com.openai.client.OpenAIClient;

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

86import com.openai.models.files.FileCreateParams;

87import com.openai.models.files.FilePurpose;

88import com.openai.models.vectorstores.VectorStoreCreateParams;

89import com.openai.models.vectorstores.files.FileRetrieveParams;

90import com.openai.models.vectorstores.files.VectorStoreFile;

91import java.nio.file.Path;

92 

93var store =

94 client.vectorStores().create(VectorStoreCreateParams.builder().name("Support FAQ").build());

95var uploaded =

96 client

97 .files()

98 .create(

99 FileCreateParams.builder()

100 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

101 .purpose(FilePurpose.ASSISTANTS)

102 .build());

103var file =

104 client

105 .vectorStores()

106 .files()

107 .create(

108 store.id(),

109 com.openai.models.vectorstores.files.FileCreateParams.builder()

110 .fileId(uploaded.id())

111 .build());

112while (file.status().equals(VectorStoreFile.Status.IN_PROGRESS)) {

113 Thread.sleep(1000);

114 file =

115 client

116 .vectorStores()

117 .files()

118 .retrieve(file.id(), FileRetrieveParams.builder().vectorStoreId(store.id()).build());

119}

120System.out.println(store.id());

121```

122 

83```ruby123```ruby

84require "openai"124require "openai"

85require "pathname"125require "pathname"


143}183}

144```184```

145 185 

186```java

187import com.openai.client.OpenAIClient;

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

189import com.openai.models.vectorstores.VectorStoreSearchParams;

190 

191String vectorStoreId = "vs_123";

192 

193var results =

194 client

195 .vectorStores()

196 .search(

197 vectorStoreId,

198 VectorStoreSearchParams.builder().query("What is the return policy?").build());

199 

200System.out.println(results.data());

201```

202 

146```ruby203```ruby

147require "openai"204require "openai"

148 205 


214}271}

215```272```

216 273 

274```java

275import com.openai.client.OpenAIClient;

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

277import com.openai.models.vectorstores.VectorStoreSearchParams;

278 

279String vectorStoreId = "vs_123";

280 

281var results =

282 client

283 .vectorStores()

284 .search(

285 vectorStoreId,

286 VectorStoreSearchParams.builder()

287 .query("How many woodchucks are allowed per passenger?")

288 .build());

289 

290System.out.println(results.data());

291```

292 

217```ruby293```ruby

218require "openai"294require "openai"

219 295 


513}589}

514```590```

515 591 

592```java

593import com.openai.client.OpenAIClient;

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

595import com.openai.models.vectorstores.VectorStoreCreateParams;

596 

597String fileId = "file_123";

598 

599var store =

600 client

601 .vectorStores()

602 .create(

603 VectorStoreCreateParams.builder().name("Support FAQ").addFileId(fileId).build());

604 

605System.out.println(store.id());

606```

607 

516```ruby608```ruby

517require "openai"609require "openai"

518 610 


563}655}

564```656```

565 657 

658```java

659import com.openai.client.OpenAIClient;

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

661 

662String vectorStoreId = "vs_123";

663 

664System.out.println(client.vectorStores().retrieve(vectorStoreId).id());

665```

666 

566```ruby667```ruby

567require "openai"668require "openai"

568 669 


615}716}

616```717```

617 718 

719```java

720import com.openai.client.OpenAIClient;

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

722import com.openai.models.vectorstores.VectorStoreUpdateParams;

723 

724String vectorStoreId = "vs_123";

725 

726var store =

727 client

728 .vectorStores()

729 .update(

730 vectorStoreId,

731 VectorStoreUpdateParams.builder().name("Updated knowledge base").build());

732 

733System.out.println(store.name());

734```

735 

618```ruby736```ruby

619require "openai"737require "openai"

620 738 


662}780}

663```781```

664 782 

783```java

784import com.openai.client.OpenAIClient;

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

786 

787String vectorStoreId = "vs_123";

788 

789System.out.println(client.vectorStores().delete(vectorStoreId).deleted());

790```

791 

665```ruby792```ruby

666require "openai"793require "openai"

667 794 


707}834}

708```835```

709 836 

837```java

838import com.openai.client.OpenAIClient;

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

840 

841System.out.println(client.vectorStores().list().data());

842```

843 

710```ruby844```ruby

711require "openai"845require "openai"

712 846 


764}898}

765```899```

766 900 

901```java

902import com.openai.client.OpenAIClient;

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

904import com.openai.models.vectorstores.files.FileCreateParams;

905 

906String vectorStoreId = "vs_123";

907 

908String fileId = "file_123";

909 

910var file =

911 client

912 .vectorStores()

913 .files()

914 .create(vectorStoreId, FileCreateParams.builder().fileId(fileId).build());

915 

916System.out.println(file.id());

917```

918 

767```ruby919```ruby

768require "openai"920require "openai"

769 921 


824}976}

825```977```

826 978 

979```java

980import com.openai.client.OpenAIClient;

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

982import com.openai.models.files.FileCreateParams;

983import com.openai.models.files.FilePurpose;

984import com.openai.models.vectorstores.files.FileRetrieveParams;

985import com.openai.models.vectorstores.files.VectorStoreFile;

986import java.nio.file.Path;

987 

988String vectorStoreId = "vs_123";

989var uploaded =

990 client

991 .files()

992 .create(

993 FileCreateParams.builder()

994 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

995 .purpose(FilePurpose.ASSISTANTS)

996 .build());

997var file =

998 client

999 .vectorStores()

1000 .files()

1001 .create(

1002 vectorStoreId,

1003 com.openai.models.vectorstores.files.FileCreateParams.builder()

1004 .fileId(uploaded.id())

1005 .build());

1006while (file.status().equals(VectorStoreFile.Status.IN_PROGRESS)) {

1007 Thread.sleep(1000);

1008 file =

1009 client

1010 .vectorStores()

1011 .files()

1012 .retrieve(

1013 file.id(), FileRetrieveParams.builder().vectorStoreId(vectorStoreId).build());

1014}

1015System.out.println(file.id());

1016```

1017 

827```ruby1018```ruby

828require "openai"1019require "openai"

829require "pathname"1020require "pathname"


887}1078}

888```1079```

889 1080 

1081```java

1082import com.openai.client.OpenAIClient;

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

1084 

1085String fileId = "file_123";

1086 

1087String vectorStoreId = "vs_123";

1088 

1089System.out.println(

1090 client

1091 .vectorStores()

1092 .files()

1093 .retrieve(

1094 fileId,

1095 com.openai.models.vectorstores.files.FileRetrieveParams.builder()

1096 .vectorStoreId(vectorStoreId)

1097 .build())

1098 .id());

1099```

1100 

890```ruby1101```ruby

891require "openai"1102require "openai"

892 1103 


943}1154}

944```1155```

945 1156 

1157```java

1158import com.openai.client.OpenAIClient;

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

1160import com.openai.core.JsonValue;

1161import com.openai.models.vectorstores.files.FileUpdateParams;

1162 

1163String fileId = "file_123";

1164 

1165String vectorStoreId = "vs_123";

1166 

1167var file =

1168 client

1169 .vectorStores()

1170 .files()

1171 .update(

1172 fileId,

1173 FileUpdateParams.builder()

1174 .vectorStoreId(vectorStoreId)

1175 .attributes(

1176 FileUpdateParams.Attributes.builder()

1177 .putAdditionalProperty("category", JsonValue.from("policy"))

1178 .build())

1179 .build());

1180 

1181System.out.println(file.id());

1182```

1183 

946```ruby1184```ruby

947require "openai"1185require "openai"

948 1186 


993}1231}

994```1232```

995 1233 

1234```java

1235import com.openai.client.OpenAIClient;

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

1237 

1238String fileId = "file_123";

1239 

1240String vectorStoreId = "vs_123";

1241 

1242System.out.println(

1243 client

1244 .vectorStores()

1245 .files()

1246 .delete(

1247 fileId,

1248 com.openai.models.vectorstores.files.FileDeleteParams.builder()

1249 .vectorStoreId(vectorStoreId)

1250 .build())

1251 .deleted());

1252```

1253 

996```ruby1254```ruby

997require "openai"1255require "openai"

998 1256 


1040}1298}

1041```1299```

1042 1300 

1301```java

1302import com.openai.client.OpenAIClient;

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

1304 

1305String vectorStoreId = "vs_123";

1306 

1307System.out.println(client.vectorStores().files().list(vectorStoreId).data());

1308```

1309 

1043```ruby1310```ruby

1044require "openai"1311require "openai"

1045 1312 


1134}1401}

1135```1402```

1136 1403 

1404```java

1405import com.openai.client.OpenAIClient;

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

1407import com.openai.core.JsonValue;

1408import com.openai.models.vectorstores.StaticFileChunkingStrategy;

1409import com.openai.models.vectorstores.filebatches.FileBatchCreateParams;

1410import com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams;

1411import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;

1412 

1413String vectorStoreId = "vs_123";

1414String fileId = "file_123";

1415String fileId2 = "file_456";

1416var first =

1417 FileBatchCreateParams.File.builder()

1418 .fileId(fileId)

1419 .attributes(

1420 FileBatchCreateParams.File.Attributes.builder()

1421 .putAdditionalProperty("department", JsonValue.from("finance"))

1422 .build())

1423 .build();

1424var second =

1425 FileBatchCreateParams.File.builder()

1426 .fileId(fileId2)

1427 .staticChunkingStrategy(

1428 StaticFileChunkingStrategy.builder()

1429 .maxChunkSizeTokens(1200)

1430 .chunkOverlapTokens(200)

1431 .build())

1432 .build();

1433 

1434var batch =

1435 client

1436 .vectorStores()

1437 .fileBatches()

1438 .create(

1439 vectorStoreId,

1440 FileBatchCreateParams.builder().addFile(first).addFile(second).build());

1441while (batch.status().equals(VectorStoreFileBatch.Status.IN_PROGRESS)) {

1442 Thread.sleep(1000);

1443 batch =

1444 client

1445 .vectorStores()

1446 .fileBatches()

1447 .retrieve(

1448 batch.id(),

1449 FileBatchRetrieveParams.builder().vectorStoreId(vectorStoreId).build());

1450}

1451System.out.println(batch.status());

1452```

1453 

1137```ruby1454```ruby

1138require "openai"1455require "openai"

1139 1456 


1204}1521}

1205```1522```

1206 1523 

1524```java

1525import com.openai.client.OpenAIClient;

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

1527 

1528String fileBatchId = "vsfb_123";

1529 

1530String vectorStoreId = "vs_123";

1531 

1532System.out.println(

1533 client

1534 .vectorStores()

1535 .fileBatches()

1536 .retrieve(

1537 fileBatchId,

1538 com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams.builder()

1539 .vectorStoreId(vectorStoreId)

1540 .build())

1541 .status());

1542```

1543 

1207```ruby1544```ruby

1208require "openai"1545require "openai"

1209 1546 


1257}1594}

1258```1595```

1259 1596 

1597```java

1598import com.openai.client.OpenAIClient;

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

1600 

1601String fileBatchId = "vsfb_123";

1602 

1603String vectorStoreId = "vs_123";

1604 

1605System.out.println(

1606 client

1607 .vectorStores()

1608 .fileBatches()

1609 .cancel(

1610 fileBatchId,

1611 com.openai.models.vectorstores.filebatches.FileBatchCancelParams.builder()

1612 .vectorStoreId(vectorStoreId)

1613 .build())

1614 .status());

1615```

1616 

1260```ruby1617```ruby

1261require "openai"1618require "openai"

1262 1619 


1310}1667}

1311```1668```

1312 1669 

1670```java

1671import com.openai.client.OpenAIClient;

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

1673 

1674String fileBatchId = "vsfb_123";

1675 

1676String vectorStoreId = "vs_123";

1677 

1678System.out.println(

1679 client

1680 .vectorStores()

1681 .fileBatches()

1682 .listFiles(

1683 fileBatchId,

1684 com.openai.models.vectorstores.filebatches.FileBatchListFilesParams.builder()

1685 .vectorStoreId(vectorStoreId)

1686 .build())

1687 .data());

1688```

1689 

1313```ruby1690```ruby

1314require "openai"1691require "openai"

1315 1692 


1383}1760}

1384```1761```

1385 1762 

1763```java

1764import com.openai.client.OpenAIClient;

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

1766import com.openai.core.JsonValue;

1767import com.openai.models.vectorstores.files.FileCreateParams;

1768 

1769String vectorStoreId = "<vector_store_id>";

1770 

1771String fileId = "file_123";

1772 

1773var file =

1774 client

1775 .vectorStores()

1776 .files()

1777 .create(

1778 vectorStoreId,

1779 FileCreateParams.builder()

1780 .fileId(fileId)

1781 .attributes(

1782 FileCreateParams.Attributes.builder()

1783 .putAdditionalProperty("category", JsonValue.from("policy"))

1784 .build())

1785 .build());

1786 

1787System.out.println(file.id());

1788```

1789 

1386```ruby1790```ruby

1387require "openai"1791require "openai"

1388 1792 


1439}1843}

1440```1844```

1441 1845 

1846```java

1847import com.openai.client.OpenAIClient;

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

1849import com.openai.core.JsonValue;

1850import com.openai.models.vectorstores.VectorStoreUpdateParams;

1851 

1852String vectorStoreId = "vs_123";

1853 

1854var store =

1855 client

1856 .vectorStores()

1857 .update(

1858 vectorStoreId,

1859 VectorStoreUpdateParams.builder()

1860 .expiresAfter(

1861 VectorStoreUpdateParams.ExpiresAfter.builder()

1862 .anchor(JsonValue.from("last_active_at"))

1863 .days(7)

1864 .build())

1865 .build());

1866 

1867System.out.println(store.expiresAfter().orElseThrow());

1868```

1869 

1442```ruby1870```ruby

1443require "openai"1871require "openai"

1444 1872 


1548}1976}

1549```1977```

1550 1978 

1979```java

1980import com.openai.client.OpenAIClient;

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

1982import com.openai.models.vectorstores.VectorStoreSearchParams;

1983 

1984String vectorStoreId = "vs_123";

1985 

1986var results =

1987 client

1988 .vectorStores()

1989 .search(

1990 vectorStoreId,

1991 VectorStoreSearchParams.builder().query("What is the return policy?").build());

1992 

1993System.out.println(results.data());

1994```

1995 

1551```ruby1996```ruby

1552require "openai"1997require "openai"

1553 1998 


1658}2103}

1659```2104```

1660 2105 

2106```java

2107import com.openai.client.OpenAIClient;

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

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

2110import com.openai.models.vectorstores.VectorStoreSearchParams;

2111import java.util.stream.Collectors;

2112 

2113String vectorStoreId = "vs_123";

2114 

2115String query = "What is the return policy?";

2116var results =

2117 client

2118 .vectorStores()

2119 .search(vectorStoreId, VectorStoreSearchParams.builder().query(query).build());

2120String sources =

2121 results.data().stream()

2122 .map(

2123 result ->

2124 "<result file_id='"

2125 + result.fileId()

2126 + "' file_name='"

2127 + result.filename()

2128 + "'>"

2129 + result.content().stream()

2130 .map(content -> "<content>" + content.text() + "</content>")

2131 .collect(Collectors.joining())

2132 + "</result>")

2133 .collect(Collectors.joining());

2134 

2135var completion =

2136 client

2137 .chat()

2138 .completions()

2139 .create(

2140 ChatCompletionCreateParams.builder()

2141 .model("gpt-5.6")

2142 .addDeveloperMessage(

2143 "Answer the query concisely using only the provided sources.")

2144 .addUserMessage(

2145 "Sources: <sources>" + sources + "</sources>\n\nQuery: " + query)

2146 .build());

2147 

2148completion.choices().stream()

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

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

2151```

2152 

1661```ruby2153```ruby

1662require "openai"2154require "openai"

1663 2155 

Details

100}100}

101```101```

102 102 

103```java

104import com.openai.client.OpenAIClient;

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

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

107 

108ChatCompletionCreateParams params =

109 ChatCompletionCreateParams.builder()

110 .model("gpt-5.6")

111 .addUserMessage("Help me plan a study schedule.")

112 .safetyIdentifier("user_1234")

113 .build();

114 

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

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

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

118```

119 

103```ruby120```ruby

104require "openai"121require "openai"

105 122 

Details

70}70}

71```71```

72 72 

73```java

74import com.openai.client.OpenAIClient;

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

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

77 

78ResponseCreateParams params =

79 ResponseCreateParams.builder()

80 .model("gpt-5.6-terra")

81 .input("Help me plan a study schedule.")

82 .safetyIdentifier("user_1234")

83 .build();

84 

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

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

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

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

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

90```

91 

73```ruby92```ruby

74require "openai"93require "openai"

75 94 


139}158}

140```159```

141 160 

161```java

162import com.openai.client.OpenAIClient;

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

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

165 

166ChatCompletionCreateParams params =

167 ChatCompletionCreateParams.builder()

168 .model("gpt-5.6-terra")

169 .addUserMessage("Help me plan a study schedule.")

170 .safetyIdentifier("user_1234")

171 .build();

172 

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

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

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

176```

177 

142```ruby178```ruby

143require "openai"179require "openai"

144 180 

Details

76}76}

77```77```

78 78 

79```java

80import com.openai.client.OpenAIClient;

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

82import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

83import java.nio.file.Path;

84 

85var result =

86 client

87 .audio()

88 .transcriptions()

89 .create(

90 TranscriptionCreateParams.builder()

91 .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))

92 .model("gpt-transcribe")

93 .build());

94 

95System.out.println(result.asTranscription().text());

96```

97 

79```ruby98```ruby

80require "openai"99require "openai"

81require "pathname"100require "pathname"


202}221}

203```222```

204 223 

224```java

225import com.openai.client.OpenAIClient;

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

227import com.openai.core.JsonValue;

228import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

229import java.nio.file.Path;

230import java.util.List;

231 

232var result =

233 client

234 .audio()

235 .transcriptions()

236 .create(

237 TranscriptionCreateParams.builder()

238 .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))

239 .model("gpt-transcribe")

240 .prompt("A customer support call about a premium plan and account AC-42.")

241 .putAdditionalBodyProperty(

242 "keywords", JsonValue.from(List.of("premium plan", "AC-42", "billing")))

243 .putAdditionalBodyProperty("languages", JsonValue.from(List.of("en", "fr")))

244 .build());

245 

246System.out.println(result.asTranscription().text());

247```

248 

205```ruby249```ruby

206require "openai"250require "openai"

207require "pathname"251require "pathname"


365}409}

366```410```

367 411 

412```java

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

414import com.openai.client.OpenAIClient;

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

416import com.openai.models.audio.AudioResponseFormat;

417import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

418import com.openai.models.audio.transcriptions.TranscriptionDiarized;

419import java.nio.file.Files;

420import java.nio.file.Path;

421import java.util.Base64;

422 

423Path audio = Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH"));

424Path speakerAudio = Path.of(System.getenv("OPENAI_EXAMPLE_SPEAKER_AUDIO_PATH"));

425String speakerReference =

426 "data:audio/wav;base64,"

427 + Base64.getEncoder().encodeToString(Files.readAllBytes(speakerAudio));

428 

429var result =

430 client

431 .audio()

432 .transcriptions()

433 .create(

434 TranscriptionCreateParams.builder()

435 .file(audio)

436 .model("gpt-4o-transcribe-diarize")

437 .responseFormat(AudioResponseFormat.DIARIZED_JSON)

438 .chunkingStrategyAuto()

439 .addKnownSpeakerName("agent")

440 .addKnownSpeakerReference(speakerReference)

441 .build());

442 

443TranscriptionDiarized diarized =

444 result.isDiarized()

445 ? result.asDiarized()

446 : new JsonMapper()

447 .readValue(result.asTranscription().text(), TranscriptionDiarized.class);

448for (var segment : diarized.segments()) {

449 System.out.println(

450 segment.speaker()

451 + ": "

452 + segment.text()

453 + " ("

454 + segment.start()

455 + "-"

456 + segment.end()

457 + ")");

458}

459```

460 

368```ruby461```ruby

369require "base64"462require "base64"

370require "openai"463require "openai"


476}569}

477```570```

478 571 

572```java

573import com.openai.client.OpenAIClient;

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

575import com.openai.models.audio.translations.TranslationCreateParams;

576import java.nio.file.Path;

577 

578var result =

579 client

580 .audio()

581 .translations()

582 .create(

583 TranslationCreateParams.builder()

584 .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))

585 .model("whisper-1")

586 .build());

587 

588System.out.println(result.asTranslation().text());

589```

590 

479```ruby591```ruby

480require "openai"592require "openai"

481require "pathname"593require "pathname"


586}698}

587```699```

588 700 

701```java

702import com.openai.client.OpenAIClient;

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

704import com.openai.models.audio.AudioResponseFormat;

705import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

706import java.nio.file.Path;

707 

708var result =

709 client

710 .audio()

711 .transcriptions()

712 .create(

713 TranscriptionCreateParams.builder()

714 .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))

715 .model("whisper-1")

716 .responseFormat(AudioResponseFormat.VERBOSE_JSON)

717 .addTimestampGranularity(TranscriptionCreateParams.TimestampGranularity.WORD)

718 .build());

719 

720result

721 .asVerbose()

722 .words()

723 .orElseThrow()

724 .forEach(

725 word -> System.out.println(word.word() + ": " + word.start() + " - " + word.end()));

726```

727 

589```ruby728```ruby

590require "openai"729require "openai"

591require "pathname"730require "pathname"


863}1002}

864```1003```

865 1004 

1005```java

1006import com.openai.client.OpenAIClient;

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

1008import com.openai.core.http.HttpResponse;

1009import com.openai.models.audio.AudioResponseFormat;

1010import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

1011import java.io.IOException;

1012import java.nio.charset.StandardCharsets;

1013import java.nio.file.Path;

1014 

1015try (HttpResponse result =

1016 client

1017 .audio()

1018 .transcriptions()

1019 .withRawResponse()

1020 .create(

1021 TranscriptionCreateParams.builder()

1022 .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))

1023 .model("whisper-1")

1024 .responseFormat(AudioResponseFormat.TEXT)

1025 .prompt(

1026 "ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, "

1027 + "OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., "

1028 + "Q.U.A.R.T.Z., F.L.I.N.T.")

1029 .build())) {

1030 System.out.println(new String(result.body().readAllBytes(), StandardCharsets.UTF_8));

1031}

1032```

1033 

866```ruby1034```ruby

867require "openai"1035require "openai"

868require "pathname"1036require "pathname"


1008}1176}

1009```1177```

1010 1178 

1179```java

1180import com.openai.client.OpenAIClient;

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

1182import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

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

1184import java.nio.file.Path;

1185 

1186String systemPrompt =

1187 """

1188 You are a helpful assistant for the company ZyntriQix. Your task is to

1189 correct any spelling discrepancies in the transcribed text. Make sure that

1190 the names of the following products are spelled correctly: ZyntriQix,

1191 Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven,

1192 DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T.

1193 Only add necessary punctuation such as periods, commas, and capitalization,

1194 and use only the context provided.

1195 """;

1196 

1197var result =

1198 client

1199 .audio()

1200 .transcriptions()

1201 .create(

1202 TranscriptionCreateParams.builder()

1203 .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))

1204 .model("gpt-4o-transcribe")

1205 .build());

1206 

1207var completion =

1208 client

1209 .chat()

1210 .completions()

1211 .create(

1212 ChatCompletionCreateParams.builder()

1213 .model("gpt-4.1")

1214 .temperature(0.0)

1215 .store(true)

1216 .addSystemMessage(systemPrompt)

1217 .addUserMessage(result.asTranscription().text())

1218 .build());

1219completion.choices().stream()

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

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

1222```

1223 

1011```ruby1224```ruby

1012require "openai"1225require "openai"

1013require "pathname"1226require "pathname"

Details

77}77}

78```78```

79 79 

80```java

81import com.openai.client.OpenAIClient;

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

83import com.openai.core.http.StreamResponse;

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

85import com.openai.models.responses.ResponseStreamEvent;

86 

87ResponseCreateParams params =

88 ResponseCreateParams.builder()

89 .model("gpt-5.6")

90 .input("Say 'double bubble bath' ten times fast.")

91 .build();

92 

93try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

94 stream.stream().forEach(System.out::println);

95}

96```

97 

80```csharp98```csharp

81using OpenAI.Responses;99using OpenAI.Responses;

82#pragma warning disable OPENAI001100#pragma warning disable OPENAI001


156type StreamingEvent = responses.ResponseStreamEventUnion174type StreamingEvent = responses.ResponseStreamEventUnion

157```175```

158 176 

177```java

178import com.openai.client.OpenAIClient;

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

180import com.openai.core.http.StreamResponse;

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

182import com.openai.models.responses.ResponseStreamEvent;

183 

184ResponseCreateParams params =

185 ResponseCreateParams.builder().model("gpt-5.5").input("Say hello.").build();

186 

187try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

188 stream.stream().forEach(System.out::println);

189}

190```

191 

159```ruby192```ruby

160require "openai"193require "openai"

161 194 

Details

124}124}

125```125```

126 126 

127```java

128import com.openai.client.OpenAIClient;

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

130import com.openai.core.JsonValue;

131import com.openai.models.responses.EasyInputMessage;

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

133import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

134import com.openai.models.responses.ResponseInputItem;

135import com.openai.models.responses.ResponseTextConfig;

136import java.util.List;

137import java.util.Map;

138 

139Map<String, Object> schema =

140 Map.of(

141 "type",

142 "object",

143 "properties",

144 Map.of(

145 "name", Map.of("type", "string"),

146 "date", Map.of("type", "string"),

147 "participants", Map.of("type", "array", "items", Map.of("type", "string"))),

148 "required",

149 List.of("name", "date", "participants"),

150 "additionalProperties",

151 false);

152 

153ResponseCreateParams params =

154 ResponseCreateParams.builder()

155 .model("gpt-5.6")

156 .inputOfResponse(

157 List.of(

158 ResponseInputItem.ofEasyInputMessage(

159 EasyInputMessage.builder()

160 .role(EasyInputMessage.Role.SYSTEM)

161 .content("Extract the event information.")

162 .build()),

163 ResponseInputItem.ofEasyInputMessage(

164 EasyInputMessage.builder()

165 .role(EasyInputMessage.Role.USER)

166 .content("Alice and Bob are going to a science fair on Friday.")

167 .build())))

168 .text(

169 ResponseTextConfig.builder()

170 .format(

171 ResponseFormatTextJsonSchemaConfig.builder()

172 .name("event")

173 .strict(true)

174 .schema(

175 JsonValue.from(schema)

176 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

177 .build())

178 .build())

179 .build();

180 

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

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

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

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

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

186```

187 

127```ruby188```ruby

128require "openai"189require "openai"

129 190 


369}430}

370```431```

371 432 

433```java

434import com.openai.client.OpenAIClient;

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

436import com.openai.core.JsonValue;

437import com.openai.models.responses.EasyInputMessage;

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

439import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

440import com.openai.models.responses.ResponseInputItem;

441import com.openai.models.responses.ResponseTextConfig;

442import java.util.List;

443import java.util.Map;

444 

445Map<String, Object> schema =

446 Map.of(

447 "type",

448 "object",

449 "properties",

450 Map.of(

451 "steps",

452 Map.of(

453 "type",

454 "array",

455 "items",

456 Map.of(

457 "type",

458 "object",

459 "properties",

460 Map.of(

461 "explanation", Map.of("type", "string"),

462 "output", Map.of("type", "string")),

463 "required",

464 List.of("explanation", "output"),

465 "additionalProperties",

466 false)),

467 "final_answer", Map.of("type", "string")),

468 "required",

469 List.of("steps", "final_answer"),

470 "additionalProperties",

471 false);

472 

473ResponseCreateParams params =

474 ResponseCreateParams.builder()

475 .model("gpt-5.6")

476 .inputOfResponse(

477 List.of(

478 ResponseInputItem.ofEasyInputMessage(

479 EasyInputMessage.builder()

480 .role(EasyInputMessage.Role.SYSTEM)

481 .content(

482 "You are a helpful math tutor. Guide the user through the solution step by step.")

483 .build()),

484 ResponseInputItem.ofEasyInputMessage(

485 EasyInputMessage.builder()

486 .role(EasyInputMessage.Role.USER)

487 .content("How can I solve 8x + 7 = -23?")

488 .build())))

489 .text(

490 ResponseTextConfig.builder()

491 .format(

492 ResponseFormatTextJsonSchemaConfig.builder()

493 .name("math_reasoning")

494 .strict(true)

495 .schema(

496 JsonValue.from(schema)

497 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

498 .build())

499 .build())

500 .build();

501 

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

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

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

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

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

507```

508 

372```ruby509```ruby

373require "openai"510require "openai"

374 511 


636}773}

637```774```

638 775 

776```java

777import com.openai.client.OpenAIClient;

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

779import com.openai.core.JsonValue;

780import com.openai.models.responses.EasyInputMessage;

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

782import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

783import com.openai.models.responses.ResponseInputItem;

784import com.openai.models.responses.ResponseTextConfig;

785import java.util.List;

786import java.util.Map;

787 

788Map<String, Object> schema =

789 Map.of(

790 "type",

791 "object",

792 "properties",

793 Map.of(

794 "title", Map.of("type", "string"),

795 "authors", Map.of("type", "array", "items", Map.of("type", "string")),

796 "abstract", Map.of("type", "string"),

797 "keywords", Map.of("type", "array", "items", Map.of("type", "string"))),

798 "required",

799 List.of("title", "authors", "abstract", "keywords"),

800 "additionalProperties",

801 false);

802 

803ResponseCreateParams params =

804 ResponseCreateParams.builder()

805 .model("gpt-5.6")

806 .inputOfResponse(

807 List.of(

808 ResponseInputItem.ofEasyInputMessage(

809 EasyInputMessage.builder()

810 .role(EasyInputMessage.Role.SYSTEM)

811 .content(

812 "You are an expert at structured data extraction. You will be given"

813 + " unstructured text from a research paper and should convert"

814 + " it into the given structure.")

815 .build()),

816 ResponseInputItem.ofEasyInputMessage(

817 EasyInputMessage.builder()

818 .role(EasyInputMessage.Role.USER)

819 .content(

820 "Attention Is All You Need by Ashish Vaswani, Noam Shazeer,"

821 + " Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez,"

822 + " Łukasz Kaiser, and Illia Polosukhin. We propose the"

823 + " Transformer, a"

824 + " sequence transduction architecture based entirely on"

825 + " attention. Keywords: transformers, attention, sequence"

826 + " transduction.")

827 .build())))

828 .text(

829 ResponseTextConfig.builder()

830 .format(

831 ResponseFormatTextJsonSchemaConfig.builder()

832 .name("research_paper_extraction")

833 .strict(true)

834 .schema(

835 JsonValue.from(schema)

836 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

837 .build())

838 .build())

839 .build();

840 

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

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

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

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

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

846```

847 

639```ruby848```ruby

640require "openai"849require "openai"

641 850 


906}1115}

907```1116```

908 1117 

1118```java

1119import com.openai.client.OpenAIClient;

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

1121import com.openai.core.JsonValue;

1122import com.openai.models.responses.EasyInputMessage;

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

1124import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

1125import com.openai.models.responses.ResponseInputItem;

1126import com.openai.models.responses.ResponseTextConfig;

1127import java.util.List;

1128import java.util.Map;

1129 

1130ResponseCreateParams params =

1131 ResponseCreateParams.builder()

1132 .model("gpt-5.6")

1133 .inputOfResponse(

1134 List.of(

1135 ResponseInputItem.ofEasyInputMessage(

1136 EasyInputMessage.builder()

1137 .role(EasyInputMessage.Role.SYSTEM)

1138 .content("Convert the user request into a UI definition.")

1139 .build()),

1140 ResponseInputItem.ofEasyInputMessage(

1141 EasyInputMessage.builder()

1142 .role(EasyInputMessage.Role.USER)

1143 .content("Make a user profile form.")

1144 .build())))

1145 .text(

1146 ResponseTextConfig.builder()

1147 .format(

1148 ResponseFormatTextJsonSchemaConfig.builder()

1149 .name("ui")

1150 .description("A dynamically generated UI")

1151 .strict(true)

1152 .schema(

1153 ResponseFormatTextJsonSchemaConfig.Schema.builder()

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

1155 .putAdditionalProperty(

1156 "properties",

1157 JsonValue.from(

1158 Map.of(

1159 "type",

1160 Map.of(

1161 "type",

1162 "string",

1163 "enum",

1164 List.of(

1165 "div", "button", "header", "section",

1166 "field", "form")),

1167 "label", Map.of("type", "string"),

1168 "children",

1169 Map.of(

1170 "type",

1171 "array",

1172 "items",

1173 Map.of("$ref", "#")),

1174 "attributes",

1175 Map.of(

1176 "type",

1177 "array",

1178 "items",

1179 Map.of(

1180 "type",

1181 "object",

1182 "properties",

1183 Map.of(

1184 "name", Map.of("type", "string"),

1185 "value", Map.of("type", "string")),

1186 "required",

1187 List.of("name", "value"),

1188 "additionalProperties",

1189 false)))))

1190 .putAdditionalProperty(

1191 "required",

1192 JsonValue.from(

1193 List.of("type", "label", "children", "attributes")))

1194 .putAdditionalProperty(

1195 "additionalProperties", JsonValue.from(false))

1196 .build())

1197 .build())

1198 .build())

1199 .build();

1200 

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

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

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

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

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

1206```

1207 

909```ruby1208```ruby

910require "openai"1209require "openai"

911 1210 


1238}1537}

1239```1538```

1240 1539 

1540```java

1541import com.openai.client.OpenAIClient;

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

1543import com.openai.core.JsonValue;

1544import com.openai.models.responses.EasyInputMessage;

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

1546import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

1547import com.openai.models.responses.ResponseInputItem;

1548import com.openai.models.responses.ResponseTextConfig;

1549import java.util.Arrays;

1550import java.util.List;

1551import java.util.Map;

1552 

1553Map<String, Object> schema =

1554 Map.of(

1555 "type",

1556 "object",

1557 "properties",

1558 Map.of(

1559 "is_violating",

1560 Map.of(

1561 "type", "boolean",

1562 "description", "Whether the content violates the guidelines"),

1563 "category",

1564 Map.of(

1565 "type", List.of("string", "null"),

1566 "enum", Arrays.asList("violence", "sexual", "self_harm", null),

1567 "description", "The violation category, or null when content is allowed"),

1568 "explanation_if_violating",

1569 Map.of(

1570 "type",

1571 List.of("string", "null"),

1572 "description",

1573 "Why the content violates the guidelines, or null")),

1574 "required",

1575 List.of("is_violating", "category", "explanation_if_violating"),

1576 "additionalProperties",

1577 false);

1578 

1579ResponseCreateParams params =

1580 ResponseCreateParams.builder()

1581 .model("gpt-5.6")

1582 .inputOfResponse(

1583 List.of(

1584 ResponseInputItem.ofEasyInputMessage(

1585 EasyInputMessage.builder()

1586 .role(EasyInputMessage.Role.SYSTEM)

1587 .content(

1588 "Determine whether the user input violates the guidelines and explain any violation.")

1589 .build()),

1590 ResponseInputItem.ofEasyInputMessage(

1591 EasyInputMessage.builder()

1592 .role(EasyInputMessage.Role.USER)

1593 .content("How do I prepare for a job interview?")

1594 .build())))

1595 .text(

1596 ResponseTextConfig.builder()

1597 .format(

1598 ResponseFormatTextJsonSchemaConfig.builder()

1599 .name("content_compliance")

1600 .description("Determines whether content violates moderation rules")

1601 .strict(true)

1602 .schema(

1603 JsonValue.from(schema)

1604 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

1605 .build())

1606 .build())

1607 .build();

1608 

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

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

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

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

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

1614```

1615 

1241```ruby1616```ruby

1242require "openai"1617require "openai"

1243 1618 


1522}1897}

1523```1898```

1524 1899 

1900```java

1901import com.openai.client.OpenAIClient;

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

1903import com.openai.core.JsonValue;

1904import com.openai.models.responses.EasyInputMessage;

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

1906import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

1907import com.openai.models.responses.ResponseInputItem;

1908import com.openai.models.responses.ResponseTextConfig;

1909import java.util.List;

1910import java.util.Map;

1911 

1912Map<String, Object> schema =

1913 Map.of(

1914 "type",

1915 "object",

1916 "properties",

1917 Map.of(

1918 "steps",

1919 Map.of(

1920 "type",

1921 "array",

1922 "items",

1923 Map.of(

1924 "type",

1925 "object",

1926 "properties",

1927 Map.of(

1928 "explanation", Map.of("type", "string"),

1929 "output", Map.of("type", "string")),

1930 "required",

1931 List.of("explanation", "output"),

1932 "additionalProperties",

1933 false)),

1934 "final_answer", Map.of("type", "string")),

1935 "required",

1936 List.of("steps", "final_answer"),

1937 "additionalProperties",

1938 false);

1939 

1940ResponseCreateParams params =

1941 ResponseCreateParams.builder()

1942 .model("gpt-5.6")

1943 .inputOfResponse(

1944 List.of(

1945 ResponseInputItem.ofEasyInputMessage(

1946 EasyInputMessage.builder()

1947 .role(EasyInputMessage.Role.SYSTEM)

1948 .content(

1949 "You are a helpful math tutor. Guide the user through the solution step by step.")

1950 .build()),

1951 ResponseInputItem.ofEasyInputMessage(

1952 EasyInputMessage.builder()

1953 .role(EasyInputMessage.Role.USER)

1954 .content("How can I solve 8x + 7 = -23?")

1955 .build())))

1956 .text(

1957 ResponseTextConfig.builder()

1958 .format(

1959 ResponseFormatTextJsonSchemaConfig.builder()

1960 .name("math_response")

1961 .strict(true)

1962 .schema(

1963 JsonValue.from(schema)

1964 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

1965 .build())

1966 .build())

1967 .build();

1968 

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

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

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

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

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

1974```

1975 

1525```ruby1976```ruby

1526require "openai"1977require "openai"

1527 1978 


1841}2292}

1842```2293```

1843 2294 

2295```java

2296import com.openai.client.OpenAIClient;

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

2298import com.openai.core.JsonValue;

2299import com.openai.models.responses.EasyInputMessage;

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

2301import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

2302import com.openai.models.responses.ResponseInputItem;

2303import com.openai.models.responses.ResponseStatus;

2304import com.openai.models.responses.ResponseTextConfig;

2305import java.util.List;

2306import java.util.Map;

2307 

2308ResponseCreateParams params =

2309 ResponseCreateParams.builder()

2310 .model("gpt-5.6")

2311 .inputOfResponse(

2312 List.of(

2313 ResponseInputItem.ofEasyInputMessage(

2314 EasyInputMessage.builder()

2315 .role(EasyInputMessage.Role.SYSTEM)

2316 .content(

2317 "You are a helpful math tutor. Guide the user through the solution step by step.")

2318 .build()),

2319 ResponseInputItem.ofEasyInputMessage(

2320 EasyInputMessage.builder()

2321 .role(EasyInputMessage.Role.USER)

2322 .content("How can I solve 8x + 7 = -23?")

2323 .build())))

2324 .text(

2325 ResponseTextConfig.builder()

2326 .format(

2327 ResponseFormatTextJsonSchemaConfig.builder()

2328 .name("math_response")

2329 .strict(true)

2330 .schema(

2331 ResponseFormatTextJsonSchemaConfig.Schema.builder()

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

2333 .putAdditionalProperty(

2334 "properties",

2335 JsonValue.from(

2336 Map.of(

2337 "steps",

2338 Map.of(

2339 "type",

2340 "array",

2341 "items",

2342 Map.of(

2343 "type",

2344 "object",

2345 "properties",

2346 Map.of(

2347 "explanation",

2348 Map.of("type", "string"),

2349 "output",

2350 Map.of("type", "string")),

2351 "required",

2352 List.of("explanation", "output"),

2353 "additionalProperties",

2354 false)),

2355 "final_answer",

2356 Map.of("type", "string"))))

2357 .putAdditionalProperty(

2358 "required",

2359 JsonValue.from(List.of("steps", "final_answer")))

2360 .putAdditionalProperty(

2361 "additionalProperties", JsonValue.from(false))

2362 .build())

2363 .build())

2364 .build())

2365 .maxOutputTokens(1_024L)

2366 .build();

2367 

2368var response = client.responses().create(params);

2369if (response.status().filter(ResponseStatus.INCOMPLETE::equals).isPresent()) {

2370 throw new IllegalStateException("Incomplete response");

2371}

2372 

2373var content =

2374 response.output().stream()

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

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

2377 .findFirst()

2378 .orElseThrow(() -> new IllegalStateException("No response content"));

2379 

2380if (content.refusal().isPresent()) {

2381 System.out.println(content.refusal().orElseThrow().refusal());

2382} else {

2383 System.out.println(

2384 content

2385 .outputText()

2386 .orElseThrow(() -> new IllegalStateException("No response content"))

2387 .text());

2388}

2389```

2390 

1844```ruby2391```ruby

1845require "openai"2392require "openai"

1846 2393 


2066}2613}

2067```2614```

2068 2615 

2616```java

2617import com.openai.client.OpenAIClient;

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

2619import com.openai.core.JsonValue;

2620import com.openai.models.responses.EasyInputMessage;

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

2622import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

2623import com.openai.models.responses.ResponseInputItem;

2624import com.openai.models.responses.ResponseTextConfig;

2625import java.util.List;

2626import java.util.Map;

2627 

2628Map<String, Object> schema =

2629 Map.of(

2630 "type",

2631 "object",

2632 "properties",

2633 Map.of(

2634 "steps",

2635 Map.of(

2636 "type",

2637 "array",

2638 "items",

2639 Map.of(

2640 "type",

2641 "object",

2642 "properties",

2643 Map.of(

2644 "explanation", Map.of("type", "string"),

2645 "output", Map.of("type", "string")),

2646 "required",

2647 List.of("explanation", "output"),

2648 "additionalProperties",

2649 false)),

2650 "final_answer", Map.of("type", "string")),

2651 "required",

2652 List.of("steps", "final_answer"),

2653 "additionalProperties",

2654 false);

2655 

2656ResponseCreateParams params =

2657 ResponseCreateParams.builder()

2658 .model("gpt-5.6")

2659 .inputOfResponse(

2660 List.of(

2661 ResponseInputItem.ofEasyInputMessage(

2662 EasyInputMessage.builder()

2663 .role(EasyInputMessage.Role.SYSTEM)

2664 .content(

2665 "You are a helpful math tutor. Guide the user through the solution step by step.")

2666 .build()),

2667 ResponseInputItem.ofEasyInputMessage(

2668 EasyInputMessage.builder()

2669 .role(EasyInputMessage.Role.USER)

2670 .content("How can I solve 8x + 7 = -23?")

2671 .build())))

2672 .text(

2673 ResponseTextConfig.builder()

2674 .format(

2675 ResponseFormatTextJsonSchemaConfig.builder()

2676 .name("math_reasoning")

2677 .strict(true)

2678 .schema(

2679 JsonValue.from(schema)

2680 .convert(ResponseFormatTextJsonSchemaConfig.Schema.class))

2681 .build())

2682 .build())

2683 .build();

2684 

2685var response = client.responses().create(params);

2686for (var output : response.output()) {

2687 if (output.message().isEmpty()) continue;

2688 for (var content : output.message().orElseThrow().content()) {

2689 if (content.refusal().isPresent()) {

2690 System.out.println(content.refusal().orElseThrow().refusal());

2691 } else {

2692 content.outputText().ifPresent(text -> System.out.println(text.text()));

2693 }

2694 }

2695}

2696```

2697 

2069```ruby2698```ruby

2070require "openai"2699require "openai"

2071 2700 


2287 print(final_response)2916 print(final_response)

2288```2917```

2289 2918 

2919```java

2920import com.openai.client.OpenAIClient;

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

2922import com.openai.core.JsonValue;

2923import com.openai.core.http.StreamResponse;

2924import com.openai.models.responses.EasyInputMessage;

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

2926import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;

2927import com.openai.models.responses.ResponseInputItem;

2928import com.openai.models.responses.ResponseStreamEvent;

2929import com.openai.models.responses.ResponseTextConfig;

2930import java.util.List;

2931import java.util.Map;

2932 

2933ResponseCreateParams params =

2934 ResponseCreateParams.builder()

2935 .model("gpt-5.6")

2936 .inputOfResponse(

2937 List.of(

2938 ResponseInputItem.ofEasyInputMessage(

2939 EasyInputMessage.builder()

2940 .role(EasyInputMessage.Role.SYSTEM)

2941 .content("Extract entities from the input text")

2942 .build()),

2943 ResponseInputItem.ofEasyInputMessage(

2944 EasyInputMessage.builder()

2945 .role(EasyInputMessage.Role.USER)

2946 .content(

2947 "The quick brown fox jumps over the lazy dog with piercing blue eyes")

2948 .build())))

2949 .text(

2950 ResponseTextConfig.builder()

2951 .format(

2952 ResponseFormatTextJsonSchemaConfig.builder()

2953 .name("entities")

2954 .strict(true)

2955 .schema(

2956 ResponseFormatTextJsonSchemaConfig.Schema.builder()

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

2958 .putAdditionalProperty(

2959 "properties",

2960 JsonValue.from(

2961 Map.of(

2962 "attributes",

2963 Map.of(

2964 "type",

2965 "array",

2966 "items",

2967 Map.of("type", "string")),

2968 "colors",

2969 Map.of(

2970 "type",

2971 "array",

2972 "items",

2973 Map.of("type", "string")),

2974 "animals",

2975 Map.of(

2976 "type",

2977 "array",

2978 "items",

2979 Map.of("type", "string")))))

2980 .putAdditionalProperty(

2981 "required",

2982 JsonValue.from(List.of("attributes", "colors", "animals")))

2983 .putAdditionalProperty(

2984 "additionalProperties", JsonValue.from(false))

2985 .build())

2986 .build())

2987 .build())

2988 .build();

2989 

2990try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

2991 stream.stream()

2992 .forEach(

2993 event -> {

2994 event.outputTextDelta().ifPresent(delta -> System.out.print(delta.delta()));

2995 event.refusalDelta().ifPresent(refusal -> System.out.print(refusal.delta()));

2996 event.error().ifPresent(error -> System.out.println(error.message()));

2997 event

2998 .completed()

2999 .ifPresent(

3000 completed -> {

3001 System.out.println("Completed");

3002 System.out.println(completed.response());

3003 });

3004 });

3005}

3006```

3007 

2290 3008 

2291 3009 

2292## Supported schemas3010## Supported schemas


2985}3703}

2986```3704```

2987 3705 

3706```java

3707import com.openai.client.OpenAIClient;

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

3709import com.openai.errors.OpenAIServiceException;

3710import com.openai.models.ResponseFormatJsonObject;

3711import com.openai.models.responses.EasyInputMessage;

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

3713import com.openai.models.responses.ResponseInputItem;

3714import com.openai.models.responses.ResponseStatus;

3715import com.openai.models.responses.ResponseTextConfig;

3716import java.util.List;

3717 

3718ResponseCreateParams params =

3719 ResponseCreateParams.builder()

3720 .model("gpt-5.6")

3721 .inputOfResponse(

3722 List.of(

3723 ResponseInputItem.ofEasyInputMessage(

3724 EasyInputMessage.builder()

3725 .role(EasyInputMessage.Role.SYSTEM)

3726 .content("You are a helpful assistant designed to output JSON.")

3727 .build()),

3728 ResponseInputItem.ofEasyInputMessage(

3729 EasyInputMessage.builder()

3730 .role(EasyInputMessage.Role.USER)

3731 .content(

3732 "Who won the World Series in 2020? Respond in the format {winner: ...}.")

3733 .build())))

3734 .text(

3735 ResponseTextConfig.builder()

3736 .format(ResponseFormatJsonObject.builder().build())

3737 .build())

3738 .build();

3739 

3740try {

3741 var response = client.responses().create(params);

3742 if (response.status().filter(ResponseStatus.INCOMPLETE::equals).isPresent()) {

3743 String reason =

3744 response

3745 .incompleteDetails()

3746 .flatMap(details -> details.reason())

3747 .map(Object::toString)

3748 .orElse("unknown");

3749 System.out.println("The JSON response is incomplete. Reason: " + reason);

3750 return;

3751 }

3752 

3753 for (var output : response.output()) {

3754 if (output.message().isEmpty()) continue;

3755 for (var content : output.message().orElseThrow().content()) {

3756 if (content.refusal().isPresent()) {

3757 System.out.println(content.refusal().orElseThrow().refusal());

3758 return;

3759 }

3760 if (response.status().filter(ResponseStatus.COMPLETED::equals).isPresent()) {

3761 content.outputText().ifPresent(text -> System.out.println(text.text()));

3762 }

3763 }

3764 }

3765} catch (OpenAIServiceException error) {

3766 System.out.println("Request failed: " + error.getMessage());

3767}

3768```

3769 

2988```ruby3770```ruby

2989require "json"3771require "json"

2990require "openai"3772require "openai"

guides/text.md +66 −0

Details

242}242}

243```243```

244 244 

245```java

246import com.openai.client.OpenAIClient;

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

248import com.openai.models.Reasoning;

249import com.openai.models.ReasoningEffort;

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

251 

252String semicolonsDevMsg = "Talk like a pirate.";

253 

254String semicolonsPrompt = "Are semicolons optional in JavaScript?";

255 

256ResponseCreateParams params =

257 ResponseCreateParams.builder()

258 .model("gpt-5.6")

259 .input(semicolonsPrompt)

260 .instructions(semicolonsDevMsg)

261 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

262 .build();

263 

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

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

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

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

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

269```

270 

245```ruby271```ruby

246require "openai"272require "openai"

247 273 


352}378}

353```379```

354 380 

381```java

382import com.openai.client.OpenAIClient;

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

384import com.openai.models.Reasoning;

385import com.openai.models.ReasoningEffort;

386import com.openai.models.responses.EasyInputMessage;

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

388import com.openai.models.responses.ResponseInputItem;

389import java.util.List;

390 

391String semicolonsDevMsg = "Talk like a pirate.";

392 

393String semicolonsPrompt = "Are semicolons optional in JavaScript?";

394 

395ResponseCreateParams params =

396 ResponseCreateParams.builder()

397 .model("gpt-5.6")

398 .input(

399 ResponseCreateParams.Input.ofResponse(

400 List.of(

401 ResponseInputItem.ofEasyInputMessage(

402 EasyInputMessage.builder()

403 .role(EasyInputMessage.Role.DEVELOPER)

404 .content(semicolonsDevMsg)

405 .build()),

406 ResponseInputItem.ofEasyInputMessage(

407 EasyInputMessage.builder()

408 .role(EasyInputMessage.Role.USER)

409 .content(semicolonsPrompt)

410 .build()))))

411 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())

412 .build();

413 

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

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

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

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

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

419```

420 

355```ruby421```ruby

356require "openai"422require "openai"

357 423 

Details

98}98}

99```99```

100 100 

101```java

102import com.openai.client.OpenAIClient;

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

104import com.openai.core.http.HttpResponse;

105import com.openai.models.audio.speech.SpeechCreateParams;

106import java.io.IOException;

107import java.nio.file.Files;

108import java.nio.file.Path;

109import java.nio.file.StandardCopyOption;

110 

111try (HttpResponse audio =

112 client

113 .audio()

114 .speech()

115 .create(

116 SpeechCreateParams.builder()

117 .model("gpt-4o-mini-tts")

118 .voice("coral")

119 .input("Today is a wonderful day to build something people love!")

120 .instructions("Speak in a cheerful and positive tone.")

121 .build())) {

122 Files.copy(audio.body(), Path.of("speech.mp3"), StandardCopyOption.REPLACE_EXISTING);

123}

124```

125 

101```ruby126```ruby

102require "openai"127require "openai"

103 128 


251}276}

252```277```

253 278 

279```java

280import com.openai.client.OpenAIClient;

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

282import com.openai.core.http.HttpResponse;

283import com.openai.models.audio.speech.SpeechCreateParams;

284import java.io.IOException;

285import java.io.OutputStream;

286import java.nio.file.Files;

287import java.nio.file.Path;

288import javax.sound.sampled.AudioFormat;

289import javax.sound.sampled.AudioSystem;

290import javax.sound.sampled.LineUnavailableException;

291import javax.sound.sampled.SourceDataLine;

292 

293try (HttpResponse audio =

294 client

295 .audio()

296 .speech()

297 .create(

298 SpeechCreateParams.builder()

299 .model("gpt-4o-mini-tts")

300 .voice("coral")

301 .input("Today is a wonderful day to build something people love!")

302 .instructions("Speak in a cheerful and positive tone.")

303 .responseFormat(SpeechCreateParams.ResponseFormat.PCM)

304 .streamFormat(SpeechCreateParams.StreamFormat.AUDIO)

305 .build())) {

306 AudioFormat format = new AudioFormat(24_000, 16, 1, true, false);

307 String outputPath = System.getenv("OPENAI_EXAMPLE_AUDIO_OUTPUT_PATH");

308 if (outputPath == null || outputPath.isBlank()) {

309 try (SourceDataLine speakers = AudioSystem.getSourceDataLine(format)) {

310 speakers.open(format);

311 speakers.start();

312 byte[] chunk = new byte[1024];

313 int bytesRead;

314 while ((bytesRead = audio.body().read(chunk)) != -1) {

315 speakers.write(chunk, 0, bytesRead);

316 }

317 speakers.drain();

318 }

319 } else {

320 try (OutputStream output = Files.newOutputStream(Path.of(outputPath))) {

321 long bytes = audio.body().transferTo(output);

322 System.out.println(bytes + " audio bytes");

323 }

324 }

325}

326```

327 

254```ruby328```ruby

255require "openai"329require "openai"

256 330 

Details

75}75}

76```76```

77 77 

78```java

79import com.openai.client.OpenAIClient;

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

81import com.openai.models.responses.inputtokens.InputTokenCountParams;

82 

83var count =

84 client

85 .responses()

86 .inputTokens()

87 .count(

88 InputTokenCountParams.builder()

89 .model("gpt-5.6")

90 .input("Tell me a joke.")

91 .build());

92 

93System.out.println(count.inputTokens());

94```

95 

78```ruby96```ruby

79require "openai"97require "openai"

80 98 


173}191}

174```192```

175 193 

194```java

195import com.openai.client.OpenAIClient;

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

197import com.openai.models.responses.EasyInputMessage;

198import com.openai.models.responses.ResponseInputItem;

199import com.openai.models.responses.inputtokens.InputTokenCountParams;

200import java.util.List;

201 

202var count =

203 client

204 .responses()

205 .inputTokens()

206 .count(

207 InputTokenCountParams.builder()

208 .model("gpt-5.6")

209 .inputOfResponseInputItems(

210 List.of(

211 ResponseInputItem.ofEasyInputMessage(

212 EasyInputMessage.builder()

213 .role(EasyInputMessage.Role.USER)

214 .content("What is 2 + 2?")

215 .build()),

216 ResponseInputItem.ofEasyInputMessage(

217 EasyInputMessage.builder()

218 .role(EasyInputMessage.Role.ASSISTANT)

219 .content("2 + 2 equals 4.")

220 .build()),

221 ResponseInputItem.ofEasyInputMessage(

222 EasyInputMessage.builder()

223 .role(EasyInputMessage.Role.USER)

224 .content("What about 3 + 3?")

225 .build())))

226 .build());

227 

228System.out.println(count.inputTokens());

229```

230 

176```ruby231```ruby

177require "openai"232require "openai"

178 233 


277}332}

278```333```

279 334 

335```java

336import com.openai.client.OpenAIClient;

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

338import com.openai.models.responses.inputtokens.InputTokenCountParams;

339 

340var count =

341 client

342 .responses()

343 .inputTokens()

344 .count(

345 InputTokenCountParams.builder()

346 .model("gpt-5.6")

347 .input("Explain quantum computing in one sentence.")

348 .instructions("You are a helpful assistant that explains concepts simply.")

349 .build());

350 

351System.out.println(count.inputTokens());

352```

353 

280```ruby354```ruby

281require "openai"355require "openai"

282 356 


401}475}

402```476```

403 477 

478```java

479import com.openai.client.OpenAIClient;

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

481import com.openai.models.responses.ResponseInputImage;

482import com.openai.models.responses.ResponseInputItem;

483import com.openai.models.responses.inputtokens.InputTokenCountParams;

484import java.util.List;

485 

486var count =

487 client

488 .responses()

489 .inputTokens()

490 .count(

491 InputTokenCountParams.builder()

492 .model("gpt-5.6")

493 .inputOfResponseInputItems(

494 List.of(

495 ResponseInputItem.ofMessage(

496 ResponseInputItem.Message.builder()

497 .role(ResponseInputItem.Message.Role.USER)

498 .addContent(

499 ResponseInputImage.builder()

500 .detail(ResponseInputImage.Detail.AUTO)

501 .imageUrl(

502 "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg")

503 .build())

504 .addInputTextContent("Summarize this chart.")

505 .build())))

506 .build());

507 

508System.out.println(count.inputTokens());

509```

510 

404```ruby511```ruby

405require "openai"512require "openai"

406 513 


552}659}

553```660```

554 661 

662```java

663import com.openai.client.OpenAIClient;

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

665import com.openai.core.JsonValue;

666import com.openai.models.responses.FunctionTool;

667import com.openai.models.responses.inputtokens.InputTokenCountParams;

668import java.util.List;

669import java.util.Map;

670 

671var count =

672 client

673 .responses()

674 .inputTokens()

675 .count(

676 InputTokenCountParams.builder()

677 .model("gpt-5.6")

678 .input("What is the weather in San Francisco?")

679 .addTool(

680 FunctionTool.builder()

681 .name("get_weather")

682 .description("Get the current weather in a location")

683 .strict(true)

684 .parameters(

685 FunctionTool.Parameters.builder()

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

687 .putAdditionalProperty(

688 "properties",

689 JsonValue.from(

690 Map.of("location", Map.of("type", "string"))))

691 .putAdditionalProperty(

692 "required", JsonValue.from(List.of("location")))

693 .putAdditionalProperty(

694 "additionalProperties", JsonValue.from(false))

695 .build())

696 .build())

697 .build());

698 

699System.out.println(count.inputTokens());

700```

701 

555```ruby702```ruby

556require "openai"703require "openai"

557 704 

guides/tools.md +169 −0

Details

64}64}

65```65```

66 66 

67```java

68import com.openai.client.OpenAIClient;

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

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

71import com.openai.models.responses.WebSearchTool;

72 

73ResponseCreateParams params =

74 ResponseCreateParams.builder()

75 .model("gpt-5.6")

76 .input("What was a positive news story from today?")

77 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

78 .build();

79 

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

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

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

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

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

85```

86 

67```csharp87```csharp

68using OpenAI.Responses;88using OpenAI.Responses;

69#pragma warning disable OPENAI00189#pragma warning disable OPENAI001


182}202}

183```203```

184 204 

205```java

206import com.openai.client.OpenAIClient;

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

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

209import java.util.List;

210 

211String vectorStoreId = "<vector_store_id>";

212 

213ResponseCreateParams params =

214 ResponseCreateParams.builder()

215 .model("gpt-5.6")

216 .input("What is deep research by OpenAI?")

217 .addFileSearchTool(List.of(vectorStoreId))

218 .build();

219 

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

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

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

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

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

225```

226 

185```csharp227```csharp

186using OpenAI.Responses;228using OpenAI.Responses;

187#pragma warning disable OPENAI001229#pragma warning disable OPENAI001


386}428}

387```429```

388 430 

431```java

432import com.openai.client.OpenAIClient;

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

434import com.openai.core.JsonValue;

435import com.openai.models.responses.NamespaceTool;

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

437import com.openai.models.responses.ToolSearchTool;

438import java.util.List;

439import java.util.Map;

440 

441ResponseCreateParams params =

442 ResponseCreateParams.builder()

443 .model("gpt-5.6")

444 .input("List open orders for customer CUST-12345.")

445 .parallelToolCalls(false)

446 .addTool(

447 NamespaceTool.builder()

448 .name("crm")

449 .description("CRM tools for customer lookup and order management.")

450 .addTool(

451 NamespaceTool.Tool.Function.builder()

452 .name("get_customer_profile")

453 .description("Fetch a customer profile by customer ID.")

454 .strict(true)

455 .parameters(

456 JsonValue.from(

457 Map.of(

458 "type",

459 "object",

460 "properties",

461 Map.of("customer_id", Map.of("type", "string")),

462 "required",

463 List.of("customer_id"),

464 "additionalProperties",

465 false)))

466 .build())

467 .addTool(

468 NamespaceTool.Tool.Function.builder()

469 .name("list_open_orders")

470 .description("List open orders for a customer ID.")

471 .deferLoading(true)

472 .strict(true)

473 .parameters(

474 JsonValue.from(

475 Map.of(

476 "type",

477 "object",

478 "properties",

479 Map.of("customer_id", Map.of("type", "string")),

480 "required",

481 List.of("customer_id"),

482 "additionalProperties",

483 false)))

484 .build())

485 .build())

486 .addTool(ToolSearchTool.builder().execution(ToolSearchTool.Execution.SERVER).build())

487 .build();

488 

489client.responses().create(params).output().forEach(System.out::println);

490```

491 

389```ruby492```ruby

390require "openai"493require "openai"

391 494 


550}653}

551```654```

552 655 

656```java

657import com.openai.client.OpenAIClient;

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

659import com.openai.core.JsonValue;

660import com.openai.models.responses.FunctionTool;

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

662import java.util.List;

663import java.util.Map;

664 

665ResponseCreateParams params =

666 ResponseCreateParams.builder()

667 .model("gpt-5.6")

668 .input("What is the weather like in Paris today?")

669 .addTool(

670 FunctionTool.builder()

671 .name("get_weather")

672 .description("Get current temperature for a given location.")

673 .parameters(

674 FunctionTool.Parameters.builder()

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

676 .putAdditionalProperty(

677 "properties",

678 JsonValue.from(

679 Map.of(

680 "location",

681 Map.of(

682 "type", "string",

683 "description",

684 "City and country e.g. Bogotá, Colombia"))))

685 .putAdditionalProperty("required", JsonValue.from(List.of("location")))

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

687 .build())

688 .strict(true)

689 .build())

690 .build();

691 

692client.responses().create(params).output().forEach(System.out::println);

693```

694 

553```csharp695```csharp

554using System.Text.Json;696using System.Text.Json;

555using System.Text.Json.Serialization.Metadata;697using System.Text.Json.Serialization.Metadata;


768}910}

769```911```

770 912 

913```java

914import com.openai.client.OpenAIClient;

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

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

917import com.openai.models.responses.Tool;

918 

919ResponseCreateParams params =

920 ResponseCreateParams.builder()

921 .model("gpt-5.6")

922 .input("Roll 2d4+1")

923 .addTool(

924 Tool.Mcp.builder()

925 .serverLabel("dmcp")

926 .serverDescription(

927 "A Dungeons and Dragons MCP server to assist with dice rolling.")

928 .serverUrl("https://dmcp-server.deno.dev/mcp")

929 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

930 .build())

931 .build();

932 

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

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

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

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

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

938```

939 

771```csharp940```csharp

772using OpenAI.Responses;941using OpenAI.Responses;

773#pragma warning disable OPENAI001942#pragma warning disable OPENAI001

Details

106}106}

107```107```

108 108 

109```java

110import com.openai.client.OpenAIClient;

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

112import com.openai.models.responses.ApplyPatchTool;

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

114 

115ResponseCreateParams params =

116 ResponseCreateParams.builder()

117 .model("gpt-5.6")

118 .input(

119 "Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name.")

120 .addTool(ApplyPatchTool.builder().build())

121 .build();

122 

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

124 .flatMap(item -> item.applyPatchCall().stream())

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

126```

127 

109```ruby128```ruby

110require "openai"129require "openai"

111 130 


199}218}

200```219```

201 220 

221```java

222import com.openai.client.OpenAIClient;

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

224import com.openai.models.responses.ApplyPatchTool;

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

226import com.openai.models.responses.ResponseInputItem;

227import java.util.List;

228 

229ResponseCreateParams params =

230 ResponseCreateParams.builder()

231 .model("gpt-5.6")

232 .inputOfResponse(

233 List.of(

234 ResponseInputItem.ofApplyPatchCallOutput(

235 ResponseInputItem.ApplyPatchCallOutput.builder()

236 .callId(System.getenv("OPENAI_EXAMPLE_APPLY_PATCH_CALL_ID"))

237 .status(ResponseInputItem.ApplyPatchCallOutput.Status.COMPLETED)

238 .output("Patch applied successfully.")

239 .build())))

240 .previousResponseId(System.getenv("OPENAI_EXAMPLE_PREVIOUS_RESPONSE_ID"))

241 .addTool(ApplyPatchTool.builder().build())

242 .build();

243 

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

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

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

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

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

249```

250 

202```ruby251```ruby

203require "openai"252require "openai"

204 253 

Details

104}104}

105```105```

106 106 

107```java

108import com.openai.client.OpenAIClient;

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

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

111import com.openai.models.responses.Tool;

112 

113ResponseCreateParams params =

114 ResponseCreateParams.builder()

115 .model("gpt-5.6")

116 .input("I need to solve the equation 3x + 11 = 14. Can you help me?")

117 .instructions(

118 "You are a personal math tutor. Write and run Python code to answer each math question.")

119 .addCodeInterpreterTool(

120 Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder()

121 .memoryLimit(

122 Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.MemoryLimit._4G)

123 .build())

124 .build();

125 

126client.responses().create(params).output().forEach(System.out::println);

127```

128 

107```ruby129```ruby

108require "openai"130require "openai"

109 131 


246}268}

247```269```

248 270 

271```java

272import com.openai.client.OpenAIClient;

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

274import com.openai.models.containers.ContainerCreateParams;

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

276import com.openai.models.responses.ToolChoiceOptions;

277 

278var container =

279 client

280 .containers()

281 .create(

282 ContainerCreateParams.builder()

283 .name("analysis")

284 .memoryLimit(ContainerCreateParams.MemoryLimit._4G)

285 .build());

286 

287var response =

288 client

289 .responses()

290 .create(

291 ResponseCreateParams.builder()

292 .model("gpt-5.6")

293 .input("Calculate 4 * 3.82, then take the square root twice.")

294 .toolChoice(ToolChoiceOptions.REQUIRED)

295 .addCodeInterpreterTool(container.id())

296 .build());

297 

298response.output().stream()

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

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

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

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

303```

304 

249```ruby305```ruby

250require "openai"306require "openai"

251 307 

Details

275}275}

276```276```

277 277 

278```java

279import com.openai.client.OpenAIClient;

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

281import com.openai.core.JsonValue;

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

283import java.util.List;

284import java.util.Map;

285 

286ResponseCreateParams params =

287 ResponseCreateParams.builder()

288 .model("gpt-5.6")

289 .input(

290 "Open the Filters panel if needed, then search for penguin. Use the computer tool for UI interaction.")

291 .putAdditionalBodyProperty("tools", JsonValue.from(List.of(Map.of("type", "computer"))))

292 .build();

293 

294client.responses().create(params).output().forEach(System.out::println);

295```

296 

278```ruby297```ruby

279require "openai"298require "openai"

280 299 


1711}1730}

1712```1731```

1713 1732 

1733```java

1734import com.openai.client.OpenAIClient;

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

1736import com.openai.core.JsonValue;

1737import com.openai.models.responses.ResponseComputerToolCallOutputScreenshot;

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

1739import com.openai.models.responses.ResponseInputItem;

1740import java.util.List;

1741import java.util.Map;

1742 

1743String responseId = "resp_abc123";

1744 

1745String computerCallId = "call_abc123";

1746 

1747String screenshotBase64 = "<base64 bytes here>";

1748 

1749ResponseCreateParams params =

1750 ResponseCreateParams.builder()

1751 .model("gpt-5.6")

1752 .input(

1753 ResponseCreateParams.Input.ofResponse(

1754 List.of(

1755 ResponseInputItem.ofComputerCallOutput(

1756 ResponseInputItem.ComputerCallOutput.builder()

1757 .callId(computerCallId)

1758 .output(

1759 ResponseComputerToolCallOutputScreenshot.builder()

1760 .imageUrl("data:image/png;base64," + screenshotBase64)

1761 .putAdditionalProperty("detail", JsonValue.from("original"))

1762 .build())

1763 .build()))))

1764 .previousResponseId(responseId)

1765 .putAdditionalBodyProperty("tools", JsonValue.from(List.of(Map.of("type", "computer"))))

1766 .build();

1767 

1768client.responses().create(params).output().forEach(System.out::println);

1769```

1770 

1714```ruby1771```ruby

1715require "openai"1772require "openai"

1716 1773 


1820 )1877 )

1821```1878```

1822 1879 

1880```java

1881import com.openai.client.OpenAIClient;

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

1883import com.openai.core.JsonValue;

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

1885import com.openai.models.responses.ResponseComputerToolCallOutputScreenshot;

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

1887import com.openai.models.responses.ResponseInputItem;

1888import java.io.IOException;

1889import java.nio.charset.StandardCharsets;

1890import java.util.ArrayList;

1891import java.util.Base64;

1892import java.util.List;

1893import java.util.Locale;

1894import java.util.Map;

1895 

1896@FunctionalInterface

1897interface ContainerAction {

1898 void run() throws Exception;

1899}

1900 

1901static int wheelUnits(long pixels) {

1902 if (pixels == 0) return 0;

1903 long rounded = Math.round(pixels / 100.0);

1904 if (rounded == 0) rounded = Long.signum(pixels);

1905 return Math.toIntExact(Math.max(-100, Math.min(100, rounded)));

1906}

1907 

1908static String isolatedContainerName(String name) {

1909 if (name == null || !name.matches("[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")) {

1910 throw new IllegalStateException(

1911 "Computer use requires an explicitly isolated Docker container; "

1912 + "start the documented VM and set OPENAI_EXAMPLE_COMPUTER_CONTAINER.");

1913 }

1914 return name;

1915}

1916 

1917record IsolatedContainer(String name) {

1918 byte[] run(String... arguments) throws IOException, InterruptedException {

1919 var command = new ArrayList<>(List.of("docker", "exec", "--env", "DISPLAY=:99", name));

1920 command.addAll(List.of(arguments));

1921 

1922 Process process = new ProcessBuilder(command).redirectErrorStream(true).start();

1923 byte[] output = process.getInputStream().readAllBytes();

1924 if (process.waitFor() != 0) {

1925 throw new IOException(

1926 "Isolated Docker command failed: " + new String(output, StandardCharsets.UTF_8));

1927 }

1928 return output;

1929 }

1930 

1931 String key(String name) {

1932 return switch (name.toUpperCase(Locale.ROOT)) {

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

1934 case "SHIFT" -> "shift";

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

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

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

1938 case "TAB" -> "Tab";

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

1940 case "BACKSPACE" -> "BackSpace";

1941 case "DELETE" -> "Delete";

1942 case "ARROWLEFT" -> "Left";

1943 case "ARROWRIGHT" -> "Right";

1944 case "ARROWUP" -> "Up";

1945 case "ARROWDOWN" -> "Down";

1946 default -> {

1947 if (name.length() != 1 || !Character.isLetterOrDigit(name.charAt(0))) {

1948 throw new IllegalArgumentException("Unsupported key: " + name);

1949 }

1950 yield name;

1951 }

1952 };

1953 }

1954 

1955 void withModifiers(List<String> modifiers, ContainerAction action) throws Exception {

1956 var keys = modifiers.stream().map(this::key).toList();

1957 for (String key : keys) run("xdotool", "keydown", key);

1958 try {

1959 action.run();

1960 } finally {

1961 for (int index = keys.size() - 1; index >= 0; index--) {

1962 run("xdotool", "keyup", keys.get(index));

1963 }

1964 }

1965 }

1966 

1967 void move(long x, long y) throws IOException, InterruptedException {

1968 if (x < 0 || y < 0) throw new IllegalArgumentException("Negative mouse coordinates");

1969 run("xdotool", "mousemove", Long.toString(x), Long.toString(y));

1970 }

1971 

1972 String button(String name) {

1973 return switch (name) {

1974 case "left" -> "1";

1975 case "wheel" -> "2";

1976 case "right" -> "3";

1977 case "back" -> "8";

1978 case "forward" -> "9";

1979 default -> throw new IllegalArgumentException("Unsupported button: " + name);

1980 };

1981 }

1982 

1983 void scroll(long pixels, String negative, String positive)

1984 throws IOException, InterruptedException {

1985 int units = wheelUnits(pixels);

1986 if (units != 0) {

1987 run(

1988 "xdotool",

1989 "click",

1990 "--repeat",

1991 Integer.toString(Math.abs(units)),

1992 units < 0 ? negative : positive);

1993 }

1994 }

1995 

1996 void execute(ComputerAction action) throws Exception {

1997 if (action.isScreenshot()) return;

1998 if (action.isWait()) {

1999 Thread.sleep(1000);

2000 return;

2001 }

2002 if (action.isType()) {

2003 run("xdotool", "type", "--delay", "0", "--", action.asType().text());

2004 return;

2005 }

2006 if (action.isKeypress()) {

2007 var keys = action.asKeypress().keys().stream().map(this::key).toList();

2008 run("xdotool", "key", String.join("+", keys));

2009 return;

2010 }

2011 if (action.isClick()) {

2012 var click = action.asClick();

2013 withModifiers(

2014 click.keys().orElse(List.of()),

2015 () -> {

2016 move(click.x(), click.y());

2017 run("xdotool", "click", button(click.button().asString()));

2018 });

2019 return;

2020 }

2021 if (action.isDoubleClick()) {

2022 var click = action.asDoubleClick();

2023 withModifiers(

2024 click.keys().orElse(List.of()),

2025 () -> {

2026 move(click.x(), click.y());

2027 run("xdotool", "click", "--repeat", "2", "1");

2028 });

2029 return;

2030 }

2031 if (action.isMove()) {

2032 var move = action.asMove();

2033 withModifiers(move.keys().orElse(List.of()), () -> move(move.x(), move.y()));

2034 return;

2035 }

2036 if (action.isScroll()) {

2037 var scroll = action.asScroll();

2038 withModifiers(

2039 scroll.keys().orElse(List.of()),

2040 () -> {

2041 move(scroll.x(), scroll.y());

2042 scroll(scroll.scrollY(), "4", "5");

2043 scroll(scroll.scrollX(), "6", "7");

2044 });

2045 return;

2046 }

2047 if (action.isDrag()) {

2048 var drag = action.asDrag();

2049 if (drag.path().size() < 2) {

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

2051 }

2052 withModifiers(

2053 drag.keys().orElse(List.of()),

2054 () -> {

2055 var first = drag.path().get(0);

2056 move(first.x(), first.y());

2057 run("xdotool", "mousedown", "1");

2058 try {

2059 for (var point : drag.path()) move(point.x(), point.y());

2060 } finally {

2061 run("xdotool", "mouseup", "1");

2062 }

2063 });

2064 return;

2065 }

2066 throw new IllegalArgumentException("Unsupported computer action: " + action);

2067 }

2068}

2069 

2070var container =

2071 new IsolatedContainer(

2072 isolatedContainerName(System.getenv("OPENAI_EXAMPLE_COMPUTER_CONTAINER")));

2073var response = client.responses().retrieve(System.getenv("OPENAI_RESPONSE_ID"));

2074while (true) {

2075 var computerCall =

2076 response.output().stream().flatMap(item -> item.computerCall().stream()).findFirst();

2077 if (computerCall.isEmpty()) break;

2078 

2079 for (ComputerAction action : computerCall.get().actions().orElse(List.of())) {

2080 container.execute(action);

2081 }

2082 

2083 byte[] screenshot = container.run("import", "-window", "root", "png:-");

2084 String encoded = Base64.getEncoder().encodeToString(screenshot);

2085 

2086 response =

2087 client

2088 .responses()

2089 .create(

2090 ResponseCreateParams.builder()

2091 .model("gpt-5.6")

2092 .previousResponseId(response.id())

2093 .putAdditionalBodyProperty(

2094 "tools", JsonValue.from(List.of(Map.of("type", "computer"))))

2095 .inputOfResponse(

2096 List.of(

2097 ResponseInputItem.ofComputerCallOutput(

2098 ResponseInputItem.ComputerCallOutput.builder()

2099 .callId(computerCall.get().callId())

2100 .output(

2101 ResponseComputerToolCallOutputScreenshot.builder()

2102 .imageUrl("data:image/png;base64," + encoded)

2103 .putAdditionalProperty(

2104 "detail", JsonValue.from("original"))

2105 .build())

2106 .build())))

2107 .build());

2108}

2109 

2110response.output().stream()

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

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

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

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

2115```

2116 

1823 2117 

1824When the response no longer contains a `computer_call`, read the remaining output items as the model's final answer or handoff.2118When the response no longer contains a `computer_call`, read the remaining output items as the model's final answer or handoff.

1825 2119 


2629}2923}

2630```2924```

2631 2925 

2926```java

2927import com.openai.client.OpenAIClient;

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

2929import com.openai.core.JsonValue;

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

2931import java.util.List;

2932import java.util.Map;

2933 

2934ResponseCreateParams params =

2935 ResponseCreateParams.builder()

2936 .model("computer-use-preview")

2937 .input("Check whether the Filters panel is open.")

2938 .truncation(ResponseCreateParams.Truncation.AUTO)

2939 .putAdditionalBodyProperty(

2940 "tools",

2941 JsonValue.from(

2942 List.of(

2943 Map.of(

2944 "type",

2945 "computer_use_preview",

2946 "display_width",

2947 1024,

2948 "display_height",

2949 768,

2950 "environment",

2951 "browser"))))

2952 .build();

2953 

2954client.responses().create(params).output().forEach(System.out::println);

2955```

2956 

2632```ruby2957```ruby

2633require "openai"2958require "openai"

2634 2959 

Details

124}124}

125```125```

126 126 

127```java

128import com.openai.client.OpenAIClient;

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

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

131import com.openai.models.responses.Tool;

132 

133ResponseCreateParams params =

134 ResponseCreateParams.builder()

135 .model("gpt-5.6")

136 .input("Roll 2d4+1")

137 .addTool(

138 Tool.Mcp.builder()

139 .serverLabel("dmcp")

140 .serverDescription(

141 "A Dungeons and Dragons MCP server to assist with dice rolling.")

142 .serverUrl("https://dmcp-server.deno.dev/mcp")

143 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

144 .build())

145 .build();

146 

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

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

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

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

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

152```

153 

127```csharp154```csharp

128using OpenAI.Responses;155using OpenAI.Responses;

129#pragma warning disable OPENAI001156#pragma warning disable OPENAI001


285}312}

286```313```

287 314 

315```java

316import com.openai.client.OpenAIClient;

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

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

319import com.openai.models.responses.Tool;

320 

321String oauthAccessToken = "<oauth access token>";

322 

323ResponseCreateParams params =

324 ResponseCreateParams.builder()

325 .model("gpt-5.6")

326 .input("Summarize the Q2 earnings report.")

327 .addTool(

328 Tool.Mcp.builder()

329 .serverLabel("Dropbox")

330 .connectorId(Tool.Mcp.ConnectorId.of("connector_dropbox"))

331 .authorization(oauthAccessToken)

332 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

333 .build())

334 .build();

335 

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

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

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

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

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

341```

342 

288```csharp343```csharp

289using OpenAI.Responses;344using OpenAI.Responses;

290#pragma warning disable OPENAI001345#pragma warning disable OPENAI001


525}580}

526```581```

527 582 

583```java

584import com.openai.client.OpenAIClient;

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

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

587import com.openai.models.responses.Tool;

588import java.util.List;

589 

590ResponseCreateParams params =

591 ResponseCreateParams.builder()

592 .model("gpt-5.6")

593 .input("Roll 2d4+1")

594 .addTool(

595 Tool.Mcp.builder()

596 .serverLabel("dmcp")

597 .serverDescription(

598 "A Dungeons and Dragons MCP server to assist with dice rolling.")

599 .serverUrl("https://dmcp-server.deno.dev/mcp")

600 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

601 .allowedToolsOfMcp(List.of("roll"))

602 .build())

603 .build();

604 

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

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

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

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

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

610```

611 

528```csharp612```csharp

529using OpenAI.Responses;613using OpenAI.Responses;

530#pragma warning disable OPENAI001614#pragma warning disable OPENAI001


727}811}

728```812```

729 813 

814```java

815import com.openai.client.OpenAIClient;

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

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

818import com.openai.models.responses.ResponseInputItem;

819import com.openai.models.responses.Tool;

820import java.util.List;

821 

822String responseId = "resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa";

823 

824String approvalRequestId = "mcpr_682d498e3bd4819196a0ce1664f8e77b04ad1e533afccbfa";

825 

826ResponseCreateParams params =

827 ResponseCreateParams.builder()

828 .model("gpt-5.6")

829 .input(

830 ResponseCreateParams.Input.ofResponse(

831 List.of(

832 ResponseInputItem.ofMcpApprovalResponse(

833 ResponseInputItem.McpApprovalResponse.builder()

834 .approvalRequestId(approvalRequestId)

835 .approve(true)

836 .build()))))

837 .previousResponseId(responseId)

838 .addTool(

839 Tool.Mcp.builder()

840 .serverLabel("dmcp")

841 .serverDescription("A Dungeons and Dragons MCP server.")

842 .serverUrl("https://dmcp-server.deno.dev/mcp")

843 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.ALWAYS)

844 .build())

845 .build();

846 

847client.responses().create(params).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```

853 

730```csharp854```csharp

731using OpenAI.Responses;855using OpenAI.Responses;

732#pragma warning disable OPENAI001856#pragma warning disable OPENAI001


897}1021}

898```1022```

899 1023 

1024```java

1025import com.openai.client.OpenAIClient;

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

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

1028import com.openai.models.responses.Tool;

1029 

1030ResponseCreateParams params =

1031 ResponseCreateParams.builder()

1032 .model("gpt-5.6")

1033 .input("What transport protocols does the 2025-03-26 version of the MCP spec support?")

1034 .addTool(

1035 Tool.Mcp.builder()

1036 .serverLabel("deepwiki")

1037 .serverUrl("https://mcp.deepwiki.com/mcp")

1038 .requireApproval(

1039 Tool.Mcp.RequireApproval.McpToolApprovalFilter.builder()

1040 .never(

1041 Tool.Mcp.RequireApproval.McpToolApprovalFilter.Never.builder()

1042 .addToolName("ask_question")

1043 .addToolName("read_wiki_structure")

1044 .build())

1045 .build())

1046 .build())

1047 .build();

1048 

1049client.responses().create(params).output().stream()

1050 .flatMap(item -> item.message().stream())

1051 .flatMap(message -> message.content().stream())

1052 .flatMap(content -> content.outputText().stream())

1053 .forEach(text -> System.out.println(text.text()));

1054```

1055 

900```csharp1056```csharp

901using OpenAI.Responses;1057using OpenAI.Responses;

902#pragma warning disable OPENAI0011058#pragma warning disable OPENAI001


1054}1210}

1055```1211```

1056 1212 

1213```java

1214import com.openai.client.OpenAIClient;

1215import com.openai.client.okhttp.OpenAIOkHttpClient;

1216import com.openai.models.responses.ResponseCreateParams;

1217import com.openai.models.responses.Tool;

1218 

1219String stripeAccessToken = System.getenv("STRIPE_OAUTH_ACCESS_TOKEN");

1220 

1221ResponseCreateParams params =

1222 ResponseCreateParams.builder()

1223 .model("gpt-5.6")

1224 .input("Create a payment link for $20.")

1225 .addTool(

1226 Tool.Mcp.builder()

1227 .serverLabel("stripe")

1228 .serverUrl("https://mcp.stripe.com")

1229 .authorization(stripeAccessToken)

1230 .build())

1231 .build();

1232 

1233client.responses().create(params).output().stream()

1234 .flatMap(item -> item.message().stream())

1235 .flatMap(message -> message.content().stream())

1236 .flatMap(content -> content.outputText().stream())

1237 .forEach(text -> System.out.println(text.text()));

1238```

1239 

1057```csharp1240```csharp

1058using OpenAI.Responses;1241using OpenAI.Responses;

1059#pragma warning disable OPENAI0011242#pragma warning disable OPENAI001


1232}1415}

1233```1416```

1234 1417 

1418```java

1419import com.openai.client.OpenAIClient;

1420import com.openai.client.okhttp.OpenAIOkHttpClient;

1421import com.openai.models.responses.ResponseCreateParams;

1422import com.openai.models.responses.Tool;

1423 

1424String oauthAccessToken = "<oauth access token>";

1425 

1426ResponseCreateParams params =

1427 ResponseCreateParams.builder()

1428 .model("gpt-5.6")

1429 .input("What's on my Google Calendar for today?")

1430 .addTool(

1431 Tool.Mcp.builder()

1432 .serverLabel("google_calendar")

1433 .connectorId(Tool.Mcp.ConnectorId.of("connector_googlecalendar"))

1434 .authorization(oauthAccessToken)

1435 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

1436 .build())

1437 .build();

1438 

1439client.responses().create(params).output().stream()

1440 .flatMap(item -> item.message().stream())

1441 .flatMap(message -> message.content().stream())

1442 .flatMap(content -> content.outputText().stream())

1443 .forEach(text -> System.out.println(text.text()));

1444```

1445 

1235```csharp1446```csharp

1236using OpenAI.Responses;1447using OpenAI.Responses;

1237#pragma warning disable OPENAI0011448#pragma warning disable OPENAI001

Details

108}108}

109```109```

110 110 

111```java

112import com.openai.client.OpenAIClient;

113import com.openai.client.okhttp.OpenAIOkHttpClient;

114import com.openai.models.responses.ResponseCreateParams;

115import com.openai.models.responses.Tool;

116import java.nio.file.Files;

117import java.nio.file.Path;

118import java.util.Base64;

119 

120ResponseCreateParams params =

121 ResponseCreateParams.builder()

122 .model("gpt-5.6")

123 .input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

124 .addTool(Tool.ImageGeneration.builder().build())

125 .build();

126 

127var image =

128 client.responses().create(params).output().stream()

129 .flatMap(item -> item.imageGenerationCall().stream())

130 .findFirst()

131 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

132String encoded =

133 image.result().orElseThrow(() -> new IllegalStateException("No image returned"));

134Files.write(Path.of("otter.png"), Base64.getDecoder().decode(encoded));

135```

136 

111```ruby137```ruby

112require "base64"138require "base64"

113require "openai"139require "openai"


143- Quality: Rendering quality, for example, low, medium, or high169- Quality: Rendering quality, for example, low, medium, or high

144- Format: File output format170- Format: File output format

145- Compression: Compression level (0-100%) for JPEG and WebP formats171- Compression: Compression level (0-100%) for JPEG and WebP formats

146- Background: Transparent or opaque172- Background: Transparent, opaque, or automatic

147- Action: Whether the request should automatically choose, generate, or edit an image173- Action: Whether the request should automatically choose, generate, or edit an image

148 174 

149`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.175`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.

150 176 

151`gpt-image-2` supports flexible `size` values that meet its [resolution constraints](https://developers.openai.com/api/docs/guides/image-generation#size-and-quality-options). It doesn't currently support transparent backgrounds, so requests with `background: "transparent"` fail.177`gpt-image-2` supports flexible `size` values that meet its [resolution constraints](https://developers.openai.com/api/docs/guides/image-generation#size-and-quality-options). Transparent backgrounds are available in preview; set `background: "transparent"` to request one. Use `png` (the default) or `webp`; `jpeg` isn't supported with transparent backgrounds.

152 178 

153For more details on available options, refer to the [image generation guide](https://developers.openai.com/api/docs/guides/image-generation#customize-image-output).179For more details on available options, refer to the [image generation guide](https://developers.openai.com/api/docs/guides/image-generation#customize-image-output).

154 180 


334}360}

335```361```

336 362 

363```java

364import com.openai.client.OpenAIClient;

365import com.openai.client.okhttp.OpenAIOkHttpClient;

366import com.openai.models.responses.ResponseCreateParams;

367import com.openai.models.responses.Tool;

368import java.nio.file.Files;

369import java.nio.file.Path;

370import java.util.Base64;

371 

372var first =

373 client

374 .responses()

375 .create(

376 ResponseCreateParams.builder()

377 .model("gpt-5.6")

378 .input(

379 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

380 .addTool(Tool.ImageGeneration.builder().build())

381 .build());

382var firstImage =

383 first.output().stream()

384 .flatMap(item -> item.imageGenerationCall().stream())

385 .findFirst()

386 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

387Files.write(

388 Path.of("cat_and_otter.png"),

389 Base64.getDecoder()

390 .decode(

391 firstImage

392 .result()

393 .orElseThrow(() -> new IllegalStateException("No image returned"))));

394 

395var second =

396 client

397 .responses()

398 .create(

399 ResponseCreateParams.builder()

400 .model("gpt-5.6")

401 .input("Now make it look realistic.")

402 .previousResponseId(first.id())

403 .addTool(Tool.ImageGeneration.builder().build())

404 .build());

405var secondImage =

406 second.output().stream()

407 .flatMap(item -> item.imageGenerationCall().stream())

408 .findFirst()

409 .orElseThrow(

410 () -> new IllegalStateException("No follow-up image generation call returned"));

411Files.write(

412 Path.of("cat_and_otter_realistic.png"),

413 Base64.getDecoder()

414 .decode(

415 secondImage

416 .result()

417 .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));

418```

419 

337```ruby420```ruby

338require "base64"421require "base64"

339require "openai"422require "openai"


564}647}

565```648```

566 649 

650```java

651import com.openai.client.OpenAIClient;

652import com.openai.client.okhttp.OpenAIOkHttpClient;

653import com.openai.core.JsonValue;

654import com.openai.models.responses.ResponseCreateParams;

655import com.openai.models.responses.ResponseInputItem;

656import com.openai.models.responses.Tool;

657import java.nio.file.Files;

658import java.nio.file.Path;

659import java.util.Base64;

660import java.util.List;

661import java.util.Map;

662 

663var first =

664 client

665 .responses()

666 .create(

667 ResponseCreateParams.builder()

668 .model("gpt-5.6")

669 .input(

670 "Generate an image of a gray tabby cat hugging an otter with an orange scarf.")

671 .addTool(Tool.ImageGeneration.builder().build())

672 .build());

673var firstImage =

674 first.output().stream()

675 .flatMap(item -> item.imageGenerationCall().stream())

676 .findFirst()

677 .orElseThrow(() -> new IllegalStateException("No image generation call returned"));

678Files.write(

679 Path.of("cat_and_otter.png"),

680 Base64.getDecoder()

681 .decode(

682 firstImage

683 .result()

684 .orElseThrow(() -> new IllegalStateException("No image returned"))));

685 

686var second =

687 client

688 .responses()

689 .create(

690 ResponseCreateParams.builder()

691 .model("gpt-5.6")

692 .inputOfResponse(

693 List.of(

694 ResponseInputItem.ofMessage(

695 ResponseInputItem.Message.builder()

696 .role(ResponseInputItem.Message.Role.USER)

697 .addInputTextContent("Now make it look realistic.")

698 .build()),

699 JsonValue.from(

700 Map.of("type", "image_generation_call", "id", firstImage.id()))

701 .convert(ResponseInputItem.class)))

702 .addTool(Tool.ImageGeneration.builder().build())

703 .build());

704var secondImage =

705 second.output().stream()

706 .flatMap(item -> item.imageGenerationCall().stream())

707 .findFirst()

708 .orElseThrow(

709 () -> new IllegalStateException("No follow-up image generation call returned"));

710Files.write(

711 Path.of("cat_and_otter_realistic.png"),

712 Base64.getDecoder()

713 .decode(

714 secondImage

715 .result()

716 .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));

717```

718 

567```ruby719```ruby

568require "base64"720require "base64"

569require "openai"721require "openai"


739}891}

740```892```

741 893 

894```java

895import com.openai.client.OpenAIClient;

896import com.openai.client.okhttp.OpenAIOkHttpClient;

897import com.openai.core.http.StreamResponse;

898import com.openai.models.responses.ResponseCreateParams;

899import com.openai.models.responses.ResponseStreamEvent;

900import com.openai.models.responses.Tool;

901import java.io.IOException;

902import java.nio.file.Files;

903import java.nio.file.Path;

904import java.util.Base64;

905 

906ResponseCreateParams params =

907 ResponseCreateParams.builder()

908 .model("gpt-5.6")

909 .input("Generate an image of a river made of white owl feathers.")

910 .addTool(Tool.ImageGeneration.builder().partialImages(2).build())

911 .build();

912 

913try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

914 var events = stream.stream().iterator();

915 while (events.hasNext()) {

916 ResponseStreamEvent event = events.next();

917 if (event.imageGenerationCallPartialImage().isPresent()) {

918 var partial = event.imageGenerationCallPartialImage().orElseThrow();

919 Files.write(

920 Path.of("river-partial-" + partial.partialImageIndex() + ".png"),

921 Base64.getDecoder().decode(partial.partialImageB64()));

922 }

923 if (event.completed().isPresent()) {

924 var image =

925 event.completed().orElseThrow().response().output().stream()

926 .flatMap(item -> item.imageGenerationCall().stream())

927 .findFirst()

928 .orElseThrow(() -> new IllegalStateException("No generated image returned"));

929 Files.write(

930 Path.of("river-final.png"),

931 Base64.getDecoder()

932 .decode(

933 image

934 .result()

935 .orElseThrow(

936 () -> new IllegalStateException("No final image returned"))));

937 }

938 }

939}

940```

941 

742```ruby942```ruby

743require "base64"943require "base64"

744require "openai"944require "openai"

Details

125}125}

126```126```

127 127 

128```java

129import com.openai.client.OpenAIClient;

130import com.openai.client.okhttp.OpenAIOkHttpClient;

131import com.openai.models.responses.ContainerAuto;

132import com.openai.models.responses.FunctionShellTool;

133import com.openai.models.responses.ResponseCreateParams;

134 

135ResponseCreateParams params =

136 ResponseCreateParams.builder()

137 .model("gpt-5.6")

138 .input("Run ls -lah /mnt/data, then show the Python and Node.js versions.")

139 .addTool(

140 FunctionShellTool.builder().environment(ContainerAuto.builder().build()).build())

141 .build();

142 

143client.responses().create(params).output().stream()

144 .flatMap(item -> item.message().stream())

145 .flatMap(message -> message.content().stream())

146 .flatMap(content -> content.outputText().stream())

147 .forEach(text -> System.out.println(text.text()));

148```

149 

128```ruby150```ruby

129require "openai"151require "openai"

130 152 


231}253}

232```254```

233 255 

256```java

257import com.openai.client.OpenAIClient;

258import com.openai.client.okhttp.OpenAIOkHttpClient;

259import com.openai.models.containers.ContainerCreateParams;

260 

261var container =

262 client

263 .containers()

264 .create(

265 ContainerCreateParams.builder()

266 .name("analysis")

267 .expiresAfter(

268 ContainerCreateParams.ExpiresAfter.builder()

269 .anchor(ContainerCreateParams.ExpiresAfter.Anchor.LAST_ACTIVE_AT)

270 .minutes(20)

271 .build())

272 .build());

273 

274System.out.println(container.id());

275```

276 

234```ruby277```ruby

235require "openai"278require "openai"

236 279 


331}374}

332```375```

333 376 

377```java

378import com.openai.client.OpenAIClient;

379import com.openai.client.okhttp.OpenAIOkHttpClient;

380import com.openai.models.responses.FunctionShellTool;

381import com.openai.models.responses.ResponseCreateParams;

382 

383String containerId = "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe";

384 

385ResponseCreateParams params =

386 ResponseCreateParams.builder()

387 .model("gpt-5.6")

388 .input("List files in the container and show disk usage.")

389 .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())

390 .build();

391 

392client.responses().create(params).output().stream()

393 .flatMap(item -> item.message().stream())

394 .flatMap(message -> message.content().stream())

395 .flatMap(content -> content.outputText().stream())

396 .forEach(text -> System.out.println(text.text()));

397```

398 

334```ruby399```ruby

335require "openai"400require "openai"

336 401 


444}509}

445```510```

446 511 

512```java

513import com.openai.client.OpenAIClient;

514import com.openai.client.okhttp.OpenAIOkHttpClient;

515import com.openai.models.containers.ContainerCreateParams;

516import com.openai.models.responses.SkillReference;

517 

518String skillId = "skill_4db6f1a2c9e73508b41f9da06e2c7b5f";

519 

520var container =

521 client

522 .containers()

523 .create(

524 ContainerCreateParams.builder()

525 .name("skill-container")

526 .addSkill(SkillReference.builder().skillId(skillId).build())

527 .addSkill(

528 SkillReference.builder()

529 .skillId("openai-spreadsheets")

530 .version("latest")

531 .build())

532 .build());

533 

534System.out.println(container.id());

535```

536 

447```ruby537```ruby

448require "openai"538require "openai"

449 539 


603}693}

604```694```

605 695 

696```java

697import com.openai.client.OpenAIClient;

698import com.openai.client.okhttp.OpenAIOkHttpClient;

699import com.openai.models.responses.ContainerAuto;

700import com.openai.models.responses.ContainerNetworkPolicyAllowlist;

701import com.openai.models.responses.FunctionShellTool;

702import com.openai.models.responses.ResponseCreateParams;

703import com.openai.models.responses.ToolChoiceOptions;

704 

705ResponseCreateParams params =

706 ResponseCreateParams.builder()

707 .model("gpt-5.6")

708 .input("Fetch release pages and write /mnt/data/release_digest.md.")

709 .toolChoice(ToolChoiceOptions.REQUIRED)

710 .addTool(

711 FunctionShellTool.builder()

712 .environment(

713 ContainerAuto.builder()

714 .networkPolicy(

715 ContainerNetworkPolicyAllowlist.builder()

716 .addAllowedDomain("pypi.org")

717 .addAllowedDomain("files.pythonhosted.org")

718 .addAllowedDomain("github.com")

719 .build())

720 .build())

721 .build())

722 .build();

723 

724client.responses().create(params).output().stream()

725 .flatMap(item -> item.message().stream())

726 .flatMap(message -> message.content().stream())

727 .flatMap(content -> content.outputText().stream())

728 .forEach(text -> System.out.println(text.text()));

729```

730 

606```ruby731```ruby

607require "openai"732require "openai"

608 733 


888}1013}

889```1014```

890 1015 

1016```java

1017import com.openai.client.OpenAIClient;

1018import com.openai.client.okhttp.OpenAIOkHttpClient;

1019 

1020String containerId = "container_id";

1021 

1022client.containers().delete(containerId);

1023 

1024System.out.println("Container deleted.");

1025```

1026 

891```ruby1027```ruby

892require "openai"1028require "openai"

893 1029 


1067}1203}

1068```1204```

1069 1205 

1206```java

1207import com.openai.client.OpenAIClient;

1208import com.openai.client.okhttp.OpenAIOkHttpClient;

1209import com.openai.models.responses.ContainerAuto;

1210import com.openai.models.responses.ContainerNetworkPolicyAllowlist;

1211import com.openai.models.responses.ContainerNetworkPolicyDomainSecret;

1212import com.openai.models.responses.FunctionShellTool;

1213import com.openai.models.responses.ResponseCreateParams;

1214import com.openai.models.responses.ToolChoiceOptions;

1215 

1216ResponseCreateParams params =

1217 ResponseCreateParams.builder()

1218 .model("gpt-5.6")

1219 .input(

1220 "Use curl to call https://httpbin.org/status/204 with an "

1221 + "Authorization: Bearer $API_KEY header. Print only the HTTP status code; "

1222 + "never print request headers or secret values.")

1223 .toolChoice(ToolChoiceOptions.REQUIRED)

1224 .addTool(

1225 FunctionShellTool.builder()

1226 .environment(

1227 ContainerAuto.builder()

1228 .networkPolicy(

1229 ContainerNetworkPolicyAllowlist.builder()

1230 .addAllowedDomain("httpbin.org")

1231 .addDomainSecret(

1232 ContainerNetworkPolicyDomainSecret.builder()

1233 .domain("httpbin.org")

1234 .name("API_KEY")

1235 .value(System.getenv("OPENAI_EXAMPLE_DOMAIN_SECRET"))

1236 .build())

1237 .build())

1238 .build())

1239 .build())

1240 .build();

1241 

1242client.responses().create(params).output().stream()

1243 .flatMap(item -> item.message().stream())

1244 .flatMap(message -> message.content().stream())

1245 .flatMap(content -> content.outputText().stream())

1246 .forEach(text -> System.out.println(text.text()));

1247```

1248 

1070```ruby1249```ruby

1071require "openai"1250require "openai"

1072 1251 


1199}1378}

1200```1379```

1201 1380 

1381```java

1382import com.openai.client.OpenAIClient;

1383import com.openai.client.okhttp.OpenAIOkHttpClient;

1384import com.openai.models.responses.FunctionShellTool;

1385import com.openai.models.responses.ResponseCreateParams;

1386 

1387String responseId = "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47";

1388 

1389String containerId = "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041";

1390 

1391ResponseCreateParams params =

1392 ResponseCreateParams.builder()

1393 .model("gpt-5.6")

1394 .input("Read /mnt/data/top5.csv and report the top candidate.")

1395 .previousResponseId(responseId)

1396 .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())

1397 .build();

1398 

1399client.responses().create(params).output().stream()

1400 .flatMap(item -> item.message().stream())

1401 .flatMap(message -> message.content().stream())

1402 .flatMap(content -> content.outputText().stream())

1403 .forEach(text -> System.out.println(text.text()));

1404```

1405 

1202```ruby1406```ruby

1203require "openai"1407require "openai"

1204 1408 


1319}1523}

1320```1524```

1321 1525 

1526```java

1527import com.openai.client.OpenAIClient;

1528import com.openai.client.okhttp.OpenAIOkHttpClient;

1529import com.openai.core.JsonValue;

1530import com.openai.models.responses.ResponseCreateParams;

1531import java.util.List;

1532import java.util.Map;

1533 

1534ResponseCreateParams params =

1535 ResponseCreateParams.builder()

1536 .model("gpt-5.6")

1537 .input("Find the largest PDF in ~/Documents.")

1538 .instructions("The local shell environment is macOS.")

1539 .putAdditionalBodyProperty(

1540 "tools",

1541 JsonValue.from(

1542 List.of(Map.of("type", "shell", "environment", Map.of("type", "local")))))

1543 .build();

1544 

1545client.responses().create(params).output().stream()

1546 .flatMap(item -> item.shellCall().stream())

1547 .flatMap(call -> call.action().commands().stream())

1548 .forEach(System.out::println);

1549```

1550 

1322```ruby1551```ruby

1323require "openai"1552require "openai"

1324 1553 

Details

169}169}

170```170```

171 171 

172```java

173import com.openai.client.OpenAIClient;

174import com.openai.client.okhttp.OpenAIOkHttpClient;

175import com.openai.core.JsonValue;

176import com.openai.models.responses.ResponseCreateParams;

177import java.util.List;

178import java.util.Map;

179 

180String skillId = "<skill_id>";

181 

182ResponseCreateParams params =

183 ResponseCreateParams.builder()

184 .model("gpt-5.6")

185 .input(

186 "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.")

187 .putAdditionalBodyProperty(

188 "tools",

189 JsonValue.from(

190 List.of(

191 Map.of(

192 "type",

193 "shell",

194 "environment",

195 Map.of(

196 "type",

197 "container_auto",

198 "skills",

199 List.of(

200 Map.of("type", "skill_reference", "skill_id", skillId),

201 Map.of(

202 "type", "skill_reference",

203 "skill_id", skillId,

204 "version", "2")))))))

205 .build();

206 

207client.responses().create(params).output().stream()

208 .flatMap(item -> item.message().stream())

209 .flatMap(message -> message.content().stream())

210 .flatMap(content -> content.outputText().stream())

211 .forEach(text -> System.out.println(text.text()));

212```

213 

172```ruby214```ruby

173require "openai"215require "openai"

174 216 


319}361}

320```362```

321 363 

364```java

365import com.openai.client.OpenAIClient;

366import com.openai.client.okhttp.OpenAIOkHttpClient;

367import com.openai.core.JsonValue;

368import com.openai.models.responses.ResponseCreateParams;

369import java.util.List;

370import java.util.Map;

371 

372String skillPath = "<path-to-skill-folder>";

373 

374ResponseCreateParams params =

375 ResponseCreateParams.builder()

376 .model("gpt-5.6")

377 .input("Use the csv-insights skill to summarize today's CSV reports.")

378 .putAdditionalBodyProperty(

379 "tools",

380 JsonValue.from(

381 List.of(

382 Map.of(

383 "type",

384 "shell",

385 "environment",

386 Map.of(

387 "type",

388 "local",

389 "skills",

390 List.of(

391 Map.of(

392 "name", "csv-insights",

393 "description",

394 "Summarize CSV files and produce a Markdown report.",

395 "path", skillPath)))))))

396 .build();

397 

398client.responses().create(params).output().stream()

399 .flatMap(item -> item.message().stream())

400 .flatMap(message -> message.content().stream())

401 .flatMap(content -> content.outputText().stream())

402 .forEach(text -> System.out.println(text.text()));

403```

404 

322```ruby405```ruby

323require "openai"406require "openai"

324 407 

Details

103}103}

104```104```

105 105 

106```java

107import com.openai.client.OpenAIClient;

108import com.openai.client.okhttp.OpenAIOkHttpClient;

109import com.openai.models.videos.VideoCreateParams;

110 

111var video =

112 client

113 .videos()

114 .create(

115 VideoCreateParams.builder()

116 .model("sora-2")

117 .prompt("A paper airplane flying over a forest")

118 .build());

119 

120System.out.println(video.id());

121```

122 

106```ruby123```ruby

107require "openai"124require "openai"

108 125 


259}276}

260```277```

261 278 

279```java

280import com.openai.client.OpenAIClient;

281import com.openai.client.okhttp.OpenAIOkHttpClient;

282import com.openai.models.videos.Video;

283import com.openai.models.videos.VideoCreateParams;

284 

285var video =

286 client

287 .videos()

288 .create(

289 VideoCreateParams.builder()

290 .model("sora-2")

291 .prompt("A paper airplane flying over a forest")

292 .build());

293 

294while (video.status().equals(Video.Status.QUEUED)

295 || video.status().equals(Video.Status.IN_PROGRESS)) {

296 Thread.sleep(1000);

297 video = client.videos().retrieve(video.id());

298}

299if (!video.status().equals(Video.Status.COMPLETED)) {

300 throw new IllegalStateException("Video generation failed: " + video.status());

301}

302System.out.println("Video completed: " + video.id());

303```

304 

262```ruby305```ruby

263require "openai"306require "openai"

264 307 


466}509}

467```510```

468 511 

512```java

513import com.openai.client.OpenAIClient;

514import com.openai.client.okhttp.OpenAIOkHttpClient;

515import com.openai.models.videos.Video;

516import com.openai.models.videos.VideoCreateParams;

517import java.nio.file.Files;

518import java.nio.file.Path;

519import java.nio.file.StandardCopyOption;

520 

521var video =

522 client

523 .videos()

524 .create(

525 VideoCreateParams.builder()

526 .model("sora-2")

527 .prompt("A video of the words 'Thank you' in sparkling letters")

528 .build());

529 

530while (video.status().equals(Video.Status.QUEUED)

531 || video.status().equals(Video.Status.IN_PROGRESS)) {

532 Thread.sleep(1000);

533 video = client.videos().retrieve(video.id());

534}

535if (!video.status().equals(Video.Status.COMPLETED)) {

536 throw new IllegalStateException("Video generation failed: " + video.status());

537}

538try (var content = client.videos().downloadContent(video.id())) {

539 Files.copy(content.body(), Path.of("video.mp4"), StandardCopyOption.REPLACE_EXISTING);

540}

541System.out.println("Wrote video.mp4");

542```

543 

469```ruby544```ruby

470require "openai"545require "openai"

471 546 

Details

160}160}

161```161```

162 162 

163```java

164import com.openai.client.OpenAIClient;

165import com.openai.client.okhttp.OpenAIOkHttpClient;

166import com.openai.models.responses.ResponseCreateParams;

167 

168ResponseCreateParams params =

169 ResponseCreateParams.builder()

170 .model("gpt-5.6")

171 .input("Write a detailed market analysis.")

172 .background(true)

173 .build();

174 

175var response = client.responses().create(params);

176System.out.println(response.status().orElseThrow());

177```

178 

163```ruby179```ruby

164require "openai"180require "openai"

165 181 

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5The Responses API supports a WebSocket mode for long-running, tool-call-heavy workflows. Beyond lowering latency, `stream_id` lets one persistent connection to `/v1/responses` run parallel conversations and fork an existing conversation onto a new stream. Continue each turn by sending only new input items plus `previous_response_id`.5The Responses API supports a WebSocket mode for long-running, tool-call-heavy workflows. Beyond lowering latency, `stream_id` enables WebSocket multiplexing: one persistent connection to `/v1/responses` can run parallel conversations and fork an existing conversation onto a new stream. Continue each turn by sending only new input items plus `previous_response_id`.

6 

7This pattern is WebSocket multiplexing: multiple logical response lanes over one persistent connection.

8 6 

9WebSocket mode is compatible with both Zero Data Retention (ZDR) and `store=false`.7WebSocket mode is compatible with both Zero Data Retention (ZDR) and `store=false`.

10 8 


14 12 

15Because the connection stays open and each turn sends only incremental input, WebSocket mode reduces per-turn continuation overhead and improves end-to-end latency across long chains. For rollouts with 20+ tool calls, we have seen up to roughly 40% faster end-to-end execution.13Because the connection stays open and each turn sends only incremental input, WebSocket mode reduces per-turn continuation overhead and improves end-to-end latency across long chains. For rollouts with 20+ tool calls, we have seen up to roughly 40% faster end-to-end execution.

16 14 

17## What `stream_id` unlocks15## Connect and create responses

16 

17In 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.

18 

19```python

20from websocket import create_connection

21import json

22import os

23 

24ws = create_connection(

25 "wss://api.openai.com/v1/responses",

26 header=[

27 f"Authorization: Bearer {os.environ['OPENAI_API_KEY']}",

28 ],

29)

30 

31ws.send(

32 json.dumps(

33 {

34 "type": "response.create",

35 "stream_id": "main",

36 "model": "gpt-5.6",

37 "store": False,

38 "input": [

39 {

40 "type": "message",

41 "role": "user",

42 "content": [{"type": "input_text", "text": "Find fizz_buzz()"}],

43 }

44 ],

45 "tools": [],

46 }

47 )

48)

49```

50 

51 

52Clients can optionally warm up request state by sending `response.create` with `generate: false`. This is useful when you already know the tools, instructions, and/or custom messages you plan to send with an upcoming turn. `generate: false` does not return a model output, but prepares request state so the next generated turn can start faster. The warmup request returns a response ID that you can chain from with `previous_response_id`, including on later turns in a response chain. The next section explains how to continue a session using `previous_response_id` and incremental inputs.

53 

54## Continue with incremental inputs

55 

56To continue a run, send another `response.create` with:

57 

58- `previous_response_id` set to the prior response ID.

59- `input` containing only new items (for example, tool outputs and the next user message).

60 

61```python

62ws.send(

63 json.dumps(

64 {

65 "type": "response.create",

66 "stream_id": "main",

67 "model": "gpt-5.6",

68 "store": False,

69 "previous_response_id": "resp_123",

70 "input": [

71 {

72 "type": "function_call_output",

73 "call_id": "call_123",

74 "output": "tool result",

75 },

76 {

77 "type": "message",

78 "role": "user",

79 "content": [{"type": "input_text", "text": "Now optimize it."}],

80 },

81 ],

82 "tools": [],

83 }

84 )

85)

86```

87 

88 

89## How continuation works

90 

91WebSocket mode uses the same `previous_response_id` chaining semantics as HTTP mode, but it adds a lower-latency continuation path on the active socket.

92 

93On an active WebSocket connection, the service keeps recent previous-response state in a connection-local in-memory cache. When you use `stream_id`, each lane keeps its latest cached response, so continuing from the latest response in that lane is fast because the service can reuse connection-local state. Because the service retains previous-response state only in memory and does not write it to disk, you can use WebSocket mode in a way that is compatible with `store=false` and Zero Data Retention (ZDR).

94 

95If a `previous_response_id` is not in the in-memory cache, behavior depends on whether you store responses:

96 

97- With `store=true`, the service may hydrate older response IDs from persisted state when available. Continuation can still work, but it loses the in-memory latency benefit.

98- With `store=false` (including ZDR), there is no persisted fallback. If the ID is uncached, the request returns `previous_response_not_found`.

99 

100If a same-lane continuation returns a `4xx` or `5xx`, the service evicts the referenced `previous_response_id` from the connection-local cache. A cross-lane fork that returns an error preserves the shared parent so the source lane can continue.

101 

102## Compaction and creating new responses

103 

104If you are using compaction, there are two different continuation patterns:

105 

106### Server-side compaction (`context_management`)

107 

108When you enable server-side compaction (`context_management` with `compact_threshold`), compaction happens during normal `/responses` generation. In WebSocket mode, you continue the same way you normally do: send the next `response.create` with the latest `previous_response_id` and only new input items.

109 

110### Standalone `/responses/compact`

111 

112The standalone [`/responses/compact` endpoint](https://developers.openai.com/api/reference/resources/responses/methods/compact) returns a new compacted input window, not a response ID. After compaction, create a new response on your WebSocket connection using the compacted window as `input` (plus the next user/tool items).

113 

114Start a new chain by omitting `previous_response_id` or setting it to `null`. Pass the compacted output as-is; do not prune the returned window.

115 

116```python

117# Compact your current window (HTTP call)

118compacted = client.responses.compact(

119 model="gpt-5.6",

120 input=long_input_items_array,

121)

122 

123# Start a new response on the WebSocket using the compacted window

124ws.send(

125 json.dumps(

126 {

127 "type": "response.create",

128 "stream_id": "main",

129 "model": "gpt-5.6",

130 "store": False,

131 "input": [

132 *compacted.output,

133 {

134 "type": "message",

135 "role": "user",

136 "content": [{"type": "input_text", "text": "Continue from here."}],

137 },

138 ],

139 "tools": [],

140 }

141 )

142)

143```

144 

145 

146## Run conversations in parallel

147 

148You can maintain parallel conversations on the same connection using the `stream_id` parameter. Send independent `response.create` events back-to-back with different `stream_id` values. The server can run them concurrently on one connection. Their events can interleave, so keep one reader loop and route each event by `stream_id`.

18 149 

19A `stream_id` names an ordered lane on one WebSocket connection. Keep `stream_id` and `previous_response_id` separate:150A `stream_id` names an ordered lane on one WebSocket connection. Keep `stream_id` and `previous_response_id` separate:

20 151 


23 154 

24That separation unlocks two useful patterns.155That separation unlocks two useful patterns.

25 156 

26### Run conversations in parallel

27 

28Send independent `response.create` events back-to-back with different `stream_id` values. The server can run them concurrently on one connection. Their events can interleave, so keep one reader loop and route each event by `stream_id`.

29 

30```text157```text

31one WebSocket connection158one WebSocket connection

32├─ stream_id="planner" draft a deployment plan159├─ stream_id="planner" draft a deployment plan


35 162 

36Requests with the same `stream_id` stay first-in, first-out and do not overlap. Requests with different `stream_id` values can run concurrently.163Requests with the same `stream_id` stay first-in, first-out and do not overlap. Requests with different `stream_id` values can run concurrently.

37 164 

38#### Limits per connection165### Limits per connection

39 166 

40- A connection can have up to 16 active, in-flight responses across named and default lanes. The connection accepts more `response.create` events and queues them until an active response finishes.167- A connection can have up to 16 active, in-flight responses across named and default lanes. The connection accepts more `response.create` events and queues them until an active response finishes.

41- A connection accepts up to 32 distinct named `stream_id` values. The implicit default lane does not count toward this named-stream limit. Reuse an existing `stream_id` or open a new connection after reaching the limit.168- A connection accepts up to 32 distinct named `stream_id` values. The implicit default lane does not count toward this named-stream limit. Reuse an existing `stream_id` or open a new connection after reaching the limit.


161 288 

162If you omit `stream_id`, the request uses an implicit default lane, and its events do not include `stream_id`. The default lane otherwise follows the same ordering and concurrency rules as named streams. An empty string is not a valid `stream_id`; omit the field to select the default lane.289If you omit `stream_id`, the request uses an implicit default lane, and its events do not include `stream_id`. The default lane otherwise follows the same ordering and concurrency rules as named streams. An empty string is not a valid `stream_id`; omit the field to select the default lane.

163 290 

164## Connect and create responses

165 

166In 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.

167 

168```python

169from websocket import create_connection

170import json

171import os

172 

173ws = create_connection(

174 "wss://api.openai.com/v1/responses",

175 header=[

176 f"Authorization: Bearer {os.environ['OPENAI_API_KEY']}",

177 ],

178)

179 

180ws.send(

181 json.dumps(

182 {

183 "type": "response.create",

184 "stream_id": "main",

185 "model": "gpt-5.6",

186 "store": False,

187 "input": [

188 {

189 "type": "message",

190 "role": "user",

191 "content": [{"type": "input_text", "text": "Find fizz_buzz()"}],

192 }

193 ],

194 "tools": [],

195 }

196 )

197)

198```

199 

200 

201Clients can optionally warm up request state by sending `response.create` with `generate: false`. This is useful when you already know the tools, instructions, and/or custom messages you plan to send with an upcoming turn. `generate: false` does not return a model output, but prepares request state so the next generated turn can start faster. The warmup request returns a response ID that you can chain from with `previous_response_id`, including on later turns in a response chain. The next section explains how to continue a session using `previous_response_id` and incremental inputs.

202 

203## Continue with incremental inputs

204 

205To continue a run, send another `response.create` with:

206 

207- `previous_response_id` set to the prior response ID.

208- `input` containing only new items (for example, tool outputs and the next user message).

209 

210```python

211ws.send(

212 json.dumps(

213 {

214 "type": "response.create",

215 "stream_id": "main",

216 "model": "gpt-5.6",

217 "store": False,

218 "previous_response_id": "resp_123",

219 "input": [

220 {

221 "type": "function_call_output",

222 "call_id": "call_123",

223 "output": "tool result",

224 },

225 {

226 "type": "message",

227 "role": "user",

228 "content": [{"type": "input_text", "text": "Now optimize it."}],

229 },

230 ],

231 "tools": [],

232 }

233 )

234)

235```

236 

237 

238## How continuation works

239 

240WebSocket mode uses the same `previous_response_id` chaining semantics as HTTP mode, but it adds a lower-latency continuation path on the active socket.

241 

242On an active WebSocket connection, the service keeps recent previous-response state in a connection-local in-memory cache. When you use `stream_id`, each lane keeps its latest cached response, so continuing from the latest response in that lane is fast because the service can reuse connection-local state. Because the service retains previous-response state only in memory and does not write it to disk, you can use WebSocket mode in a way that is compatible with `store=false` and Zero Data Retention (ZDR).

243 

244If a `previous_response_id` is not in the in-memory cache, behavior depends on whether you store responses:

245 

246- With `store=true`, the service may hydrate older response IDs from persisted state when available. Continuation can still work, but it loses the in-memory latency benefit.

247- With `store=false` (including ZDR), there is no persisted fallback. If the ID is uncached, the request returns `previous_response_not_found`.

248 

249If a same-lane continuation returns a `4xx` or `5xx`, the service evicts the referenced `previous_response_id` from the connection-local cache. A cross-lane fork that returns an error preserves the shared parent so the source lane can continue.

250 

251## Compaction and creating new responses

252 

253If you are using compaction, there are two different continuation patterns:

254 

255### Server-side compaction (`context_management`)

256 

257When you enable server-side compaction (`context_management` with `compact_threshold`), compaction happens during normal `/responses` generation. In WebSocket mode, you continue the same way you normally do: send the next `response.create` with the latest `previous_response_id` and only new input items.

258 

259### Standalone `/responses/compact`

260 

261The standalone [`/responses/compact` endpoint](https://developers.openai.com/api/reference/resources/responses/methods/compact) returns a new compacted input window, not a response ID. After compaction, create a new response on your WebSocket connection using the compacted window as `input` (plus the next user/tool items).

262 

263Start a new chain by omitting `previous_response_id` or setting it to `null`. Pass the compacted output as-is; do not prune the returned window.

264 

265```python

266# Compact your current window (HTTP call)

267compacted = client.responses.compact(

268 model="gpt-5.6",

269 input=long_input_items_array,

270)

271 

272# Start a new response on the WebSocket using the compacted window

273ws.send(

274 json.dumps(

275 {

276 "type": "response.create",

277 "stream_id": "main",

278 "model": "gpt-5.6",

279 "store": False,

280 "input": [

281 *compacted.output,

282 {

283 "type": "message",

284 "role": "user",

285 "content": [{"type": "input_text", "text": "Continue from here."}],

286 },

287 ],

288 "tools": [],

289 }

290 )

291)

292```

293 

294 

295## Connection behavior and limits291## Connection behavior and limits

296 292 

297- Events within each response follow the existing Responses streaming event model. Events from different lanes can interleave.293- Events within each response follow the existing Responses streaming event model. Events from different lanes can interleave.


326}322}

327```323```

328 324 

325`invalid_stream_id`

326 

327```json

328{

329 "type": "error",

330 "status": 400,

331 "error": {

332 "type": "invalid_request_error",

333 "code": "invalid_stream_id",

334 "message": "The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",

335 "param": "stream_id"

336 }

337}

338```

339 

329`websocket_stream_limit_reached`340`websocket_stream_limit_reached`

330 341 

331```json342```json

Details

2 2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Workload identity federation lets trusted workloads exchange an externally issued identity token for a short-lived OpenAI access token. X.509 workload identity federation is also available in beta, allowing workloads to exchange a verified certificate identity. Use these guides to configure your external identity provider, create OpenAI service account mappings, and authenticate workloads without storing long-lived API keys.5Workload identity federation lets a trusted workload use an identity it already

6 6has instead of storing an OpenAI API key or ChatGPT credential. The workload

7For token exchange request and response details, authorization behavior, and current limitations, see the [workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation).7presents a short-lived token from your identity provider, and OpenAI exchanges

8it for a short-lived OpenAI access token.

9 

10OpenAI API workloads can also exchange a verified certificate identity through

11the X.509 workload identity federation beta.

12 

13You can use workload identity federation with the OpenAI API or Codex:

14 

15| | OpenAI API | Codex |

16| ---------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------ |

17| **OpenAI identity** | A service account in an API Platform project | A user or service account in a managed ChatGPT workspace |

18| **Where administrators set it up** | OpenAI Platform | OpenAI Admin Portal |

19| **How the workload connects** | An OpenAI SDK or the token exchange endpoint | Codex environment variables and an identity-token file |

20| **What the access token can use** | The APIs and permissions available to the mapped service account | The Codex access available to the mapped workspace principal |

21 

22Both paths use the same trust model, but their administration and runtime

23configuration differ. Start with the shared concepts and identity-provider

24guidance below, then follow the section for the product your workload uses.

25 

26- **OpenAI API:** Continue to [Use workload identity with the OpenAI

27 API](#use-workload-identity-with-the-openai-api).

28- **Codex:** Follow [Use workload identity with

29 Codex](https://developers.openai.com/codex/enterprise/workload-identity) for the complete Admin Portal and

30 runtime setup.

31 

32Administrators can also [manage Codex providers and rules with the Admin

33API](https://developers.openai.com/api/docs/guides/workload-identity-federation/admin-api). See the [Codex

34federation rule

35reference](https://developers.openai.com/api/docs/guides/workload-identity-federation/federation-rules) for

36rule and lifecycle behavior.

8 37 

9## How it works38## How it works

10 39 

11Workload identity federation has four parts:40An administrator configures three things before the workload connects:

41 

421. An **identity provider** tells OpenAI which external issuer to trust and how

43 to verify its signed tokens or certificate identities.

442. An **access rule** describes which token attributes OpenAI accepts and which

45 OpenAI identity the workload may act as. OpenAI API configuration calls this

46 a service account mapping. Codex configuration calls it a federation rule.

473. An **OpenAI principal** receives the resulting access. For the OpenAI API,

48 the principal is a Platform service account. For Codex, the principal is a

49 ChatGPT user or service account in a managed workspace.

50 

51At runtime:

12 52 

131. A **workload identity provider** describes the external identity. An OIDC provider stores the issuer, audience, and key source used to verify external subject tokens. An X.509 provider derives identity attributes from a client certificate verified against existing Mutual TLS roots.531. The workload receives a short-lived OIDC JWT or SPIFFE JWT-SVID, or an OpenAI

142. A **service account mapping** authorizes specific external identity attributes to mint tokens for a particular OpenAI service account within a project.54 API workload presents an X.509 certificate.

153. A **token exchange** request sends an external subject token or presents a client certificate to OpenAI and returns a short-lived OpenAI access token.552. The workload presents its external identity with the IDs required by its

164. The workload uses the OpenAI-issued access token as a bearer credential to authenticate requests to the OpenAI API. For X.509 federation, the API request also presents an accepted client certificate.56 product.

573. OpenAI verifies the token or certificate, then evaluates the configured

58 mapping or rule.

594. OpenAI returns a short-lived access token for the mapped principal.

17 60 

18You must be an organization owner to configure this feature. Go to [Organization Settings > Security > Workload Identity Provider](https://platform.openai.com/settings/organization/security/workload-identity-provider), then configure service account mappings from the workload identity provider details page. The X.509 provider option is available in beta. If it doesn't appear, contact your system administrator; your administrator can work with OpenAI to enable the beta for your organization.61Token exchange never creates a principal, project, or workspace membership.

62Administrators create or select those resources during setup.

19 63 

20## Choose a setup guide64<a id="choose-a-setup-guide"></a>

21 65 

22Start with the guide that matches your workload environment or identity source:66## Get an identity token

67 

68Choose the guide for the environment where your workload runs:

23 69 

24 70 

25 71 


34 80 

35 81 

36 82 

37OpenAI supports OIDC-compatible JWT subject tokens in the documented configurations, including SPIFFE JWT-SVIDs. If you need an OIDC provider that isn't listed, contact us.83OpenAI supports OIDC-compatible JWT subject tokens in the documented

84configurations, including SPIFFE JWT-SVIDs. For the OpenAI API, contact OpenAI

85support if your OIDC provider isn't listed. For Codex, choose **Custom OIDC** in

86the OpenAI Admin Portal.

87 

88Each OIDC provider guide explains how to issue and inspect a token. For Codex,

89follow only those token-issuance steps, then return to

90[Use workload identity with Codex](#use-workload-identity-with-codex). The

91guides' OpenAI setup and SDK examples apply to the OpenAI API path. X.509

92federation supports the OpenAI API path only.

38 93 

39Each OIDC provider guide shows how to issue and inspect a subject token on that platform, and how to configure the OpenAI SDK to exchange it for a short-lived OpenAI access token.94## Use workload identity with the OpenAI API

40 95 

41## X.509 providers (beta)96Use this path when your workload calls the OpenAI API directly. You must be an

97organization owner to configure it.

98 

99Go to [Organization Settings > Security > Workload Identity Provider](https://platform.openai.com/settings/organization/security/workload-identity-provider).

100Create the provider first, then configure its service account mappings from the

101provider details page.

102 

103### X.509 providers (beta)

42 104 

43X.509 workload identity federation is available in beta. If X.509 doesn't105X.509 workload identity federation is available in beta. If X.509 doesn't

44 appear as a provider type, contact your system administrator. Your106 appear as a provider type, contact your system administrator. Your


52 114 

53Follow the [X.509 certificate setup guide](https://developers.openai.com/api/docs/guides/workload-identity-federation/x509) for the complete dashboard and request flow.115Follow the [X.509 certificate setup guide](https://developers.openai.com/api/docs/guides/workload-identity-federation/x509) for the complete dashboard and request flow.

54 116 

55## Configure an OIDC Workload Identity Provider117### Configure an OIDC Workload Identity Provider

56 

57Create a Workload Identity Provider for each external issuer you trust. Workload identity federation supports OIDC JWT subject tokens.

58 

59For certificate-backed workloads, follow the [X.509 certificate guide](https://developers.openai.com/api/docs/guides/workload-identity-federation/x509). X.509 providers reuse active Mutual TLS roots and don't use OIDC issuer, audience, discovery, or JWKS settings.

60 118 

61Workload Identity Provider configuration includes these dashboard options:119Create a Workload Identity Provider for each external issuer you trust. OpenAI

120API workload identity supports OIDC JWT subject tokens. Its configuration

121includes:

62 122 

63| Option | Description |123| Option | Description |

64| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |124| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |


72| JWKS JSON | The uploaded public JWKS object used when uploaded JWKS verification is enabled. The JWKS must contain a non-empty `keys` array and no private key material. |132| JWKS JSON | The uploaded public JWKS object used when uploaded JWKS verification is enabled. The JWKS must contain a non-empty `keys` array and no private key material. |

73| Attribute transformations | Optional CEL expressions that derive custom `openai.*` attributes from token claims for mapping decisions. |133| Attribute transformations | Optional CEL expressions that derive custom `openai.*` attributes from token claims for mapping decisions. |

74 134 

75Custom OIDC discovery and uploaded JWKS are mutually exclusive. Enabling custom discovery hides the uploaded JWKS option. The custom discovery URL must use public HTTPS and cannot contain credentials, a custom port, a query, or a fragment.135Custom OIDC discovery and uploaded JWKS are mutually exclusive. Enabling

136custom discovery hides the uploaded JWKS option. The custom discovery URL must

137use public HTTPS and cannot contain credentials, a custom port, a query, or a

138fragment.

76 139 

77If **Use custom URL for OIDC discovery** does not appear in your dashboard, use standard OIDC discovery or enable **Use uploaded JWKS for token verification** instead. Use the public JWKS published by your identity provider and update it when the provider rotates its signing keys.140If **Use custom URL for OIDC discovery** does not appear in your dashboard, use

141standard OIDC discovery or enable **Use uploaded JWKS for token verification**

142instead. Use the public JWKS published by your identity provider and update it

143when the provider rotates its signing keys.

78 144 

79When the token issuer and discovery host differ, set **OIDC Issuer URL** to the token's `iss` claim and **Custom OIDC discovery URL** to the host that publishes the provider's discovery document. OpenAI still checks the token against the configured issuer; the custom URL only determines where it retrieves discovery metadata and public signing keys.145When the token issuer and discovery host differ, set **OIDC Issuer URL** to the

146token's `iss` claim and **Custom OIDC discovery URL** to the host that publishes

147the provider's discovery document. OpenAI still checks the token against the

148configured issuer; the custom URL only determines where it retrieves discovery

149metadata and public signing keys.

80 150 

81### Transform token claims with CEL151#### Transform token claims with CEL

82 152 

83Attribute transformations use Common Expression Language (CEL). OpenAI supports the standard CEL operators specified in [langdef.md](https://github.com/google/cel-spec/blob/master/doc/langdef.md) and doesn't add custom workload identity federation-specific functions. Each expression receives one root object:153Attribute transformations use Common Expression Language (CEL). OpenAI

154supports the standard CEL operators specified in

155[langdef.md](https://github.com/google/cel-spec/blob/master/doc/langdef.md) and

156doesn't add custom workload identity federation functions. Each expression

157receives one root object:

84 158 

85- `assertion`: The verified JWT claim set.159- `assertion`: The verified JWT claim set.

86 160 

87In the dashboard, the `openai.` prefix is applied automatically. Enter the suffix, such as `subject`, and an expression, such as `assertion.sub`. The API stores the derived attribute as `openai.subject`.161The dashboard automatically applies the `openai.` prefix. Enter the

162suffix, such as `subject`, and an expression, such as `assertion.sub`. The API

163stores the derived attribute as `openai.subject`.

88 164 

89```json165```json

90[166[


99]175]

100```176```

101 177 

102Use CEL syntax defined by the CEL language specification. For example, you can read claim values with expressions such as `assertion.sub` or `assertion.repository`. Unsupported syntax or functions fail mapping resolution.178Use CEL syntax defined by the CEL language specification. For example, you can

179read claim values with expressions such as `assertion.sub` or

180`assertion.repository`. Unsupported syntax or functions fail mapping

181resolution.

103 182 

104```json183```json

105[184[


114]193]

115```194```

116 195 

117Transformation results must be scalar values: strings, boolean values, integers, or finite numbers. Arrays, objects, null values, and evaluation errors fail mapping resolution. OpenAI converts scalar transformation results to strings before comparing them to mapping values. For example, `true` becomes `"true"` and `7` becomes `"7"`.196Transformation results must be scalar values: strings, `true` or `false`

118 197values, integers, or finite numbers. Arrays, objects, null values, and

119Mapping keys that start with `openai.` resolve only from attribute transformations. Raw subject token claims that already use an `openai.` prefix don't affect mapping decisions unless you configure a matching transformation.198evaluation errors fail mapping resolution. OpenAI converts scalar

120 199transformation results to strings before comparing them to mapping values. For

121### Manage JWKS and key rotation200example, `true` becomes `"true"` and `7` becomes `"7"`.

122 201 

123OpenAI verifies OIDC subject tokens with the key source configured on the Workload Identity Provider.202Mapping keys that start with `openai.` resolve only from attribute

124 203transformations. Raw subject token claims that already use an `openai.` prefix

125- **OIDC discovery:** OpenAI fetches the issuer's `/.well-known/openid-configuration`, then fetches the discovered `jwks_uri`. Discovery documents and remote JWKS payloads are cached for 600 seconds.204don't affect mapping decisions unless you configure a matching transformation.

126- **Custom OIDC discovery:** OpenAI fetches `/.well-known/openid-configuration` from the configured custom discovery base URL, then fetches the discovered `jwks_uri`. The token's `iss` claim must still match **OIDC Issuer URL**. Use this option when the issuer and discovery document use different hosts.205 

127- **Key refresh on miss:** If a token `kid` isn't found in the cached JWKS, OpenAI refreshes the JWKS and tries the lookup again before rejecting the token.206#### Manage JWKS and key rotation

128- **Uploaded JWKS:** When **Use uploaded JWKS for token verification** is enabled, OpenAI uses the uploaded JWKS stored on the Workload Identity Provider and doesn't perform OIDC discovery or remote JWKS fetching. After a provider update is saved and available to token exchange, new exchanges use the saved JWKS.207 

129- **Multiple keys:** A JWKS can contain multiple public keys, and each key must have a unique non-empty `kid`.208OpenAI verifies OIDC subject tokens with the key source configured on the

130 209Workload Identity Provider:

131During signing-key rotation, publish both old and new public keys in the issuer JWKS during the rotation window. This lets tokens signed by the old key continue working while OpenAI accepts tokens signed by the new key. For uploaded JWKS mode, update the Workload Identity Provider JWKS before issuing tokens with the new `kid`; OpenAI rejects tokens signed by a key absent from the configured JWKS.210 

132 211- **OIDC discovery:** OpenAI fetches the issuer's

133## Configure service account mappings212 `/.well-known/openid-configuration`, then fetches the discovered `jwks_uri`.

134 213 OpenAI caches discovery documents and remote JWKS payloads for 600 seconds.

135A service account mapping defines which external identities can mint access tokens for an OpenAI service account.214- **Custom OIDC discovery:** OpenAI fetches

136 215 `/.well-known/openid-configuration` from the configured custom discovery base

137For X.509 providers, mapping keys use derived `openai.*` attributes. Prefer an exact `openai.subject` mapping. Raw JWT claims such as `sub`, `aud`, and `iss` apply only to OIDC providers.216 URL, then fetches the discovered `jwks_uri`. The token's `iss` claim must

138 217 still match **OIDC Issuer URL**.

139Mapping configuration includes these dashboard options:218- **Key refresh on miss:** If a token `kid` isn't found in the cached JWKS,

219 OpenAI refreshes the JWKS and tries the lookup again before rejecting the

220 token.

221- **Uploaded JWKS:** When **Use uploaded JWKS for token verification** is

222 enabled, OpenAI uses the uploaded JWKS stored on the provider and doesn't

223 perform OIDC discovery or remote JWKS fetching. After a provider update is

224 available to token exchange, new exchanges use the saved JWKS.

225- **Key sets:** A JWKS can contain more than one public key. Each key must have a

226 unique, non-empty `kid`.

227 

228During signing-key rotation, publish both old and new public keys in the issuer

229JWKS during the rotation window. This lets tokens signed by the old key keep

230working while OpenAI accepts tokens signed by the new key. For uploaded JWKS,

231update the provider before issuing tokens with the new `kid`; OpenAI rejects

232tokens signed by a key absent from the configured JWKS.

233 

234<a id="configure-service-account-mappings"></a>

235 

236### Configure a service account mapping

237 

238A service account mapping defines which external identities can mint access

239tokens for an OpenAI service account.

240 

241For X.509 providers, mapping keys use derived `openai.*` attributes. Prefer an

242exact `openai.subject` mapping. Raw JWT claims such as `sub`, `aud`, and `iss`

243apply only to OIDC providers.

244 

245Its configuration includes:

140 246 

141| Option | Description |247| Option | Description |

142| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |248| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |


148| Service account | The service account the workload can use. You can create a new service account in the selected project or select an existing service account. |254| Service account | The service account the workload can use. You can create a new service account in the selected project or select an existing service account. |

149| Permissions | Optional API permissions that further narrow access tokens minted from this mapping. These permissions can't grant access beyond the mapped service account. |255| Permissions | Optional API permissions that further narrow access tokens minted from this mapping. These permissions can't grant access beyond the mapped service account. |

150 256 

151Attribute assertion values must be scalar JSON values. String values may use one trailing wildcard, such as `repo:example/*`. The wildcard must have a non-empty prefix; `*` by itself isn't supported.257Attribute values must be scalar JSON values. String values can use one trailing

258wildcard with a non-empty prefix, such as `repo:example/*`. A wildcard by itself

259or in the middle of a value isn't supported.

152 260 

153Valid wildcard values:261Valid wildcard values:

154 262 

155- `repo:openai/*`263- `repo:openai/*`

156- `repository:my-org/*`264- `repository:my-org/*`

157 265 

158Invalid wildcard values:266Unsupported wildcard values:

159 267 

160- `*`268- `*`

161- `repo:*:prod`269- `repo:*:prod`

162- `repo/*/main`270- `repo/*/main`

163 271 

164The dashboard shows mapping-level restrictions as **Permissions**. Token exchange responses expose the same restrictions as OAuth scopes in the `scope` property. Admin API scopes can't be assigned to Workload Identity Provider mappings, and downstream API authorization still applies after OpenAI mints a token.272The dashboard shows mapping restrictions as **Permissions**. Token exchange

273responses expose the same restrictions as OAuth scopes in the `scope`

274property. Mappings can't include Admin API scopes, and normal downstream API

275authorization still applies.

165 276 

166### Mapping resolution example277#### Mapping resolution example

167 278 

168Mapping resolution starts after OpenAI verifies the external identity. OpenAI looks up mappings for the requested `identity_provider_id` and `service_account_id`, skips disabled mappings, evaluates only the attributes needed by each mapping, and issues a token only if exactly one enabled mapping matches all configured attributes.279Mapping resolution starts after OpenAI verifies the external identity.

280OpenAI looks up mappings for the requested `identity_provider_id` and

281`service_account_id`, skips mappings that aren't enabled, evaluates only the

282attributes needed by each mapping, and issues a token only if exactly one

283enabled mapping matches every configured attribute.

169 284 

170For example, a GitHub Actions token might contain these claims:285Suppose a GitHub Actions token contains these claims:

171 286 

172```json287```json

173{288{


179}294}

180```295```

181 296 

182The Workload Identity Provider can define a derived attribute:297The provider can derive an attribute:

183 298 

184```json299```json

185[300[


190]305]

191```306```

192 307 

193Then a service account mapping can require both raw and derived attributes:308The service account mapping can then require both raw and derived attributes:

194 309 

195| Key | Value |310| Key | Value |

196| ----------------------- | --------------------------------------------- |311| ----------------------- | --------------------------------------------- |


198| `sub` | `repo:my-org/my-repo:*` |313| `sub` | `repo:my-org/my-repo:*` |

199| `openai.repository_ref` | `my-org/my-repo@refs/heads/main` |314| `openai.repository_ref` | `my-org/my-repo@refs/heads/main` |

200 315 

201This mapping matches only when all three attributes match. The `sub` value uses a trailing wildcard, so it matches any value with the prefix `repo:my-org/my-repo:`. The `openai.repository_ref` key resolves from the attribute transformation; OpenAI doesn't use a raw token claim named `openai.repository_ref`.316All three values must match. The `sub` value uses a trailing wildcard, so it

317matches any value with the prefix `repo:my-org/my-repo:`. The

318`openai.repository_ref` key resolves from the attribute transformation, not a

319raw token claim with that name.

320 

321If more than one enabled mapping matches an exchange, OpenAI rejects it. OpenAI

322enforces a unique mapping for each `(provider, service account)` pair and

323doesn't combine permissions from different mappings.

324 

325### Connect the workload

326 

327Use the SDK example in your [identity-provider guide](#get-an-identity-token),

328or call the token exchange endpoint directly. For request and response fields,

329authorization behavior, and current limitations, see the

330[workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation).

331 

332## Use workload identity with Codex

333 

334Use this path for trusted Codex automation in a managed ChatGPT workspace.

335Codex maps the workload to a ChatGPT user or service account instead of an API

336Platform service account.

337 

338Codex workload identity federation is in beta and must be enabled for your

339 workspace. To request access, contact your OpenAI representative or [OpenAI

340 Support](https://help.openai.com/en/articles/6614161-how-can-i-contact-support).

341 

342Follow [Use workload identity with

343Codex](https://developers.openai.com/codex/enterprise/workload-identity) for the complete administrator and

344runtime procedure. It covers provider-specific token sources, federation rules,

345the required token-file configuration, credential precedence, supported Codex

346surfaces, rotation, and verification. For optional audit attribution, Codex

347accepts `OPENAI_WORKLOAD_IDENTITY_CONTEXT`; the Codex guide defines its schema,

348privacy limits, and audit behavior.

349 

350Use the [Admin

351API](https://developers.openai.com/api/docs/guides/workload-identity-federation/admin-api) to manage Codex

352providers and rules programmatically. The [federation rule

353reference](https://developers.openai.com/api/docs/guides/workload-identity-federation/federation-rules)

354explains how one rule can accept more than one external subject while mapping to one

355ChatGPT principal.

356 

357## Troubleshoot a connection

358 

359### OpenAI rejects the identity token

360 

361Decode the token locally and compare its `iss`, `aud`, `sub`, `exp`, `iat`, and

362provider-specific claims with the configured provider. Don't paste production

363tokens into third-party JWT tools.

364 

365For the OpenAI API, also compare the token attributes with the selected service

366account mapping. For Codex, compare them with the selected federation rule.

367 

368### The OpenAI API mapping doesn't match

369 

370Confirm that the request uses the intended identity provider and service

371account IDs, that the mapping is active, and that exactly one mapping matches.

372See the [token exchange error reference](https://developers.openai.com/api/reference/workload-identity-federation#token-exchange-errors)

373for detailed error categories.

374 

375### Codex reports incomplete configuration

376 

377Confirm that the Codex process has both required workload identity environment

378variables and that `OPENAI_IDENTITY_TOKEN_FILE` contains an absolute path to a

379current token. Check the file and parent-directory permissions.

380 

381### Codex uses another credential

202 382 

203If multiple enabled mappings match the same token exchange, OpenAI rejects the exchange. OpenAI enforces a unique mapping for each `(provider, service account)` pair and doesn't combine permissions across multiple mappings.383Load both required workload identity variables into the Codex process. The

384presence of either variable selects WIF ahead of API keys, access tokens, and

385stored logins. Start a new process with the downloaded configuration loaded,

386then run `codex login status` again.

204 387 

205## Security recommendations388## Security recommendations

206 389 

207- Use a dedicated OpenAI service account for each application or workload.390- Use a dedicated principal for each application or workload.

208- Separate production and non-production environments.391- Separate production and non-production environments.

209- Prefer exact claim matching over broad attribute patterns.392- Prefer exact claim matching over broad patterns.

210- Grant only the minimum OpenAI permissions required.393- Grant only the access the workload needs.

211- Review and remove unused mappings regularly.394- Use short access-token lifetimes.

212- Monitor token exchange failures and unexpected access patterns.395- Review and remove unused providers, mappings, and rules.

213- Avoid sharing identities across unrelated workloads.396- Review token exchange errors and unexpected access patterns.

397 

398## Related docs

399 

400- [Use workload identity with Codex](https://developers.openai.com/codex/enterprise/workload-identity)

401- [Codex federation rule reference](https://developers.openai.com/api/docs/guides/workload-identity-federation/federation-rules)

402- [Manage Codex workload identity with the Admin API](https://developers.openai.com/api/docs/guides/workload-identity-federation/admin-api)

403- [Workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation)

404- [Codex authentication](https://developers.openai.com/codex/auth)

405- [Codex environment variables](https://developers.openai.com/codex/config-file/environment-variables)

406- [Codex non-interactive mode](https://developers.openai.com/codex/non-interactive-mode)

Details

1# Manage Codex workload identity with the Admin API

2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 

5Use the organization Admin API to manage Codex workload identity providers and

6federation rules from infrastructure tooling or CI. The API exposes the same

7provider and rule model as the OpenAI Admin Portal.

8 

9The API calls federation rules `mappings` in paths and response objects. This

10page uses **federation rule** for the product concept and `mapping` only when it

11refers to an API field or path.

12 

13These endpoints manage the Codex workload identity federation beta for managed

14 ChatGPT workspaces. To request access, contact your OpenAI representative or

15 [OpenAI

16 Support](https://help.openai.com/en/articles/6614161-how-can-i-contact-support).

17 These endpoints do not replace the existing OpenAI API workload identity

18 provider and service account mapping APIs.

19 

20## Prerequisites

21 

22You need:

23 

24- Workload identity federation enabled for your organization and managed

25 ChatGPT workspace.

26- An [Admin API key](https://platform.openai.com/settings/organization/admin-keys)

27 whose owner is an active administrator allowed to manage workload identity.

28- The ID of the managed ChatGPT workspace.

29- The OpenAI user ID of an existing active human or service account in that

30 workspace.

31- The issuer, audience, and claims for the workload's OIDC token or SPIFFE

32 JWT-SVID.

33 

34The WIF endpoints use resource IDs instead of names. They do not list or create

35ChatGPT workspaces or principals. Supply those IDs from your provisioning system.

36If you do not manage those resources programmatically, use the OpenAI Admin

37Portal to create or select the principal and connect that workload.

38 

39Set the Admin API key in your environment:

40 

41```bash

42export OPENAI_ADMIN_KEY="<admin-api-key>"

43```

44 

45Admin API keys are long-lived credentials. Store the key in a secrets manager,

46do not commit it, and do not use it for Codex runtime authentication.

47 

48## Endpoints

49 

50All requests use `https://api.openai.com` and an Admin API key in the bearer

51authorization header.

52 

53| Operation | Method and path |

54| ---------------------------- | ----------------------------------------------------------------------------------------- |

55| List providers | `GET /v1/organization/workload_identity/providers` |

56| Create a provider | `POST /v1/organization/workload_identity/providers` |

57| Get a provider | `GET /v1/organization/workload_identity/providers/{provider_id}` |

58| Update or disable a provider | `POST /v1/organization/workload_identity/providers/{provider_id}` |

59| Archive a provider | `DELETE /v1/organization/workload_identity/providers/{provider_id}` |

60| List rules | `GET /v1/organization/workload_identity/providers/{provider_id}/mappings` |

61| Create a rule | `POST /v1/organization/workload_identity/providers/{provider_id}/mappings` |

62| Get a rule | `GET /v1/organization/workload_identity/providers/{provider_id}/mappings/{mapping_id}` |

63| Update or disable a rule | `POST /v1/organization/workload_identity/providers/{provider_id}/mappings/{mapping_id}` |

64| Archive a rule | `DELETE /v1/organization/workload_identity/providers/{provider_id}/mappings/{mapping_id}` |

65 

66List responses use `{ "object": "list", "data": [...] }`. The endpoints do

67not use pagination.

68 

69## Create an OIDC provider

70 

71Create one provider for each issuer and trust boundary that you want to manage

72independently. Replace the example issuer and audience with exact values from a

73sample token. Inspect the token's `iat` and `exp` claims locally, then choose an

74accepted assertion lifetime that covers the issuer's expected `exp - iat`

75range. OpenAI checks that full duration, not the token's remaining validity.

76 

77For Microsoft Entra, do not assume a one-hour assertion. [Access-token lifetimes

78vary](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens#token-lifetime),

79and Microsoft does not support [configuring managed-identity token

80lifetimes](https://learn.microsoft.com/en-us/entra/identity-platform/configurable-token-lifetimes).

81Replace `MAX_ASSERTION_LIFETIME_SECONDS` with an approved integer from 1 through

82176,400. This provider limit is separate from the lifetime of the OpenAI access

83token that a federation rule issues.

84 

85```bash

86MAX_ASSERTION_LIFETIME_SECONDS="<accepted-issuer-lifetime-seconds>"

87 

88jq -n \

89 --argjson max_assertion_lifetime_seconds "$MAX_ASSERTION_LIFETIME_SECONDS" \

90 '{

91 name: "entra-production",

92 type: "oidc",

93 issuer: "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/v2.0",

94 audience: "api://openai-codex-production",

95 description: "Production Codex workloads in Microsoft Azure",

96 max_assertion_lifetime_seconds: $max_assertion_lifetime_seconds,

97 check_jti: true

98 }' > provider.json

99 

100curl --fail-with-body --silent --show-error \

101 https://api.openai.com/v1/organization/workload_identity/providers \

102 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \

103 -H "Content-Type: application/json" \

104 --data @provider.json \

105 --output provider-response.json

106 

107PROVIDER_ID="$(jq -r .id provider-response.json)"

108printf 'Created provider %s\n' "$PROVIDER_ID"

109```

110 

111Expected output begins with an identity-provider ID:

112 

113```text

114Created provider idp_...

115```

116 

117By default, an OIDC provider uses discovery at its issuer URL. Use `custom_url`

118when the public discovery document lives elsewhere, `jwks_uri` for an

119explicit public JWKS URL, or `jwks_local: true` with `jwks` to upload public

120keys. Do not include private key material.

121 

122## Create a SPIFFE JWT-SVID provider

123 

124Set `type` to `spiffe_jwt`, set `issuer` to the canonical trust domain, and

125provide either a public bundle URL or an uploaded SPIFFE bundle. A SPIFFE rule

126must also set `audiences`.

127 

128```json

129{

130 "name": "spiffe-production",

131 "type": "spiffe_jwt",

132 "issuer": "spiffe://example.com",

133 "jwks_uri": "https://spiffe.example.com/bundle.json",

134 "max_assertion_lifetime_seconds": 3600,

135 "check_jti": true

136}

137```

138 

139For an uploaded bundle, set `jwks_local` to `true`, replace `jwks_uri` with the

140`jwks` object, and include at least one public key whose `use` is `jwt-svid`.

141 

142## Create a federation rule

143 

144A rule targets one existing principal and can match one or many external

145workload identities. This example accepts one Azure managed identity subject:

146 

147```bash

148export WORKSPACE_ID="<managed-chatgpt-workspace-id>"

149export PRINCIPAL_ID="<existing-openai-user-id>"

150 

151jq -n \

152 --arg workspace_id "$WORKSPACE_ID" \

153 --arg principal_id "$PRINCIPAL_ID" \

154 '{

155 name: "entra-payments-production",

156 description: "Production payments workload",

157 workspace_id: $workspace_id,

158 principal_id: $principal_id,

159 external_subject: "11111111-2222-3333-4444-555555555555",

160 audiences: ["api://openai-codex-production"],

161 access_token_lifetime_seconds: 600,

162 enabled: true

163 }' > rule.json

164 

165curl --fail-with-body --silent --show-error \

166 "https://api.openai.com/v1/organization/workload_identity/providers/$PROVIDER_ID/mappings" \

167 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \

168 -H "Content-Type: application/json" \

169 --data @rule.json \

170 --output rule-response.json

171 

172FEDERATION_RULE_ID="$(jq -r .id rule-response.json)"

173printf 'Created federation rule %s\n' "$FEDERATION_RULE_ID"

174```

175 

176Expected output begins with a mapping ID. This is the value Codex uses as

177`OPENAI_FEDERATION_RULE_ID`:

178 

179```text

180Created federation rule idpm_...

181```

182 

183For a set of allowed subjects in one rule, omit `external_subject` and use a CEL

184condition:

185 

186```json

187{

188 "condition": "assertion.sub in [\"workload-a\", \"workload-b\"]"

189}

190```

191 

192Set at least one of `external_subject`, `claims`, or `condition`. All configured

193identity checks must pass. See the [federation rule

194reference](https://developers.openai.com/api/docs/guides/workload-identity-federation/federation-rules) for

195cardinality, CEL, audience, scope, and lifetime behavior.

196 

197## List and reconcile resources

198 

199List providers before creating one so your automation can compare the intended

200configuration with the current state:

201 

202```bash

203curl --fail-with-body --silent --show-error \

204 https://api.openai.com/v1/organization/workload_identity/providers \

205 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" | jq .

206```

207 

208Then list rules under a provider:

209 

210```bash

211curl --fail-with-body --silent --show-error \

212 "https://api.openai.com/v1/organization/workload_identity/providers/$PROVIDER_ID/mappings" \

213 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" | jq .

214```

215 

216The API does not define an idempotency-key contract. Store returned IDs in your

217approved configuration state, read the current resource before changing it,

218and update by ID. Do not create a replacement on every run.

219 

220## Update or disable a resource

221 

222Updates use `POST` with only the fields you want to change. This example changes

223the rule lifetime:

224 

225```bash

226curl --fail-with-body --silent --show-error \

227 -X POST \

228 "https://api.openai.com/v1/organization/workload_identity/providers/$PROVIDER_ID/mappings/$FEDERATION_RULE_ID" \

229 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \

230 -H "Content-Type: application/json" \

231 -d '{"access_token_lifetime_seconds": 300}' | jq .

232```

233 

234Disable a rule for an immediate stop:

235 

236```bash

237curl --fail-with-body --silent --show-error \

238 -X POST \

239 "https://api.openai.com/v1/organization/workload_identity/providers/$PROVIDER_ID/mappings/$FEDERATION_RULE_ID" \

240 -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \

241 -H "Content-Type: application/json" \

242 -d '{"enabled": false}' | jq .

243```

244 

245Set `enabled` to `false` on the provider path to stop every rule under that

246provider. Disablement blocks new exchanges and revokes access tokens issued

247through the resource. You can turn it back on after its principal, workspace,

248binding, and provider are active.

249 

250Ordinary rule edits affect only new exchanges. Tokens issued before the edit can

251remain valid until their TTL ends. Provider trust edits revoke issued tokens

252before the new trust takes effect.

253 

254## Archive a resource

255 

256`DELETE` archives a provider or rule instead of erasing it. Archival blocks new

257exchanges, revokes issued tokens, hides the resource from normal list results,

258and cannot be undone.

259 

260Archive a rule:

261 

262```bash

263curl --fail-with-body --silent --show-error \

264 -X DELETE \

265 "https://api.openai.com/v1/organization/workload_identity/providers/$PROVIDER_ID/mappings/$FEDERATION_RULE_ID" \

266 -H "Authorization: Bearer $OPENAI_ADMIN_KEY"

267```

268 

269Archive a provider:

270 

271```bash

272curl --fail-with-body --silent --show-error \

273 -X DELETE \

274 "https://api.openai.com/v1/organization/workload_identity/providers/$PROVIDER_ID" \

275 -H "Authorization: Bearer $OPENAI_ADMIN_KEY"

276```

277 

278Archiving a provider revokes access for its Codex rules. You must remove any

279non-Codex product mapping before you can archive that provider. This protects

280existing OpenAI API workload identity configuration.

281 

282## Provider fields

283 

284Create requires `name` and `issuer`. Update accepts the mutable fields except

285`type`.

286 

287| Field | Type and behavior |

288| -------------------------------- | ---------------------------------------------------------------------------------------------------------------- |

289| `name` | Non-empty display name. |

290| `type` | `oidc` by default, or `spiffe_jwt`. You cannot change it after creation. |

291| `issuer` | Exact OIDC `iss` URL or canonical SPIFFE trust domain. |

292| `audience` | Optional provider-level audience. Set a rule audience when this is absent. |

293| `description` | Optional administrator description. |

294| `custom_url` | Optional public HTTPS OIDC discovery URL. OIDC only. |

295| `jwks_uri` | Optional public HTTPS JWKS or SPIFFE bundle URL. |

296| `jwks_local` | Set to `true` when supplying `jwks`. |

297| `jwks` | Uploaded public JWKS object, up to 100 keys and 1 MiB. |

298| `custom_ca_certificate` | Optional PEM CA bundle for JWKS HTTPS, up to 256 KiB. |

299| `attribute_conditions` | Optional bounded CEL condition applied before rule matching. Use `assertion` for the verified claims. |

300| `max_assertion_lifetime_seconds` | Accepted upstream assertion lifetime, 1 through 176,400 seconds. OIDC uses the full `exp - iat`. Default: 3,600. |

301| `check_jti` | When `true`, reject a repeated non-empty JWT `jti`. Default: `false`. |

302| `enabled` | Update-only switch that accepts or blocks exchanges. |

303 

304Discovery and explicit or uploaded keys are alternative verification modes.

305Issuer, discovery, and JWKS URLs have validation requirements described in the

306[workload identity overview](https://developers.openai.com/api/docs/guides/workload-identity-federation#manage-jwks-and-key-rotation).

307 

308## Federation rule fields

309 

310Create requires `workspace_id` and `principal_id`, plus at least one identity

311check. You cannot change the workspace or principal after creation.

312 

313| Field | Type and behavior |

314| ------------------------------- | ---------------------------------------------------------------------------------------------------- |

315| `workspace_id` | Existing managed ChatGPT workspace ID. Create-only. |

316| `principal_id` | Existing active OpenAI user or service-account ID in the workspace. Create-only. |

317| `external_subject` | Exact `sub` or one trailing-`*` prefix, up to 4,096 bytes. |

318| `claims` | Up to 32 exact top-level scalar claims. Do not include `sub`. |

319| `audiences` | One through 32 unique accepted audiences. Required for SPIFFE and when the provider has no audience. |

320| `condition` | Bounded CEL boolean condition over `assertion`, up to 16 KiB. |

321| `scopes` | Optional subset of the four supported Codex scopes. Omit to use the default set. |

322| `access_token_lifetime_seconds` | 60 through 3,600 seconds. Default: 3,600. |

323| `name` | Optional display name. |

324| `description` | Optional administrator description. |

325| `enabled` | Whether the rule accepts exchanges. Default: `true`. |

326 

327Provider responses use `workload_identity_provider`; rule responses use

328`workload_identity_mapping`. Both include `id`, `enabled`, `created_at`, and

329`updated_at`. Timestamps are Unix seconds.

330 

331## Limits and errors

332 

333An organization can have up to 50 non-archived providers. A provider can have up

334to 50 non-archived rules. The API returns:

335 

336- `400` for request field errors, provider trust settings, rule conditions, scopes, or

337 inactive principal membership.

338- `403` when the Admin API key owner cannot manage workload identity.

339- `404` when the organization has no tenant association or the requested

340 resource is outside the organization and tenant boundary.

341- `409` for provider or rule limits, subject conflicts, inactive bindings, or

342 lifecycle conflicts.

343 

344Treat `404` as non-disclosing: the service does not reveal a provider or rule

345owned by another organization or tenant. Retry transient `429` and `5xx`

346responses with bounded delays that increase after each attempt. Do not retry a

347validation or permission error without changing the request or administrator

348state.

Details

7- **AWS outbound identity federation:** Exchange an AWS STS-issued OIDC JWT from `GetWebIdentityToken` for a short-lived OpenAI access token.7- **AWS outbound identity federation:** Exchange an AWS STS-issued OIDC JWT from `GetWebIdentityToken` for a short-lived OpenAI access token.

8- **Amazon EKS:** Exchange a projected Amazon EKS service account token for a short-lived OpenAI access token.8- **Amazon EKS:** Exchange a projected Amazon EKS service account token for a short-lived OpenAI access token.

9 9 

10For Codex, use this page to get and inspect the AWS token. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to write that token to a file and point Codex to it. The service-account mapping and SDK examples on this page apply to the OpenAI API.

11 

10OpenAI supports AWS-issued OIDC JWTs from outbound identity federation and12OpenAI supports AWS-issued OIDC JWTs from outbound identity federation and

11 Kubernetes projected service account tokens issued by Amazon EKS. OpenAI does13 Kubernetes projected service account tokens issued by Amazon EKS. OpenAI does

12 not support SigV4-signed requests or AWS STS temporary access key credentials14 not support SigV4-signed requests or AWS STS temporary access key credentials

Details

1# Codex federation rule reference

2 

3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 

5A federation rule decides which verified workload identities may act as one

6ChatGPT user or service account. OpenAI evaluates only the rule named by the

7Codex process. It does not search every rule for a match.

8 

9Each rule has one target principal and can accept one or many upstream

10identities. To accept a set of subjects in one rule, use a trailing-prefix

11subject or a CEL condition. You can also create more than one rule for the same

12principal.

13 

14For the setup procedure, see [Use workload identity with

15Codex](https://developers.openai.com/codex/enterprise/workload-identity). To manage rules with code, see the

16[workload identity Admin

17API](https://developers.openai.com/api/docs/guides/workload-identity-federation/admin-api).

18 

19## Rule model

20 

21| Part | Purpose |

22| --------------------- | --------------------------------------------------------------- |

23| Provider | Defines the issuer and signing keys OpenAI trusts. |

24| Workspace | Limits the resulting access to one managed ChatGPT workspace. |

25| Principal | Selects one existing user or service account in that workspace. |

26| Identity checks | Restrict which verified identity tokens may use the rule. |

27| Scopes | Optionally narrow the existing Codex OAuth scopes. |

28| Access token lifetime | Limits the OpenAI access token to 60 through 3,600 seconds. |

29 

30The principal and its workspace membership must exist before exchange. A rule

31does not create a user, service account, or membership when a workload connects.

32 

33## How identity checks combine

34 

35A rule can use these checks:

36 

37| Check | Behavior | Use it for |

38| ------------------ | --------------------------------------------------------------------- | -------------------------------------------------------- |

39| Subject | Exact `sub` value or one trailing `*` prefix. | One workload identity or a controlled subject namespace. |

40| Accepted audiences | One through 32 audience strings. The token must contain at least one. | Tokens minted specifically for OpenAI. |

41| Exact claims | Up to 32 exact top-level scalar claim values. | Stable strings, numbers, true/false values, or null. |

42| CEL condition | A boolean expression over the verified claim map named `assertion`. | Lists, nested claims, or a set of allowed values. |

43 

44Set at least one subject, exact-claim, or CEL check. An accepted

45audience alone does not identify a workload. If you configure more than one

46check type, each one must pass.

47 

48Provider verification happens first. A rule cannot override the provider's

49issuer, signature, expiry, assertion-lifetime, replay, or provider-level CEL

50checks.

51 

52## Subject matching

53 

54Use an exact subject whenever one stable `sub` identifies the workload:

55 

56```text

57repo:example-company/payments:environment:production

58```

59 

60One trailing `*` performs a prefix match:

61 

62```text

63system:serviceaccount:production:codex-*

64```

65 

66The wildcard must be the last character and must follow a non-empty prefix.

67OpenAI does not accept `*`, `repo:*:production`, or `repo/*/main`.

68 

69Do not use a broad prefix when a more stable claim can separate privileged

70workloads. For example, a GitHub rule should match a repository,

71workflow file, ref, or protected environment rather than every repository

72owned by one organization.

73 

74## Exact claims

75 

76Exact claims compare top-level JWT claims without converting their types. A

77string matches only the same string, a boolean matches only the same boolean,

78and a number matches the same numeric value. Lists and objects are not supported

79as exact values.

80 

81For example:

82 

83```json

84{

85 "repository": "example-company/payments",

86 "ref": "refs/heads/main",

87 "environment": "production"

88}

89```

90 

91Do not include `sub` in the exact-claims map. Use the subject field or CEL.

92Use CEL for nested provider claims and list membership.

93 

94## CEL conditions

95 

96CEL conditions receive the complete verified JWT claim map as `assertion` and

97must return `true` or `false`. OpenAI supports a bounded CEL subset so rule

98evaluation stays predictable.

99 

100To allow a set of exact subjects in one rule:

101 

102```text

103assertion.sub in [

104 "repo:example-company/payments:environment:production",

105 "repo:example-company/billing:environment:production"

106]

107```

108 

109To require a repository and one of two refs:

110 

111```text

112assertion.repository == "example-company/payments" &&

113assertion.ref in ["refs/heads/main", "refs/heads/release"]

114```

115 

116To read a nested or optional claim:

117 

118```text

119has(assertion.environment) &&

120assertion.environment == "production"

121```

122 

123Supported helpers include `has`, `size`, `contains`, `startsWith`, and

124`endsWith`. Regular-expression matching, collection iteration macros such as

125`all` or `exists`, arbitrary functions, and identifiers other than `assertion`

126are not supported. Keep expressions short and prefer exact checks when they

127can express the same policy.

128 

129An absent claim, unsupported operation, non-boolean result, or evaluation error

130rejects the exchange.

131 

132## Audience matching

133 

134The provider can set one expected audience. A rule can instead set one or more

135accepted audiences. When a rule has an audience list, at least one value in the

136token's `aud` claim must appear in that list.

137 

138Use a dedicated audience for OpenAI when your provider supports one. SPIFFE

139JWT-SVID rules must set an accepted audience. An OIDC rule must also set one if

140the provider does not define a provider-level audience.

141 

142Audience matching and identity checks are cumulative. A matching audience does

143not compensate for a subject, exact-claim, or CEL check that does not pass.

144 

145## Principal cardinality

146 

147One rule maps to exactly one principal:

148 

149```text

150many accepted external identities -> one federation rule -> one OpenAI principal

151```

152 

153This supports workload replicas, jobs, or approved subjects acting as the same

154user or service account. It does not let one rule choose a different

155principal based on claims. Create separate rules when workloads need different

156principals, workspaces, scopes, or token lifetimes.

157 

158More than one rule may target the same principal. Use separate rules when you need

159independent lifecycle controls or clearer audit attribution for each workload.

160 

161## Scopes and authorization

162 

163The rule can narrow the OAuth scopes in the issued access token. It cannot grant

164permissions the target principal or workspace does not already have.

165 

166When you omit scopes, OpenAI uses the standard Codex scopes: `openid`,

167`profile`, `email`, and Codex local access. If you set scopes through the Admin

168API, include `chatgpt.workspace.feature.allow-codex-local-access.access` and use

169only those four supported values.

170 

171Choose the least-privilege principal and workspace permissions first. Treat

172rule scopes as a second restriction, not the main authorization boundary.

173 

174## Token lifetime

175 

176Set the OpenAI access token lifetime from 60 through 3,600 seconds. OpenAI uses

177the shorter of:

178 

179- The remaining lifetime of the upstream identity token.

180- The rule's configured access-token lifetime.

181 

182Shorter lifetimes reduce how long an issued token can outlive a policy edit,

183but increase exchange frequency. A 10-minute lifetime is a practical starting

184point unless your workload needs a different balance.

185 

186## Replay protection

187 

188Provider-level replay protection uses the JWT `jti` claim. When an administrator

189turns on **Prevent assertion replay** and the token has a non-empty `jti`, OpenAI

190accepts that `jti` only once for that provider until the assertion expires.

191 

192The workload must get a new assertion with a new `jti` before every exchange,

193including retries after an exchange whose outcome is unknown. Assertions without

194`jti` remain usable but do not receive replay protection. Empty, null, or

195non-string `jti` values do not pass validation.

196 

197## Changes, disablement, and archival

198 

199Ordinary edits to identity checks, scopes, or token lifetime apply to new exchanges.

200Access tokens issued before the edit can remain valid until their existing TTL

201ends.

202 

203Disabling a rule or provider blocks new exchanges and revokes OpenAI access

204tokens issued through it. Archiving does the same and cannot be undone.

205Changing provider trust, such as issuer or JWKS settings, revokes issued tokens

206before the new trust configuration becomes active.

207 

208Use disablement for an emergency stop or a temporary pause. Archive a resource

209only when you no longer need it.

210 

211## Limits

212 

213| Resource | Limit |

214| --------------------------------------- | ------------------- |

215| Non-archived providers per organization | 50 |

216| Non-archived rules per provider | 50 |

217| Exact claims per rule | 32 |

218| Accepted audiences per rule | 32 unique values |

219| Subject length | 4,096 bytes |

220| Exact-claim map or CEL condition | 16 KiB |

221| Access token lifetime | 60 to 3,600 seconds |

222 

223Create separate providers for trust boundaries that need independent issuer,

224key, replay, or lifecycle controls. Create separate rules under one provider

225for workloads that share trust but need different principals or access policy.

Details

4 4 

5Use GitHub Actions as a Workload Identity Provider by exchanging a GitHub-issued OIDC token for a short-lived OpenAI access token. This lets workflows authenticate to the OpenAI API without storing a long-lived API key in GitHub secrets.5Use GitHub Actions as a Workload Identity Provider by exchanging a GitHub-issued OIDC token for a short-lived OpenAI access token. This lets workflows authenticate to the OpenAI API without storing a long-lived API key in GitHub secrets.

6 6 

7For Codex, use this page to get and inspect the GitHub token. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to write that token to a file and point Codex to it. The service-account mapping and SDK examples on this page apply to the OpenAI API.

8 

7GitHub can mint a signed OIDC JWT for a workflow job that has `id-token: write` permission and requests an identity token. OpenAI validates the token issuer, audience, signature, and mapping attributes before issuing an OpenAI access token.9GitHub can mint a signed OIDC JWT for a workflow job that has `id-token: write` permission and requests an identity token. OpenAI validates the token issuer, audience, signature, and mapping attributes before issuing an OpenAI access token.

8 10 

9## Setting up GitHub Actions11## Setting up GitHub Actions

Details

7- **Google workload identity:** Exchange a Google-signed OIDC token issued to an attached Google service account for a short-lived OpenAI access token.7- **Google workload identity:** Exchange a Google-signed OIDC token issued to an attached Google service account for a short-lived OpenAI access token.

8- **Google Kubernetes Engine:** Exchange a projected GKE service account token for a short-lived OpenAI access token.8- **Google Kubernetes Engine:** Exchange a projected GKE service account token for a short-lived OpenAI access token.

9 9 

10For Codex, use this page to get and inspect the Google token. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to write that token to a file and point Codex to it. The service-account mapping and SDK examples on this page apply to the OpenAI API.

11 

10 12 

11 13 

12## Google workload identity14## Google workload identity

Details

4 4 

5Use Kubernetes as a Workload Identity Provider by exchanging a projected Kubernetes service account token for a short-lived OpenAI access token.5Use Kubernetes as a Workload Identity Provider by exchanging a projected Kubernetes service account token for a short-lived OpenAI access token.

6 6 

7For Codex, use this page to get and inspect the projected token. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to point Codex to the mounted token file. The service-account mapping and SDK examples on this page apply to the OpenAI API.

8 

7## Setting up Kubernetes9## Setting up Kubernetes

8 10 

9This guide assumes Kubernetes service account token projection is enabled, which is available by default in modern Kubernetes releases. OpenAI workload identity federation requires OIDC-compatible projected service account tokens. Legacy Kubernetes service account tokens stored in Secrets are not supported.11This guide assumes Kubernetes service account token projection is enabled, which is available by default in modern Kubernetes releases. OpenAI workload identity federation requires OIDC-compatible projected service account tokens. Legacy Kubernetes service account tokens stored in Secrets are not supported.

Details

7- **Azure managed identity:** Exchange a Microsoft Entra ID access token issued for a managed identity for a short-lived OpenAI access token.7- **Azure managed identity:** Exchange a Microsoft Entra ID access token issued for a managed identity for a short-lived OpenAI access token.

8- **AKS:** Exchange a projected Azure Kubernetes Service (AKS) service account token for a short-lived OpenAI access token.8- **AKS:** Exchange a projected Azure Kubernetes Service (AKS) service account token for a short-lived OpenAI access token.

9 9 

10For Codex, use this page to get and inspect the Microsoft Entra token. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to write that token to a file and point Codex to it. The service-account mapping and SDK examples on this page apply to the OpenAI API.

11 

10 12 

11 13 

12## Azure managed identity14## Azure managed identity


79- `aud`: Must match the Application ID URI, the IMDS `resource` parameter, and the OpenAI Workload Identity Provider audience.81- `aud`: Must match the Application ID URI, the IMDS `resource` parameter, and the OpenAI Workload Identity Provider audience.

80- `tid`: The Microsoft Entra tenant ID.82- `tid`: The Microsoft Entra tenant ID.

81- `appid`: The managed identity's application/client ID, when present.83- `appid`: The managed identity's application/client ID, when present.

84- `iat` and `exp`: Check the token's full lifetime, `exp - iat`, in seconds.

85 

86For Codex, set the provider's `max_assertion_lifetime_seconds` to an approved

87limit that covers the issuer's expected token-lifetime range. Do not use the

88token's remaining validity or assume that every Entra token lasts one hour.

89Microsoft documents [variable access-token

90lifetimes](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens#token-lifetime)

91and does not support [configuring managed-identity token

92lifetimes](https://learn.microsoft.com/en-us/entra/identity-platform/configurable-token-lifetimes).

93See the [Admin API provider

94example](https://developers.openai.com/api/docs/guides/workload-identity-federation/admin-api#create-an-oidc-provider).

82 95 

83Managed identity tokens can also contain claims such as `azp`, `oid`, `sub`, or `xms_mirid`. Use the decoded token as the source of truth, and choose claims that identify the exact managed identity and resource boundary you trust.96Managed identity tokens can also contain claims such as `azp`, `oid`, `sub`, or `xms_mirid`. Use the decoded token as the source of truth, and choose claims that identify the exact managed identity and resource boundary you trust.

84 97 

Details

4 4 

5Use Oracle Cloud Infrastructure (OCI) as a Workload Identity Provider by exchanging an Oracle Identity Cloud Service (IDCS) access token for a short-lived OpenAI access token. An OCI instance principal signs a token exchange request to an identity domain in the same tenancy. OpenAI validates the resulting token and authorizes the OCI workload to act as a mapped OpenAI service account.5Use Oracle Cloud Infrastructure (OCI) as a Workload Identity Provider by exchanging an Oracle Identity Cloud Service (IDCS) access token for a short-lived OpenAI access token. An OCI instance principal signs a token exchange request to an identity domain in the same tenancy. OpenAI validates the resulting token and authorizes the OCI workload to act as a mapped OpenAI service account.

6 6 

7For Codex, use this page to get and inspect the Oracle token. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to write that token to a file and point Codex to it. The service-account mapping and SDK examples on this page apply to the OpenAI API.

8 

7This setup does not require an OpenAI API key, a custom Oracle OAuth resource application, or dynamic group grants to a custom application.9This setup does not require an OpenAI API key, a custom Oracle OAuth resource application, or dynamic group grants to a custom application.

8 10 

9## Set up the OCI workload11## Set up the OCI workload

Details

4 4 

5Use SPIFFE as a Workload Identity Provider by exchanging a SPIFFE JWT-SVID for a short-lived OpenAI access token. This lets workloads authenticated by SPIRE or another SPIFFE-compatible identity provider call the OpenAI API without storing long-lived API keys.5Use SPIFFE as a Workload Identity Provider by exchanging a SPIFFE JWT-SVID for a short-lived OpenAI access token. This lets workloads authenticated by SPIRE or another SPIFFE-compatible identity provider call the OpenAI API without storing long-lived API keys.

6 6 

7For Codex, use this page to get and inspect the JWT-SVID. Then [configure Codex workload identity](https://developers.openai.com/codex/enterprise/workload-identity) to write that token to a file and point Codex to it. The service-account mapping and SDK examples on this page apply to the OpenAI API.

8 

7OpenAI supports SPIFFE JWT-SVIDs that can be validated as JWT subject tokens with an issuer, audience, expiration, issued-at timestamp, and JWKS-backed signature. OpenAI doesn't support SPIFFE X.509-SVIDs as workload identity federation subject tokens.9OpenAI supports SPIFFE JWT-SVIDs that can be validated as JWT subject tokens with an issuer, audience, expiration, issued-at timestamp, and JWKS-backed signature. OpenAI doesn't support SPIFFE X.509-SVIDs as workload identity federation subject tokens.

8 10 

9The JWT-SVID specification requires the `sub`, `aud`, and `exp` claims. To use a JWT-SVID with OpenAI, the token must also include `iss` and `iat` claims and a `kid` header so OpenAI can validate the token against the Workload Identity Provider configuration.11The JWT-SVID specification requires the `sub`, `aud`, and `exp` claims. To use a JWT-SVID with OpenAI, the token must also include `iss` and `iat` claims and a `kid` header so OpenAI can validate the token against the Workload Identity Provider configuration.

Details

4 4 

5X.509 workload identity federation lets a workload exchange an identity from a TLS client certificate for a short-lived OpenAI access token. The workload then calls the OpenAI API with both the access token and an accepted client certificate. This flow replaces the API key, not the client certificate.5X.509 workload identity federation lets a workload exchange an identity from a TLS client certificate for a short-lived OpenAI access token. The workload then calls the OpenAI API with both the access token and an accepted client certificate. This flow replaces the API key, not the client certificate.

6 6 

7X.509 workload identity federation is available in beta. If X.509 doesn't7X.509 workload identity federation is available in beta for the OpenAI API;

8 appear as a provider type, contact your system administrator. Your8 Codex does not support it. If X.509 doesn't appear as a provider type, contact

9 administrator can work with OpenAI to enable the beta for your organization.9 your system administrator. For Codex, use an OIDC token or SPIFFE JWT-SVID and

10 follow the [Codex workload identity

11 guide](https://developers.openai.com/codex/enterprise/workload-identity).

10 12 

11For token exchange request and response details, see the [workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation#exchange-an-x509-certificate). For Mutual TLS certificate requirements and supported API endpoints, see the [OpenAI Mutual TLS Beta Program](https://help.openai.com/en/articles/10876024-openai-mutual-tls-beta-program).13For token exchange request and response details, see the [workload identity token exchange reference](https://developers.openai.com/api/reference/workload-identity-federation#exchange-an-x509-certificate). For Mutual TLS certificate requirements and supported API endpoints, see the [OpenAI Mutual TLS Beta Program](https://help.openai.com/en/articles/10876024-openai-mutual-tls-beta-program).

12 14 

Details

384 384 

385Current limitation: image commands do not yet have native `--output` support, so image generation still requires extracting `b64_json` and decoding it yourself.385Current limitation: image commands do not yet have native `--output` support, so image generation still requires extracting `b64_json` and decoding it yourself.

386 386 

387For `gpt-image-2`, omit `--input-fidelity`; image inputs are always processed at high fidelity. Do not use `--background transparent` with `gpt-image-2`. The model also supports broader `--size` values than earlier GPT Image models, as long as the requested resolution satisfies the Image API size constraints.387For `gpt-image-2`, omit `--input-fidelity`; image inputs are always processed at high fidelity. Transparent backgrounds are available in preview; use `--background transparent` with `png` (the default) or `webp`. `jpeg` isn't supported with transparent backgrounds. The model also supports broader `--size` values than earlier GPT Image models, as long as the requested resolution satisfies the Image API size constraints.

388 388 

389### Edit an image389### Edit an image

390 390 

quickstart.md +259 −0

Details

485}485}

486```486```

487 487 

488```java

489import com.openai.client.OpenAIClient;

490import com.openai.client.okhttp.OpenAIOkHttpClient;

491import com.openai.models.responses.ResponseCreateParams;

492import com.openai.models.responses.ResponseInputImage;

493import com.openai.models.responses.ResponseInputItem;

494import java.util.List;

495 

496ResponseInputItem imageInput =

497 ResponseInputItem.ofMessage(

498 ResponseInputItem.Message.builder()

499 .role(ResponseInputItem.Message.Role.USER)

500 .addInputTextContent("What teams are playing in this image?")

501 .addContent(

502 ResponseInputImage.builder()

503 .detail(ResponseInputImage.Detail.AUTO)

504 .imageUrl(

505 "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg")

506 .build())

507 .build());

508 

509ResponseCreateParams params =

510 ResponseCreateParams.builder()

511 .model("gpt-5.6")

512 .inputOfResponse(List.of(imageInput))

513 .build();

514 

515client.responses().create(params).output().stream()

516 .flatMap(item -> item.message().stream())

517 .flatMap(message -> message.content().stream())

518 .flatMap(content -> content.outputText().stream())

519 .forEach(text -> System.out.println(text.text()));

520```

521 

488```csharp522```csharp

489using OpenAI.Responses;523using OpenAI.Responses;

490#pragma warning disable OPENAI001524#pragma warning disable OPENAI001


683}717}

684```718```

685 719 

720```java

721import com.openai.client.OpenAIClient;

722import com.openai.client.okhttp.OpenAIOkHttpClient;

723import com.openai.models.responses.ResponseCreateParams;

724import com.openai.models.responses.ResponseInputFile;

725import com.openai.models.responses.ResponseInputItem;

726import java.util.List;

727 

728ResponseCreateParams params =

729 ResponseCreateParams.builder()

730 .model("gpt-5.6")

731 .inputOfResponse(

732 List.of(

733 ResponseInputItem.ofMessage(

734 ResponseInputItem.Message.builder()

735 .role(ResponseInputItem.Message.Role.USER)

736 .addInputTextContent(

737 "Analyze the letter and provide a summary of the key points.")

738 .addContent(

739 ResponseInputFile.builder()

740 .fileUrl(

741 "https://www.berkshirehathaway.com/letters/2024ltr.pdf")

742 .build())

743 .build())))

744 .build();

745 

746client.responses().create(params).output().stream()

747 .flatMap(item -> item.message().stream())

748 .flatMap(message -> message.content().stream())

749 .flatMap(content -> content.outputText().stream())

750 .forEach(text -> System.out.println(text.text()));

751```

752 

686```csharp753```csharp

687using OpenAI.Responses;754using OpenAI.Responses;

688#pragma warning disable OPENAI001755#pragma warning disable OPENAI001


889}956}

890```957```

891 958 

959```java

960import com.openai.client.OpenAIClient;

961import com.openai.client.okhttp.OpenAIOkHttpClient;

962import com.openai.models.files.FileCreateParams;

963import com.openai.models.files.FilePurpose;

964import com.openai.models.responses.ResponseCreateParams;

965import com.openai.models.responses.ResponseInputFile;

966import com.openai.models.responses.ResponseInputItem;

967import java.nio.file.Path;

968import java.util.List;

969 

970var file =

971 client

972 .files()

973 .create(

974 FileCreateParams.builder()

975 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))

976 .purpose(FilePurpose.USER_DATA)

977 .build());

978 

979var response =

980 client

981 .responses()

982 .create(

983 ResponseCreateParams.builder()

984 .model("gpt-5.6")

985 .inputOfResponse(

986 List.of(

987 ResponseInputItem.ofMessage(

988 ResponseInputItem.Message.builder()

989 .role(ResponseInputItem.Message.Role.USER)

990 .addContent(

991 ResponseInputFile.builder().fileId(file.id()).build())

992 .addInputTextContent("What is the first dragon in the book?")

993 .build())))

994 .build());

995response.output().stream()

996 .flatMap(item -> item.message().stream())

997 .flatMap(message -> message.content().stream())

998 .flatMap(content -> content.outputText().stream())

999 .forEach(text -> System.out.println(text.text()));

1000```

1001 

892```csharp1002```csharp

893using OpenAI.Files;1003using OpenAI.Files;

894using OpenAI.Responses;1004using OpenAI.Responses;


1055}1165}

1056```1166```

1057 1167 

1168```java

1169import com.openai.client.OpenAIClient;

1170import com.openai.client.okhttp.OpenAIOkHttpClient;

1171import com.openai.models.responses.ResponseCreateParams;

1172import com.openai.models.responses.WebSearchTool;

1173 

1174ResponseCreateParams params =

1175 ResponseCreateParams.builder()

1176 .model("gpt-5.6")

1177 .input("What was a positive news story from today?")

1178 .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())

1179 .build();

1180 

1181client.responses().create(params).output().stream()

1182 .flatMap(item -> item.message().stream())

1183 .flatMap(message -> message.content().stream())

1184 .flatMap(content -> content.outputText().stream())

1185 .forEach(text -> System.out.println(text.text()));

1186```

1187 

1058```csharp1188```csharp

1059using OpenAI.Responses;1189using OpenAI.Responses;

1060#pragma warning disable OPENAI0011190#pragma warning disable OPENAI001


1173}1303}

1174```1304```

1175 1305 

1306```java

1307import com.openai.client.OpenAIClient;

1308import com.openai.client.okhttp.OpenAIOkHttpClient;

1309import com.openai.models.responses.ResponseCreateParams;

1310import java.util.List;

1311 

1312String vectorStoreId = "<vector_store_id>";

1313 

1314ResponseCreateParams params =

1315 ResponseCreateParams.builder()

1316 .model("gpt-5.6")

1317 .input("What is deep research by OpenAI?")

1318 .addFileSearchTool(List.of(vectorStoreId))

1319 .build();

1320 

1321client.responses().create(params).output().stream()

1322 .flatMap(item -> item.message().stream())

1323 .flatMap(message -> message.content().stream())

1324 .flatMap(content -> content.outputText().stream())

1325 .forEach(text -> System.out.println(text.text()));

1326```

1327 

1176```csharp1328```csharp

1177using OpenAI.Responses;1329using OpenAI.Responses;

1178#pragma warning disable OPENAI0011330#pragma warning disable OPENAI001


1284}1436}

1285```1437```

1286 1438 

1439```java

1440import com.openai.client.OpenAIClient;

1441import com.openai.client.okhttp.OpenAIOkHttpClient;

1442import com.openai.models.responses.ResponseCreateParams;

1443import com.openai.models.responses.Tool;

1444 

1445ResponseCreateParams params =

1446 ResponseCreateParams.builder()

1447 .model("gpt-5.6")

1448 .input("I need to solve the equation 3x + 11 = 14. Can you help me?")

1449 .instructions(

1450 "You are a personal math tutor. When asked a math question, write and run code to answer the question.")

1451 .addCodeInterpreterTool(

1452 Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder().build())

1453 .build();

1454 

1455client.responses().create(params).output().stream()

1456 .flatMap(item -> item.message().stream())

1457 .flatMap(message -> message.content().stream())

1458 .flatMap(content -> content.outputText().stream())

1459 .forEach(text -> System.out.println(text.text()));

1460```

1461 

1287```ruby1462```ruby

1288require "openai"1463require "openai"

1289 1464 


1443}1618}

1444```1619```

1445 1620 

1621```java

1622import com.openai.client.OpenAIClient;

1623import com.openai.client.okhttp.OpenAIOkHttpClient;

1624import com.openai.core.JsonValue;

1625import com.openai.models.responses.FunctionTool;

1626import com.openai.models.responses.ResponseCreateParams;

1627import java.util.List;

1628import java.util.Map;

1629 

1630ResponseCreateParams params =

1631 ResponseCreateParams.builder()

1632 .model("gpt-5.6")

1633 .input("What is the weather like in Paris today?")

1634 .addTool(

1635 FunctionTool.builder()

1636 .name("get_weather")

1637 .description("Get current temperature for a given location.")

1638 .parameters(

1639 FunctionTool.Parameters.builder()

1640 .putAdditionalProperty("type", JsonValue.from("object"))

1641 .putAdditionalProperty(

1642 "properties",

1643 JsonValue.from(

1644 Map.of(

1645 "location",

1646 Map.of(

1647 "type", "string",

1648 "description",

1649 "City and country e.g. Bogotá, Colombia"))))

1650 .putAdditionalProperty("required", JsonValue.from(List.of("location")))

1651 .putAdditionalProperty("additionalProperties", JsonValue.from(false))

1652 .build())

1653 .strict(true)

1654 .build())

1655 .build();

1656 

1657client.responses().create(params).output().forEach(System.out::println);

1658```

1659 

1446```csharp1660```csharp

1447using System.Text.Json;1661using System.Text.Json;

1448using System.Text.Json.Serialization.Metadata;1662using System.Text.Json.Serialization.Metadata;


1661}1875}

1662```1876```

1663 1877 

1878```java

1879import com.openai.client.OpenAIClient;

1880import com.openai.client.okhttp.OpenAIOkHttpClient;

1881import com.openai.models.responses.ResponseCreateParams;

1882import com.openai.models.responses.Tool;

1883 

1884ResponseCreateParams params =

1885 ResponseCreateParams.builder()

1886 .model("gpt-5.6")

1887 .input("Roll 2d4+1")

1888 .addTool(

1889 Tool.Mcp.builder()

1890 .serverLabel("dmcp")

1891 .serverDescription(

1892 "A Dungeons and Dragons MCP server to assist with dice rolling.")

1893 .serverUrl("https://dmcp-server.deno.dev/mcp")

1894 .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)

1895 .build())

1896 .build();

1897 

1898client.responses().create(params).output().stream()

1899 .flatMap(item -> item.message().stream())

1900 .flatMap(message -> message.content().stream())

1901 .flatMap(content -> content.outputText().stream())

1902 .forEach(text -> System.out.println(text.text()));

1903```

1904 

1664```csharp1905```csharp

1665using OpenAI.Responses;1906using OpenAI.Responses;

1666#pragma warning disable OPENAI0011907#pragma warning disable OPENAI001


1791}2032}

1792```2033```

1793 2034 

2035```java

2036import com.openai.client.OpenAIClient;

2037import com.openai.client.okhttp.OpenAIOkHttpClient;

2038import com.openai.core.http.StreamResponse;

2039import com.openai.models.responses.ResponseCreateParams;

2040import com.openai.models.responses.ResponseStreamEvent;

2041 

2042ResponseCreateParams params =

2043 ResponseCreateParams.builder()

2044 .model("gpt-5.6")

2045 .input("Say 'double bubble bath' ten times fast.")

2046 .build();

2047 

2048try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {

2049 stream.stream().forEach(System.out::println);

2050}

2051```

2052 

1794```csharp2053```csharp

1795using OpenAI.Responses;2054using OpenAI.Responses;

1796#pragma warning disable OPENAI0012055#pragma warning disable OPENAI001