SpyBara
Go Premium

Documentation 2026-07-14 21:58 UTC to 2026-07-15 02:58 UTC

15 files changed +4,294 −30. View all changes and history on the product overview
2026
Wed 15 02:58 Tue 14 21:58 Mon 13 21:58 Sat 11 07:01 Fri 10 23:02 Thu 9 17:03 Wed 8 22:02 Mon 6 22:58 Sat 4 16:59
Details

166print(response.output_text)166print(response.output_text)

167```167```

168 168 

169```ruby

170require "openai"

171 

172openai = OpenAI::Client.new

173 

174response = openai.responses.create(

175 model: "gpt-5.6",

176 input: [

177 {

178 role: "user",

179 content: [

180 {

181 type: "input_text",

182 text: "Analyze the letter and provide a summary of the key points."

183 },

184 {

185 type: "input_file",

186 file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf"

187 }

188 ]

189 }

190 ]

191)

192 

193puts(response.output_text)

194```

195 

169```csharp196```csharp

170using OpenAI.Files;197using OpenAI.Files;

171using OpenAI.Responses;198using OpenAI.Responses;


293print(response.output_text)320print(response.output_text)

294```321```

295 322 

323```ruby

324require "openai"

325 

326openai = OpenAI::Client.new

327 

328file = openai.files.create(

329 file: File.open("draconomicon.pdf", "rb"),

330 purpose: "user_data"

331)

332 

333response = openai.responses.create(

334 model: "gpt-5.6",

335 input: [

336 {

337 role: "user",

338 content: [

339 {type: "input_file", file_id: file.id},

340 {type: "input_text", text: "What is the first dragon in the book?"}

341 ]

342 }

343 ]

344)

345 

346puts(response.output_text)

347```

348 

296```csharp349```csharp

297using OpenAI.Files;350using OpenAI.Files;

298using OpenAI.Responses;351using OpenAI.Responses;

Details

69 69 

70 70 

71 71 

72 Note that for reasoning models like GPT-5 or o4-mini, any reasoning items72 Complete tool calling example

73 

74```python

75from openai import OpenAI

76import json

77 

78client = OpenAI()

79 

80# 1. Define a list of callable tools for the model

81tools = [

82 {

83 "type": "function",

84 "name": "get_horoscope",

85 "description": "Get today's horoscope for an astrological sign.",

86 "parameters": {

87 "type": "object",

88 "properties": {

89 "sign": {

90 "type": "string",

91 "description": "An astrological sign like Taurus or Aquarius",

92 },

93 },

94 "required": ["sign"],

95 },

96 },

97]

98 

99def get_horoscope(sign):

100 return f"{sign}: Next Tuesday you will befriend a baby otter."

101 

102# Create a running input list we will add to over time

103input_list = [

104 {"role": "user", "content": "What is my horoscope? I am an Aquarius."}

105]

106 

107# 2. Prompt the model with tools defined

108response = client.responses.create(

109 model="gpt-5.6",

110 tools=tools,

111 input=input_list,

112)

113 

114# Save function call outputs for subsequent requests

115input_list += response.output

116 

117for item in response.output:

118 if item.type == "function_call":

119 if item.name == "get_horoscope":

120 # 3. Execute the function logic for get_horoscope

121 sign = json.loads(item.arguments)["sign"]

122 horoscope = get_horoscope(sign)

123

124 # 4. Provide function call results to the model

125 input_list.append({

126 "type": "function_call_output",

127 "call_id": item.call_id,

128 "output": horoscope,

129 })

130 

131print("Final input:")

132print(input_list)

133 

134response = client.responses.create(

135 model="gpt-5.6",

136 instructions="Respond only with a horoscope generated by a tool.",

137 tools=tools,

138 input=input_list,

139)

140 

141# 5. The model should be able to give a response!

142print("Final output:")

143print(response.model_dump_json(indent=2))

144print("\n" + response.output_text)

145```

146 

147```javascript

148import OpenAI from "openai";

149 

150const openai = new OpenAI();

151 

152// 1. Define a list of callable tools for the model

153const tools = [

154 {

155 type: "function",

156 name: "get_horoscope",

157 description: "Get today's horoscope for an astrological sign.",

158 parameters: {

159 type: "object",

160 properties: {

161 sign: {

162 type: "string",

163 description: "An astrological sign like Taurus or Aquarius",

164 },

165 },

166 required: ["sign"],

167 additionalProperties: false,

168 },

169 strict: true,

170 },

171];

172 

173function getHoroscope(sign) {

174 return `${sign}: Next Tuesday you will befriend a baby otter.`;

175}

176 

177// Create a running input list we will add to over time

178let input = [

179 { role: "user", content: "What is my horoscope? I am an Aquarius." },

180];

181 

182// 2. Prompt the model with tools defined

183let response = await openai.responses.create({

184 model: "gpt-5.6",

185 tools,

186 input,

187});

188 

189// Preserve model output for the next turn

190input.push(...response.output);

191 

192for (const item of response.output) {

193 if (item.type !== "function_call") continue;

194 

195 if (item.name === "get_horoscope") {

196 // 3. Execute the function logic for get_horoscope

197 const { sign } = JSON.parse(item.arguments);

198 const horoscope = getHoroscope(sign);

199 

200 // 4. Provide function call results to the model

201 input.push({

202 type: "function_call_output",

203 call_id: item.call_id,

204 output: horoscope,

205 });

206 }

207}

208 

209console.log("Final input:");

210console.log(JSON.stringify(input, null, 2));

211 

212response = await openai.responses.create({

213 model: "gpt-5.6",

214 instructions: "Respond only with a horoscope generated by a tool.",

215 tools,

216 input,

217});

218 

219// 5. The model should be able to give a response!

220console.log("Final output:");

221console.log(response.output_text);

222```

223 

224 

225 

226Note that for reasoning models like GPT-5 or o4-mini, any reasoning items

73 returned in model responses with tool calls must also be passed back with tool227 returned in model responses with tool calls must also be passed back with tool

74 call outputs.228 call outputs.

75 229 


201 355 

202The response `output` array contains an entry with the `type` having a value of `function_call`. Each entry with a `call_id` (used later to submit the function result), `name`, and JSON-encoded `arguments`.356The response `output` array contains an entry with the `type` having a value of `function_call`. Each entry with a `call_id` (used later to submit the function result), `name`, and JSON-encoded `arguments`.

203 357 

358Sample response with multiple function calls

359 

360```json

361[

362 {

363 "id": "fc_12345xyz",

364 "call_id": "call_12345xyz",

365 "type": "function_call",

366 "name": "get_weather",

367 "arguments": "{\"location\":\"Paris, France\"}"

368 },

369 {

370 "id": "fc_67890abc",

371 "call_id": "call_67890abc",

372 "type": "function_call",

373 "name": "get_weather",

374 "arguments": "{\"location\":\"Bogotá, Colombia\"}"

375 },

376 {

377 "id": "fc_99999def",

378 "call_id": "call_99999def",

379 "type": "function_call",

380 "name": "send_email",

381 "arguments": "{\"to\":\"bob@email.com\",\"body\":\"Hi bob\"}"

382 }

383]

384```

385 

386 

204If you are using [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search), you may also see `tool_search_call` and `tool_search_output` items before a `function_call`. Once the function is loaded, handle the function call in the same way shown here.387If you are using [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search), you may also see `tool_search_call` and `tool_search_output` items before a `function_call`. Once the function is loaded, handle the function call in the same way shown here.

205 388 

389Execute function calls and append results

390 

391```python

392for tool_call in response.output:

393 if tool_call.type != "function_call":

394 continue

395 

396 name = tool_call.name

397 args = json.loads(tool_call.arguments)

398 

399 result = call_function(name, args)

400 input_messages.append({

401 "type": "function_call_output",

402 "call_id": tool_call.call_id,

403 "output": str(result)

404 })

405```

406 

407```javascript

408for (const toolCall of response.output) {

409 if (toolCall.type !== "function_call") {

410 continue;

411 }

412 

413 const name = toolCall.name;

414 const args = JSON.parse(toolCall.arguments);

415 

416 const result = callFunction(name, args);

417 input.push({

418 type: "function_call_output",

419 call_id: toolCall.call_id,

420 output: result.toString()

421 });

422}

423```

424 

425 

426 

206In the example above, we have a hypothetical `call_function` to route each call. Here’s a possible implementation:427In the example above, we have a hypothetical `call_function` to route each call. Here’s a possible implementation:

207 428 

429Execute function calls and append results

430 

431```python

432def call_function(name, args):

433 if name == "get_weather":

434 return get_weather(**args)

435 if name == "send_email":

436 return send_email(**args)

437```

438 

439```javascript

440const callFunction = async (name, args) => {

441 if (name === "get_weather") {

442 return getWeather(args.latitude, args.longitude);

443 }

444 if (name === "send_email") {

445 return sendEmail(args.to, args.body);

446 }

447};

448```

449 

450 

208### Formatting results451### Formatting results

209 452 

210The result you pass in the `function_call_output` message should typically be a string, where the format is up to you (JSON, error codes, plain text, etc.). The model will interpret that string as needed.453The result you pass in the `function_call_output` message should typically be a string, where the format is up to you (JSON, error codes, plain text, etc.). The model will interpret that string as needed.


219 462 

220After appending the results to your `input`, you can send them back to the model to get a final response.463After appending the results to your `input`, you can send them back to the model to get a final response.

221 464 

465Send results back to model

466 

467```python

468response = client.responses.create(

469 model="gpt-5.6",

470 input=input_messages,

471 tools=tools,

472)

473```

474 

475```javascript

476const response = await openai.responses.create({

477 model: "gpt-5.6",

478 input,

479 tools,

480});

481```

482 

483 

484 

485Final response

486 

487```json

488"It's about 15°C in Paris, 18°C in Bogotá, and I've sent that email to Bob."

489```

490 

491 

222## Additional configurations492## Additional configurations

223 493 

224### Tool choice494### Tool choice


292 562 

293<div data-content-switcher-pane data-value="enabled">563<div data-content-switcher-pane data-value="enabled">

294 <div class="hidden">Strict mode enabled</div>564 <div class="hidden">Strict mode enabled</div>

565 ```json

566{

567 "type": "function",

568 "name": "get_weather",

569 "description": "Retrieves current weather for the given location.",

570 //highlight-start

571 "strict": true,

572 //highlight-end

573 "parameters": {

574 "type": "object",

575 "properties": {

576 "location": {

577 "type": "string",

578 "description": "City and country e.g. Bogotá, Colombia"

579 },

580 "units": {

581 //highlight-start

582 "type": ["string", "null"],

583 //highlight-end

584 "enum": ["celsius", "fahrenheit"],

585 "description": "Units the temperature will be returned in."

586 }

587 },

588 //highlight-start

589 "required": ["location", "units"],

590 "additionalProperties": false

591 //highlight-end

592 }

593}

594```

595 

295 </div>596 </div>

296 <div data-content-switcher-pane data-value="disabled" hidden>597 <div data-content-switcher-pane data-value="disabled" hidden>

297 <div class="hidden">Strict mode disabled</div>598 <div class="hidden">Strict mode disabled</div>

599 ```json

600{

601 "type": "function",

602 "name": "get_weather",

603 "description": "Retrieves current weather for the given location.",

604 "parameters": {

605 "type": "object",

606 "properties": {

607 "location": {

608 "type": "string",

609 "description": "City and country e.g. Bogotá, Colombia"

610 },

611 "units": {

612 //highlight-start

613 "type": "string",

614 //highlight-end

615 "enum": ["celsius", "fahrenheit"],

616 "description": "Units the temperature will be returned in."

617 }

618 },

619 //highlight-start

620 "required": ["location"],

621 //highlight-end

622 }

623}

624```

625 

298 </div>626 </div>

299 627 

300 628 


321 649 

322Streaming function calls is very similar to streaming regular responses: you set `stream` to `true` and get different `event` objects.650Streaming function calls is very similar to streaming regular responses: you set `stream` to `true` and get different `event` objects.

323 651 

652Streaming function calls

653 

654```python

655from openai import OpenAI

656 

657client = OpenAI()

658 

659tools = [{

660 "type": "function",

661 "name": "get_weather",

662 "description": "Get current temperature for a given location.",

663 "parameters": {

664 "type": "object",

665 "properties": {

666 "location": {

667 "type": "string",

668 "description": "City and country e.g. Bogotá, Colombia"

669 }

670 },

671 "required": [

672 "location"

673 ],

674 "additionalProperties": False

675 }

676}]

677 

678stream = client.responses.create(

679 model="gpt-5.6",

680 input=[{"role": "user", "content": "What's the weather like in Paris today?"}],

681 tools=tools,

682 stream=True

683)

684 

685for event in stream:

686 print(event)

687```

688 

689```javascript

690import { OpenAI } from "openai";

691 

692const openai = new OpenAI();

693 

694const tools = [{

695 type: "function",

696 name: "get_weather",

697 description: "Get current temperature for provided coordinates in celsius.",

698 parameters: {

699 type: "object",

700 properties: {

701 latitude: { type: "number" },

702 longitude: { type: "number" }

703 },

704 required: ["latitude", "longitude"],

705 additionalProperties: false

706 },

707 strict: true

708}];

709 

710const stream = await openai.responses.create({

711 model: "gpt-5.6",

712 input: [{ role: "user", content: "What's the weather like in Paris today?" }],

713 tools,

714 stream: true,

715 store: true,

716});

717 

718for await (const event of stream) {

719 console.log(event)

720}

721```

722 

723 

724Output events

725 

726```json

727{"type":"response.output_item.added","response_id":"resp_1234xyz","output_index":0,"item":{"type":"function_call","id":"fc_1234xyz","call_id":"call_1234xyz","name":"get_weather","arguments":""}}

728{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"{\""}

729{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"location"}

730{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"\":\""}

731{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"Paris"}

732{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":","}

733{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":" France"}

734{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"\"}"}

735{"type":"response.function_call_arguments.done","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"arguments":"{\"location\":\"Paris, France\"}"}

736{"type":"response.output_item.done","response_id":"resp_1234xyz","output_index":0,"item":{"type":"function_call","id":"fc_1234xyz","call_id":"call_1234xyz","name":"get_weather","arguments":"{\"location\":\"Paris, France\"}"}}

737```

738 

739 

324Instead of aggregating chunks into a single `content` string, however, you're aggregating chunks into an encoded `arguments` JSON object.740Instead of aggregating chunks into a single `content` string, however, you're aggregating chunks into an encoded `arguments` JSON object.

325 741 

326When the model calls one or more functions an event of type `response.output_item.added` will be emitted for each function call that contains the following fields:742When the model calls one or more functions an event of type `response.output_item.added` will be emitted for each function call that contains the following fields:


342 758 

343Below is a code snippet demonstrating how to aggregate the `delta`s into a final `tool_call` object.759Below is a code snippet demonstrating how to aggregate the `delta`s into a final `tool_call` object.

344 760 

761Accumulating tool_call deltas

762 

763```python

764final_tool_calls = {}

765 

766for event in stream:

767 if event.type === 'response.output_item.added':

768 final_tool_calls[event.output_index] = event.item;

769 elif event.type === 'response.function_call_arguments.delta':

770 index = event.output_index

771 

772 if final_tool_calls[index]:

773 final_tool_calls[index].arguments += event.delta

774```

775 

776```javascript

777const finalToolCalls = {};

778 

779for await (const event of stream) {

780 if (event.type === 'response.output_item.added') {

781 finalToolCalls[event.output_index] = event.item;

782 } else if (event.type === 'response.function_call_arguments.delta') {

783 const index = event.output_index;

784 

785 if (finalToolCalls[index]) {

786 finalToolCalls[index].arguments += event.delta;

787 }

788 }

789}

790```

791 

792 

793Accumulated final_tool_calls[0]

794 

795```json

796{

797 "type": "function_call",

798 "id": "fc_1234xyz",

799 "call_id": "call_2345abc",

800 "name": "get_weather",

801 "arguments": "{\"location\":\"Paris, France\"}"

802}

803```

804 

805 

345When the model has finished calling the functions an event of type `response.function_call_arguments.done` will be emitted. This event contains the entire function call including the following fields:806When the model has finished calling the functions an event of type `response.function_call_arguments.done` will be emitted. This event contains the entire function call including the following fields:

346 807 

347| Field | Description |808| Field | Description |


358 819 

359The following code sample shows creating a custom tool that expects to receive a string of text containing Python code as a response.820The following code sample shows creating a custom tool that expects to receive a string of text containing Python code as a response.

360 821 

822Custom tool calling example

823 

824```python

825from openai import OpenAI

826 

827client = OpenAI()

828 

829response = client.responses.create(

830 model="gpt-5.6",

831 input="Use the code_exec tool to print hello world to the console.",

832 tools=[

833 {

834 "type": "custom",

835 "name": "code_exec",

836 "description": "Executes arbitrary Python code.",

837 }

838 ]

839)

840print(response.output)

841```

842 

843```javascript

844import OpenAI from "openai";

845const client = new OpenAI();

846 

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

848 model: "gpt-5.6",

849 input: "Use the code_exec tool to print hello world to the console.",

850 tools: [

851 {

852 type: "custom",

853 name: "code_exec",

854 description: "Executes arbitrary Python code.",

855 },

856 ],

857});

858 

859console.log(response.output);

860```

861 

862 

361Just as before, the `output` array will contain a tool call generated by the model. Except this time, the tool call input is given as plain text.863Just as before, the `output` array will contain a tool call generated by the model. Except this time, the tool call input is given as plain text.

362 864 

363```json865```json


387 889 

388#### Lark CFG890#### Lark CFG

389 891 

892Lark context free grammar example

893 

894```python

895from openai import OpenAI

896 

897client = OpenAI()

898 

899grammar = """

900start: expr

901expr: term (SP ADD SP term)* -> add

902| term

903term: factor (SP MUL SP factor)* -> mul

904| factor

905factor: INT

906SP: " "

907ADD: "+"

908MUL: "*"

909%import common.INT

910"""

911 

912response = client.responses.create(

913 model="gpt-5.6",

914 input="Use the math_exp tool to add four plus four.",

915 tools=[

916 {

917 "type": "custom",

918 "name": "math_exp",

919 "description": "Creates valid mathematical expressions",

920 "format": {

921 "type": "grammar",

922 "syntax": "lark",

923 "definition": grammar,

924 },

925 }

926 ]

927)

928print(response.output)

929```

930 

931```javascript

932import OpenAI from "openai";

933const client = new OpenAI();

934 

935const grammar = `

936start: expr

937expr: term (SP ADD SP term)* -> add

938| term

939term: factor (SP MUL SP factor)* -> mul

940| factor

941factor: INT

942SP: " "

943ADD: "+"

944MUL: "*"

945%import common.INT

946`;

947 

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

949 model: "gpt-5.6",

950 input: "Use the math_exp tool to add four plus four.",

951 tools: [

952 {

953 type: "custom",

954 name: "math_exp",

955 description: "Creates valid mathematical expressions",

956 format: {

957 type: "grammar",

958 syntax: "lark",

959 definition: grammar,

960 },

961 },

962 ],

963});

964 

965console.log(response.output);

966```

967 

968 

390The output from the tool should then conform to the Lark CFG that you defined:969The output from the tool should then conform to the Lark CFG that you defined:

391 970 

392```json971```json


495 1074 

496#### Regex CFG1075#### Regex CFG

497 1076 

1077Regex context free grammar example

1078 

1079```python

1080from openai import OpenAI

1081 

1082client = OpenAI()

1083 

1084grammar = r"^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$"

1085 

1086response = client.responses.create(

1087 model="gpt-5.6",

1088 input="Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",

1089 tools=[

1090 {

1091 "type": "custom",

1092 "name": "timestamp",

1093 "description": "Saves a timestamp in date + time in 24-hr format.",

1094 "format": {

1095 "type": "grammar",

1096 "syntax": "regex",

1097 "definition": grammar,

1098 },

1099 }

1100 ]

1101)

1102print(response.output)

1103```

1104 

1105```javascript

1106import OpenAI from "openai";

1107const client = new OpenAI();

1108 

1109const grammar = "^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$";

1110 

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

1112 model: "gpt-5.6",

1113 input: "Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",

1114 tools: [

1115 {

1116 type: "custom",

1117 name: "timestamp",

1118 description: "Saves a timestamp in date + time in 24-hr format.",

1119 format: {

1120 type: "grammar",

1121 syntax: "regex",

1122 definition: grammar,

1123 },

1124 },

1125 ],

1126});

1127 

1128console.log(response.output);

1129```

1130 

1131 

498The output from the tool should then conform to the Regex CFG that you defined:1132The output from the tool should then conform to the Regex CFG that you defined:

499 1133 

500```json1134```json

Details

6 6 

7Here's a simple example using the [Responses API](https://developers.openai.com/api/docs/api-reference/responses).7Here's a simple example using the [Responses API](https://developers.openai.com/api/docs/api-reference/responses).

8 8 

9Generate text from a simple prompt

10 

11```javascript

12import OpenAI from "openai";

13const client = new OpenAI();

14 

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

16 model: "gpt-5.6",

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

18});

19 

20console.log(response.output_text);

21```

22 

23```python

24from openai import OpenAI

25client = OpenAI()

26 

27response = client.responses.create(

28 model="gpt-5.6",

29 input="Write a one-sentence bedtime story about a unicorn."

30)

31 

32print(response.output_text)

33```

34 

35```cli

36openai responses create \

37 --model "gpt-5.6" \

38 --input "Write a one-sentence bedtime story about a unicorn." \

39 --raw-output \

40 --transform 'output.#(type=="message").content.0.text'

41```

42 

43```csharp

44using System;

45using System.Threading.Tasks;

46using OpenAI;

47 

48class Program

49{

50 static async Task Main()

51 {

52 var client = new OpenAIClient(

53 Environment.GetEnvironmentVariable("OPENAI_API_KEY")

54 );

55 

56 var response = await client.Responses.CreateAsync(new ResponseCreateRequest

57 {

58 Model = "gpt-5.6",

59 Input = "Say 'this is a test.'"

60 });

61 

62 Console.WriteLine($"[ASSISTANT]: {response.OutputText()}");

63 }

64}

65```

66 

67```java

68import com.openai.client.OpenAIClient;

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

70import com.openai.models.responses.Response;

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

72 

73public class Main {

74 public static void main(String[] args) {

75 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

76 

77 ResponseCreateParams params = ResponseCreateParams.builder()

78 .input("Say this is a test")

79 .model("gpt-5.6")

80 .build();

81 

82 Response response = client.responses().create(params);

83 System.out.println(response.outputText());

84 }

85}

86```

87 

88```go

89package main

90 

91import (

92 "context"

93 "fmt"

94 

95 "github.com/openai/openai-go/v3"

96 "github.com/openai/openai-go/v3/option"

97 "github.com/openai/openai-go/v3/responses"

98)

99 

100func main() {

101 client := openai.NewClient(

102 option.WithAPIKey("My API Key"), // or set OPENAI_API_KEY in your env

103 )

104 

105 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

106 Model: "gpt-5.6",

107 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

108 })

109 if err != nil {

110 panic(err.Error())

111 }

112 

113 fmt.Println(resp.OutputText())

114}

115```

116 

117```ruby

118require "openai"

119 

120openai = OpenAI::Client.new

121 

122response = openai.responses.create(

123 model: "gpt-5.6",

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

125)

126 

127puts(response.output_text)

128```

129 

130```bash

131curl "https://api.openai.com/v1/responses" \

132 -H "Content-Type: application/json" \

133 -H "Authorization: Bearer $OPENAI_API_KEY" \

134 -d '{

135 "model": "gpt-5.6",

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

137 }'

138```

139 

140 

9An array of content generated by the model is in the `output` property of the response. In this simple example, we have just one output which looks like this:141An array of content generated by the model is in the `output` property of the response. In this simple example, we have just one output which looks like this:

10 142 

11```json143```json

Details

23 23 

24<div data-content-switcher-pane data-value="text-out">24<div data-content-switcher-pane data-value="text-out">

25 <div class="hidden">Text-out</div>25 <div class="hidden">Text-out</div>

26 Text meta-prompt

27 

28```python

29from openai import OpenAI

30 

31client = OpenAI()

32 

33META_PROMPT = """

34Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.

35 

36# Guidelines

37 

38- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

39- 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.

40- 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!

41 - 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.

42 - Conclusion, classifications, or results should ALWAYS appear last.

43- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

44 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

45- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

46- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.

47- 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.

48- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

49- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)

50 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.

51 - JSON should never be wrapped in code blocks (```) unless explicitly requested.

52 

53The 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 "---")

54 

55[Concise instruction describing the task - this should be the first line in the prompt, no section header]

56 

57[Additional details as needed.]

58 

59[Optional sections with headings or bullet points for detailed steps.]

60 

61# Steps [optional]

62 

63[optional: a detailed breakdown of the steps necessary to accomplish the task]

64 

65# Output Format

66 

67[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]

68 

69# Examples [optional]

70 

71[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.]

72[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! ]

73 

74# Notes [optional]

75 

76[optional: edge cases, details, and an area to call or repeat out specific important considerations]

77""".strip()

78 

79def generate_prompt(task_or_prompt: str):

80 completion = client.chat.completions.create(

81 model="gpt-5.6",

82 messages=[

83 {

84 "role": "system",

85 "content": META_PROMPT,

86 },

87 {

88 "role": "user",

89 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,

90 },

91 ],

92 )

93 

94 return completion.choices[0].message.content

95```

96 

26 </div>97 </div>

27 <div data-content-switcher-pane data-value="audio-out" hidden>98 <div data-content-switcher-pane data-value="audio-out" hidden>

28 <div class="hidden">Audio-out</div>99 <div class="hidden">Audio-out</div>

100 Audio meta-prompt

101 

102```python

103from openai import OpenAI

104 

105client = OpenAI()

106 

107META_PROMPT = """

108Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.

109 

110# Guidelines

111 

112- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

113- 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.

114- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.

115- 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.

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 - It is very important that any examples included reflect the short, conversational output responses of the model.

119Keep 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.

120 - 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.

121 - 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.

122- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

123- 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.

124- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

125 

126The 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# Examples [optional]

135 

136[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.]

137[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! ]

138 

139# Notes [optional]

140 

141[optional: edge cases, details, and an area to call or repeat out specific important considerations]

142""".strip()

143 

144def generate_prompt(task_or_prompt: str):

145 completion = client.chat.completions.create(

146 model="gpt-5.6",

147 messages=[

148 {

149 "role": "system",

150 "content": META_PROMPT,

151 },

152 {

153 "role": "user",

154 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,

155 },

156 ],

157 )

158 

159 return completion.choices[0].message.content

160```

161 

29 </div>162 </div>

30 163 

31 164 


38 171 

39<div data-content-switcher-pane data-value="text-out">172<div data-content-switcher-pane data-value="text-out">

40 <div class="hidden">Text-out</div>173 <div class="hidden">Text-out</div>

174 Text meta-prompt for edits

175 

176```python

177from openai import OpenAI

178 

179client = OpenAI()

180 

181META_PROMPT = """

182Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.

183 

184Your 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:

185<reasoning>

186- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)

187- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?

188 - Identify: (max 10 words) if so, which section(s) utilize reasoning?

189 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?

190 - Ordering: (before/after) is the chain of though located before or after

191- Structure: (yes/no) does the input prompt have a well defined structure

192- Examples: (yes/no) does the input prompt have few-shot examples

193 - Representative: (1-5) if present, how representative are the examples?

194- Complexity: (1-5) how complex is the input prompt?

195 - Task: (1-5) how complex is the implied task?

196 - Necessity: ()

197- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)

198- Prioritization: (list) what 1-3 categories are the MOST important to address.

199- 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

200</reasoning>

201

202# Guidelines

203 

204- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

205- 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.

206- 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!

207 - 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.

208 - Conclusion, classifications, or results should ALWAYS appear last.

209- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

210 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

211- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

212- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.

213- 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.

214- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

215- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)

216 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.

217 - JSON should never be wrapped in code blocks (```) unless explicitly requested.

218 

219The 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 "---")

220 

221[Concise instruction describing the task - this should be the first line in the prompt, no section header]

222 

223[Additional details as needed.]

224 

225[Optional sections with headings or bullet points for detailed steps.]

226 

227# Steps [optional]

228 

229[optional: a detailed breakdown of the steps necessary to accomplish the task]

230 

231# Output Format

232 

233[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]

234 

235# Examples [optional]

236 

237[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.]

238[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! ]

239 

240# Notes [optional]

241 

242[optional: edge cases, details, and an area to call or repeat out specific important considerations]

243[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]

244""".strip()

245 

246def generate_prompt(task_or_prompt: str):

247 completion = client.chat.completions.create(

248 model="gpt-5.6",

249 messages=[

250 {

251 "role": "system",

252 "content": META_PROMPT,

253 },

254 {

255 "role": "user",

256 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,

257 },

258 ],

259 )

260 

261 return completion.choices[0].message.content

262```

263 

41 </div>264 </div>

42 <div data-content-switcher-pane data-value="audio-out" hidden>265 <div data-content-switcher-pane data-value="audio-out" hidden>

43 <div class="hidden">Audio-out</div>266 <div class="hidden">Audio-out</div>

267 Audio meta-prompt for edits

268 

269```python

270from openai import OpenAI

271 

272client = OpenAI()

273 

274META_PROMPT = """

275Given 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.

276 

277Your 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:

278<reasoning>

279- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)

280- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?

281 - Identify: (max 10 words) if so, which section(s) utilize reasoning?

282 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?

283 - Ordering: (before/after) is the chain of though located before or after

284- Structure: (yes/no) does the input prompt have a well defined structure

285- Examples: (yes/no) does the input prompt have few-shot examples

286 - Representative: (1-5) if present, how representative are the examples?

287- Complexity: (1-5) how complex is the input prompt?

288 - Task: (1-5) how complex is the implied task?

289 - Necessity: ()

290- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)

291- Prioritization: (list) what 1-3 categories are the MOST important to address.

292- 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

293</reasoning>

294 

295# Guidelines

296 

297- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.

298- 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.

299- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.

300- 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.

301- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.

302 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.

303 - It is very important that any examples included reflect the short, conversational output responses of the model.

304Keep 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.

305 - 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.

306 - 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.

307- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.

308- 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.

309- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.

310 

311The 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 "---")

312 

313[Concise instruction describing the task - this should be the first line in the prompt, no section header]

314 

315[Additional details as needed.]

316 

317[Optional sections with headings or bullet points for detailed steps.]

318 

319# Examples [optional]

320 

321[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.]

322[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! ]

323 

324# Notes [optional]

325 

326[optional: edge cases, details, and an area to call or repeat out specific important considerations]

327[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]

328""".strip()

329 

330def generate_prompt(task_or_prompt: str):

331 completion = client.chat.completions.create(

332 model="gpt-5.6",

333 messages=[

334 {

335 "role": "system",

336 "content": META_PROMPT,

337 },

338 {

339 "role": "user",

340 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,

341 },

342 ],

343 )

344 

345 return completion.choices[0].message.content

346```

347 

44 </div>348 </div>

45 349 

46 350 


101 405 

102<div data-content-switcher-pane data-value="structured-output">406<div data-content-switcher-pane data-value="structured-output">

103 <div class="hidden">Structured output schema</div>407 <div class="hidden">Structured output schema</div>

408 Structured output meta-schema

409 

410```python

411from openai import OpenAI

412import json

413 

414client = OpenAI()

415 

416META_SCHEMA = {

417 "name": "metaschema",

418 "schema": {

419 "type": "object",

420 "properties": {

421 "name": {

422 "type": "string",

423 "description": "The name of the schema"

424 },

425 "type": {

426 "type": "string",

427 "enum": [

428 "object",

429 "array",

430 "string",

431 "number",

432 "boolean",

433 "null"

434 ]

435 },

436 "properties": {

437 "type": "object",

438 "additionalProperties": {

439 "$ref": "#/$defs/schema_definition"

440 }

441 },

442 "items": {

443 "anyOf": [

444 {

445 "$ref": "#/$defs/schema_definition"

446 },

447 {

448 "type": "array",

449 "items": {

450 "$ref": "#/$defs/schema_definition"

451 }

452 }

453 ]

454 },

455 "required": {

456 "type": "array",

457 "items": {

458 "type": "string"

459 }

460 },

461 "additionalProperties": {

462 "type": "boolean"

463 }

464 },

465 "required": [

466 "type"

467 ],

468 "additionalProperties": False,

469 "if": {

470 "properties": {

471 "type": {

472 "const": "object"

473 }

474 }

475 },

476 "then": {

477 "required": [

478 "properties"

479 ]

480 },

481 "$defs": {

482 "schema_definition": {

483 "type": "object",

484 "properties": {

485 "type": {

486 "type": "string",

487 "enum": [

488 "object",

489 "array",

490 "string",

491 "number",

492 "boolean",

493 "null"

494 ]

495 },

496 "properties": {

497 "type": "object",

498 "additionalProperties": {

499 "$ref": "#/$defs/schema_definition"

500 }

501 },

502 "items": {

503 "anyOf": [

504 {

505 "$ref": "#/$defs/schema_definition"

506 },

507 {

508 "type": "array",

509 "items": {

510 "$ref": "#/$defs/schema_definition"

511 }

512 }

513 ]

514 },

515 "required": {

516 "type": "array",

517 "items": {

518 "type": "string"

519 }

520 },

521 "additionalProperties": {

522 "type": "boolean"

523 }

524 },

525 "required": [

526 "type"

527 ],

528 "additionalProperties": False,

529 "if": {

530 "properties": {

531 "type": {

532 "const": "object"

533 }

534 }

535 },

536 "then": {

537 "required": [

538 "properties"

539 ]

540 }

541 }

542 }

543 }

544}

545 

546META_PROMPT = """

547# Instructions

548Return a valid schema for the described JSON.

549 

550You must also make sure:

551- all fields in an object are set as required

552- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED

553- all objects must have additionalProperties set to false

554 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties

555- all objects must have properties defined

556- field order matters. any form of "thinking" or "explanation" should come before the conclusion

557- $defs must be defined under the schema param

558 

559Notable keywords NOT supported include:

560- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties

561- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems

562 

563Other notes:

564- definitions and recursion are supported

565- only if necessary to include references e.g. "$defs", it must be inside the "schema" object

566 

567# Examples

568Input: Generate a math reasoning schema with steps and a final answer.

569Output: {

570 "name": "math_reasoning",

571 "type": "object",

572 "properties": {

573 "steps": {

574 "type": "array",

575 "description": "A sequence of steps involved in solving the math problem.",

576 "items": {

577 "type": "object",

578 "properties": {

579 "explanation": {

580 "type": "string",

581 "description": "Description of the reasoning or method used in this step."

582 },

583 "output": {

584 "type": "string",

585 "description": "Result or outcome of this specific step."

586 }

587 },

588 "required": [

589 "explanation",

590 "output"

591 ],

592 "additionalProperties": false

593 }

594 },

595 "final_answer": {

596 "type": "string",

597 "description": "The final solution or answer to the math problem."

598 }

599 },

600 "required": [

601 "steps",

602 "final_answer"

603 ],

604 "additionalProperties": false

605}

606 

607Input: Give me a linked list

608Output: {

609 "name": "linked_list",

610 "type": "object",

611 "properties": {

612 "linked_list": {

613 "$ref": "#/$defs/linked_list_node",

614 "description": "The head node of the linked list."

615 }

616 },

617 "$defs": {

618 "linked_list_node": {

619 "type": "object",

620 "description": "Defines a node in a singly linked list.",

621 "properties": {

622 "value": {

623 "type": "number",

624 "description": "The value stored in this node."

625 },

626 "next": {

627 "anyOf": [

628 {

629 "$ref": "#/$defs/linked_list_node"

630 },

631 {

632 "type": "null"

633 }

634 ],

635 "description": "Reference to the next node; null if it is the last node."

636 }

637 },

638 "required": [

639 "value",

640 "next"

641 ],

642 "additionalProperties": false

643 }

644 },

645 "required": [

646 "linked_list"

647 ],

648 "additionalProperties": false

649}

650 

651Input: Dynamically generated UI

652Output: {

653 "name": "ui",

654 "type": "object",

655 "properties": {

656 "type": {

657 "type": "string",

658 "description": "The type of the UI component",

659 "enum": [

660 "div",

661 "button",

662 "header",

663 "section",

664 "field",

665 "form"

666 ]

667 },

668 "label": {

669 "type": "string",

670 "description": "The label of the UI component, used for buttons or form fields"

671 },

672 "children": {

673 "type": "array",

674 "description": "Nested UI components",

675 "items": {

676 "$ref": "#"

677 }

678 },

679 "attributes": {

680 "type": "array",

681 "description": "Arbitrary attributes for the UI component, suitable for any element",

682 "items": {

683 "type": "object",

684 "properties": {

685 "name": {

686 "type": "string",

687 "description": "The name of the attribute, for example onClick or className"

688 },

689 "value": {

690 "type": "string",

691 "description": "The value of the attribute"

692 }

693 },

694 "required": [

695 "name",

696 "value"

697 ],

698 "additionalProperties": false

699 }

700 }

701 },

702 "required": [

703 "type",

704 "label",

705 "children",

706 "attributes"

707 ],

708 "additionalProperties": false

709}

710""".strip()

711 

712def generate_schema(description: str):

713 completion = client.chat.completions.create(

714 model="gpt-5.6-terra",

715 response_format={"type": "json_schema", "json_schema": META_SCHEMA},

716 messages=[

717 {

718 "role": "system",

719 "content": META_PROMPT,

720 },

721 {

722 "role": "user",

723 "content": "Description:\n" + description,

724 },

725 ],

726 )

727 

728 return json.loads(completion.choices[0].message.content)

729```

730 

104 </div>731 </div>

105 <div data-content-switcher-pane data-value="function" hidden>732 <div data-content-switcher-pane data-value="function" hidden>

106 <div class="hidden">Function schema</div>733 <div class="hidden">Function schema</div>

734 Structured output meta-schema

735 

736```python

737from openai import OpenAI

738import json

739 

740client = OpenAI()

741 

742META_SCHEMA = {

743 "name": "function-metaschema",

744 "schema": {

745 "type": "object",

746 "properties": {

747 "name": {

748 "type": "string",

749 "description": "The name of the function"

750 },

751 "description": {

752 "type": "string",

753 "description": "A description of what the function does"

754 },

755 "parameters": {

756 "$ref": "#/$defs/schema_definition",

757 "description": "A JSON schema that defines the function's parameters"

758 }

759 },

760 "required": [

761 "name",

762 "description",

763 "parameters"

764 ],

765 "additionalProperties": False,

766 "$defs": {

767 "schema_definition": {

768 "type": "object",

769 "properties": {

770 "type": {

771 "type": "string",

772 "enum": [

773 "object",

774 "array",

775 "string",

776 "number",

777 "boolean",

778 "null"

779 ]

780 },

781 "properties": {

782 "type": "object",

783 "additionalProperties": {

784 "$ref": "#/$defs/schema_definition"

785 }

786 },

787 "items": {

788 "anyOf": [

789 {

790 "$ref": "#/$defs/schema_definition"

791 },

792 {

793 "type": "array",

794 "items": {

795 "$ref": "#/$defs/schema_definition"

796 }

797 }

798 ]

799 },

800 "required": {

801 "type": "array",

802 "items": {

803 "type": "string"

804 }

805 },

806 "additionalProperties": {

807 "type": "boolean"

808 }

809 },

810 "required": [

811 "type"

812 ],

813 "additionalProperties": False,

814 "if": {

815 "properties": {

816 "type": {

817 "const": "object"

818 }

819 }

820 },

821 "then": {

822 "required": [

823 "properties"

824 ]

825 }

826 }

827 }

828 }

829}

830 

831META_PROMPT = """

832# Instructions

833Return a valid schema for the described function.

834 

835Pay 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.

836Make sure that every property, no matter how short, has a type and description correctly nested inside it.

837 

838# Examples

839Input: Assign values to NN hyperparameters

840Output: {

841 "name": "set_hyperparameters",

842 "description": "Assign values to NN hyperparameters",

843 "parameters": {

844 "type": "object",

845 "required": [

846 "learning_rate",

847 "epochs"

848 ],

849 "properties": {

850 "epochs": {

851 "type": "number",

852 "description": "Number of complete passes through dataset"

853 },

854 "learning_rate": {

855 "type": "number",

856 "description": "Speed of model learning"

857 }

858 }

859 }

860}

861 

862Input: Plans a motion path for the robot

863Output: {

864 "name": "plan_motion",

865 "description": "Plans a motion path for the robot",

866 "parameters": {

867 "type": "object",

868 "required": [

869 "start_position",

870 "end_position"

871 ],

872 "properties": {

873 "end_position": {

874 "type": "object",

875 "properties": {

876 "x": {

877 "type": "number",

878 "description": "End X coordinate"

879 },

880 "y": {

881 "type": "number",

882 "description": "End Y coordinate"

883 }

884 }

885 },

886 "obstacles": {

887 "type": "array",

888 "description": "Array of obstacle coordinates",

889 "items": {

890 "type": "object",

891 "properties": {

892 "x": {

893 "type": "number",

894 "description": "Obstacle X coordinate"

895 },

896 "y": {

897 "type": "number",

898 "description": "Obstacle Y coordinate"

899 }

900 }

901 }

902 },

903 "start_position": {

904 "type": "object",

905 "properties": {

906 "x": {

907 "type": "number",

908 "description": "Start X coordinate"

909 },

910 "y": {

911 "type": "number",

912 "description": "Start Y coordinate"

913 }

914 }

915 }

916 }

917 }

918}

919 

920Input: Calculates various technical indicators

921Output: {

922 "name": "technical_indicator",

923 "description": "Calculates various technical indicators",

924 "parameters": {

925 "type": "object",

926 "required": [

927 "ticker",

928 "indicators"

929 ],

930 "properties": {

931 "indicators": {

932 "type": "array",

933 "description": "List of technical indicators to calculate",

934 "items": {

935 "type": "string",

936 "description": "Technical indicator",

937 "enum": [

938 "RSI",

939 "MACD",

940 "Bollinger_Bands",

941 "Stochastic_Oscillator"

942 ]

943 }

944 },

945 "period": {

946 "type": "number",

947 "description": "Time period for the analysis"

948 },

949 "ticker": {

950 "type": "string",

951 "description": "Stock ticker symbol"

952 }

953 }

954 }

955}

956""".strip()

957 

958def generate_function_schema(description: str):

959 completion = client.chat.completions.create(

960 model="gpt-5.6-terra",

961 response_format={"type": "json_schema", "json_schema": META_SCHEMA},

962 messages=[

963 {

964 "role": "system",

965 "content": META_PROMPT,

966 },

967 {

968 "role": "user",

969 "content": "Description:\n" + description,

970 },

971 ],

972 )

973 

974 return json.loads(completion.choices[0].message.content)

975```

976 

107 </div>977 </div>

Details

70 70 

71The fine-tuning rate limits for your organization can be [found in the dashboard as well](https://platform.openai.com/settings/organization/limits), and can also be retrieved via API:71The fine-tuning rate limits for your organization can be [found in the dashboard as well](https://platform.openai.com/settings/organization/limits), and can also be retrieved via API:

72 72 

73```bash

74curl https://api.openai.com/v1/fine_tuning/model_limits \

75 -H "Authorization: Bearer $OPENAI_API_KEY"

76```

77 

78 

73## Error mitigation79## Error mitigation

74 80 

75### What are some steps I can take to mitigate this?81### What are some steps I can take to mitigate this?


98Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.104Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

99To add exponential backoff to your requests, you can use the `tenacity.retry` decorator. The below example uses the `tenacity.wait_random_exponential` function to add random exponential backoff to a request.105To add exponential backoff to your requests, you can use the `tenacity.retry` decorator. The below example uses the `tenacity.wait_random_exponential` function to add random exponential backoff to a request.

100 106 

107Using the Tenacity library

108 

109```python

110from openai import OpenAI

111client = OpenAI()

112 

113from tenacity import (

114retry,

115stop_after_attempt,

116wait_random_exponential,

117) # for exponential backoff

118 

119@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))

120def completion_with_backoff(**kwargs):

121return client.completions.create(**kwargs)

122 

123completion_with_backoff(model="gpt-3.5-turbo-instruct", prompt="Once upon a time,")

124```

125 

126 

101Note that the Tenacity library is a third-party tool, and OpenAI makes no guarantees about127Note that the Tenacity library is a third-party tool, and OpenAI makes no guarantees about

102its reliability or security.128its reliability or security.

103 129 


105 131 

106Another python library that provides function decorators for backoff and retry is [backoff](https://pypi.org/project/backoff/):132Another python library that provides function decorators for backoff and retry is [backoff](https://pypi.org/project/backoff/):

107 133 

134Using the Tenacity library

135 

136```python

137import backoff

138import openai

139from openai import OpenAI

140client = OpenAI()

141 

142@backoff.on_exception(backoff.expo, openai.RateLimitError)

143def completions_with_backoff(**kwargs):

144return client.completions.create(**kwargs)

145 

146completions_with_backoff(model="gpt-3.5-turbo-instruct", prompt="Once upon a time,")

147```

148 

149 

108Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.150Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.

109 151 

110Example 3: Manual backoff implementation152Example 3: Manual backoff implementation

111 153 

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

155Using manual backoff implementation

156 

157```python

158# imports

159import random

160import time

161 

162import openai

163from openai import OpenAI

164client = OpenAI()

165 

166# define a retry decorator

167 

168def retry_with_exponential_backoff(

169func,

170initial_delay: float = 1,

171exponential_base: float = 2,

172jitter: bool = True,

173max_retries: int = 10,

174errors: tuple = (openai.RateLimitError,),

175):

176"""Retry a function with exponential backoff."""

177 

178 def wrapper(*args, **kwargs):

179 # Initialize variables

180 num_retries = 0

181 delay = initial_delay

182 

183 # Loop until a successful response or max_retries is hit or an exception is raised

184 while True:

185 try:

186 return func(*args, **kwargs)

187 

188 # Retry on specific errors

189 except errors as e:

190 # Increment retries

191 num_retries += 1

192 

193 # Check if max retries has been reached

194 if num_retries > max_retries:

195 raise Exception(

196 f"Maximum number of retries ({max_retries}) exceeded."

197 )

198 

199 # Increment the delay

200 delay *= exponential_base * (1 + jitter * random.random())

201 

202 # Sleep for the delay

203 time.sleep(delay)

204 

205 # Raise exceptions for any errors not specified

206 except Exception as e:

207 raise e

208 

209 return wrapper

210 

211@retry_with_exponential_backoff

212def completions_with_backoff(**kwargs):

213return client.completions.create(**kwargs)

214```

215 

113Again, OpenAI makes no guarantees on the security or efficiency of this solution but it can be a good starting place for your own solution.216Again, OpenAI makes no guarantees on the security or efficiency of this solution but it can be a good starting place for your own solution.

114 217 

115#### Reduce the `max_tokens` to match the size of your completions218#### Reduce the `max_tokens` to match the size of your completions

Details

12 **Create vector store** and upload files.12 **Create vector store** and upload files.

13</li>13</li>

14 14 

15Create vector store with files

16 

17```python

18from openai import OpenAI

19client = OpenAI()

20 

21vector_store = client.vector_stores.create( # Create vector store

22 name="Support FAQ",

23)

24 

25client.vector_stores.files.upload_and_poll( # Upload file

26 vector_store_id=vector_store.id,

27 file=open("customer_policies.txt", "rb")

28)

29```

30 

31```javascript

32import OpenAI from "openai";

33const client = new OpenAI();

34 

35const vector_store = await client.vectorStores.create({ // Create vector store

36 name: "Support FAQ",

37});

38 

39await client.vector_stores.files.upload_and_poll({ // Upload file

40 vector_store_id: vector_store.id,

41 file: fs.createReadStream("customer_policies.txt"),

42});

43```

44 

45 

15<li className={s.StandaloneLi} data-number={2}>46<li className={s.StandaloneLi} data-number={2}>

16 **Send search query** to get relevant results.47 **Send search query** to get relevant results.

17</li>48</li>

18 49 

50Search query

51 

52```python

53user_query = "What is the return policy?"

54 

55results = client.vector_stores.search(

56 vector_store_id=vector_store.id,

57 query=user_query,

58)

59```

60 

61```javascript

62const userQuery = "What is the return policy?";

63 

64const results = await client.vectorStores.search({

65 vector_store_id: vector_store.id,

66 query: userQuery,

67});

68```

69 

70 

19To learn how to use the results with our models, check out the [synthesizing71To learn how to use the results with our models, check out the [synthesizing

20 responses](#synthesizing-responses) section.72 responses](#synthesizing-responses) section.

21 73 


41 93 

42You can query a vector store using the `search` function and specifying a `query` in natural language. This will return a list of results, each with the relevant chunks, similarity scores, and file of origin.94You can query a vector store using the `search` function and specifying a `query` in natural language. This will return a list of results, each with the relevant chunks, similarity scores, and file of origin.

43 95 

96Search query

97 

98```python

99results = client.vector_stores.search(

100 vector_store_id=vector_store.id,

101 query="How many woodchucks are allowed per passenger?",

102)

103```

104 

105```javascript

106const results = await client.vectorStores.search({

107 vector_store_id: vector_store.id,

108 query: "How many woodchucks are allowed per passenger?",

109});

110```

111 

112 

113Results

114 

115```json

116{

117 "object": "vector_store.search_results.page",

118 "search_query": "How many woodchucks are allowed per passenger?",

119 "data": [

120 {

121 "file_id": "file-12345",

122 "filename": "woodchuck_policy.txt",

123 "score": 0.85,

124 "attributes": {

125 "region": "North America",

126 "author": "Wildlife Department"

127 },

128 "content": [

129 {

130 "type": "text",

131 "text": "According to the latest regulations, each passenger is allowed to carry up to two woodchucks."

132 },

133 {

134 "type": "text",

135 "text": "Ensure that the woodchucks are properly contained during transport."

136 }

137 ]

138 },

139 {

140 "file_id": "file-67890",

141 "filename": "transport_guidelines.txt",

142 "score": 0.75,

143 "attributes": {

144 "region": "North America",

145 "author": "Transport Authority"

146 },

147 "content": [

148 {

149 "type": "text",

150 "text": "Passengers must adhere to the guidelines set forth by the Transport Authority regarding the transport of woodchucks."

151 }

152 ]

153 }

154 ],

155 "has_more": false,

156 "next_page": null

157}

158```

159 

160 

44A response will contain 10 results maximum by default, but you can set up to 50 using the `max_num_results` param.161A response will contain 10 results maximum by default, but you can set up to 50 using the `max_num_results` param.

45 162 

46### Query rewriting163### Query rewriting


61 178 

62Use **comparison filters** to compare a specific `key` in a file's `attributes` with a given `value`, and **compound filters** to combine multiple filters using `and` and `or`.179Use **comparison filters** to compare a specific `key` in a file's `attributes` with a given `value`, and **compound filters** to combine multiple filters using `and` and `or`.

63 180 

181Comparison filter

182 

183```json

184{

185 "type": "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "nin", // comparison operators

186 "key": "attributes_key", // attributes key

187 "value": "target_value" // value to compare against

188}

189```

190 

191 

192Compound filter

193 

194```json

195{

196 "type": "and" | "or", // logical operators

197 "filters": [...]

198}

199```

200 

201 

64Below are some example filters.202Below are some example filters.

65 203 

66 204 

67 205 

68<div data-content-switcher-pane data-value="region">206<div data-content-switcher-pane data-value="region">

69 <div class="hidden">Region</div>207 <div class="hidden">Region</div>

208 Filter for a region

209 

210```json

211{

212 "type": "eq",

213 "key": "region",

214 "value": "us"

215}

216```

217 

70 </div>218 </div>

71 <div data-content-switcher-pane data-value="date-range" hidden>219 <div data-content-switcher-pane data-value="date-range" hidden>

72 <div class="hidden">Date range</div>220 <div class="hidden">Date range</div>

221 Filter for a date range

222 

223```json

224{

225 "type": "and",

226 "filters": [

227 {

228 "type": "gte",

229 "key": "date",

230 "value": 1704067200 // unix timestamp for 2024-01-01

231 },

232 {

233 "type": "lte",

234 "key": "date",

235 "value": 1710892800 // unix timestamp for 2024-03-20

236 }

237 ]

238}

239```

240 

73 </div>241 </div>

74 <div data-content-switcher-pane data-value="filename" hidden>242 <div data-content-switcher-pane data-value="filename" hidden>

75 <div class="hidden">Filenames</div>243 <div class="hidden">Filenames</div>

244 Filter to match any of a set of filenames

245 

246```json

247{

248 "type": "in",

249 "property": "filename",

250 "value": ["example.txt", "example2.txt"]

251}

252```

253 

76 </div>254 </div>

77 <div data-content-switcher-pane data-value="exclude-filenames" hidden>255 <div data-content-switcher-pane data-value="exclude-filenames" hidden>

78 <div class="hidden">Exclude filenames</div>256 <div class="hidden">Exclude filenames</div>

257 Filter to exclude drafts by filename

258 

259```json

260{

261 "type": "nin",

262 "property": "filename",

263 "value": ["draft.txt", "internal_notes.md"]

264}

265```

266 

79 </div>267 </div>

80 <div data-content-switcher-pane data-value="date-range-and-region" hidden>268 <div data-content-switcher-pane data-value="date-range-and-region" hidden>

81 <div class="hidden">Complex</div>269 <div class="hidden">Complex</div>

270 Filter for top secret projects with certain names in english

271 

272```json

273{

274 "type": "or",

275 "filters": [

276 {

277 "type": "and",

278 "filters": [

279 {

280 "type": "or",

281 "filters": [

282 {

283 "type": "eq",

284 "key": "project_code",

285 "value": "X123"

286 },

287 {

288 "type": "eq",

289 "key": "project_code",

290 "value": "X999"

291 }

292 ]

293 },

294 {

295 "type": "eq",

296 "key": "confidentiality",

297 "value": "top_secret"

298 }

299 ]

300 },

301 {

302 "type": "eq",

303 "key": "language",

304 "value": "en"

305 }

306 ]

307}

308```

309 

82 </div>310 </div>

83 311 

84 312 


116 344 

117<div data-content-switcher-pane data-value="create">345<div data-content-switcher-pane data-value="create">

118 <div class="hidden">Create</div>346 <div class="hidden">Create</div>

347 Create vector store

348 

349```python

350client.vector_stores.create(

351 name="Support FAQ",

352 file_ids=["file_123"]

353)

354```

355 

356```javascript

357await client.vector_stores.create({

358 name: "Support FAQ",

359 file_ids: ["file_123"]

360});

361```

362 

119 </div>363 </div>

120 <div data-content-switcher-pane data-value="retrieve" hidden>364 <div data-content-switcher-pane data-value="retrieve" hidden>

121 <div class="hidden">Retrieve</div>365 <div class="hidden">Retrieve</div>

366 Retrieve vector store

367 

368```python

369client.vector_stores.retrieve(

370 vector_store_id="vs_123"

371)

372```

373 

374```javascript

375await client.vector_stores.retrieve({

376 vector_store_id: "vs_123"

377});

378```

379 

122 </div>380 </div>

123 <div data-content-switcher-pane data-value="update" hidden>381 <div data-content-switcher-pane data-value="update" hidden>

124 <div class="hidden">Update</div>382 <div class="hidden">Update</div>

383 Update vector store

384 

385```python

386client.vector_stores.update(

387 vector_store_id="vs_123",

388 name="Support FAQ Updated"

389)

390```

391 

392```javascript

393await client.vector_stores.update({

394 vector_store_id: "vs_123",

395 name: "Support FAQ Updated"

396});

397```

398 

125 </div>399 </div>

126 <div data-content-switcher-pane data-value="delete" hidden>400 <div data-content-switcher-pane data-value="delete" hidden>

127 <div class="hidden">Delete</div>401 <div class="hidden">Delete</div>

402 Delete vector store

403 

404```python

405client.vector_stores.delete(

406 vector_store_id="vs_123"

407)

408```

409 

410```javascript

411await client.vector_stores.delete({

412 vector_store_id: "vs_123"

413});

414```

415 

128 </div>416 </div>

129 <div data-content-switcher-pane data-value="list" hidden>417 <div data-content-switcher-pane data-value="list" hidden>

130 <div class="hidden">List</div>418 <div class="hidden">List</div>

419 List vector stores

420 

421```python

422client.vector_stores.list()

423```

424 

425```javascript

426await client.vector_stores.list();

427```

428 

131 </div>429 </div>

132 430 

133 431 


142 440 

143<div data-content-switcher-pane data-value="create">441<div data-content-switcher-pane data-value="create">

144 <div class="hidden">Create</div>442 <div class="hidden">Create</div>

443 Create vector store file

444 

445```python

446client.vector_stores.files.create_and_poll(

447 vector_store_id="vs_123",

448 file_id="file_123"

449)

450```

451 

452```javascript

453await client.vector_stores.files.create_and_poll({

454 vector_store_id: "vs_123",

455 file_id: "file_123"

456});

457```

458 

145 </div>459 </div>

146 <div data-content-switcher-pane data-value="upload" hidden>460 <div data-content-switcher-pane data-value="upload" hidden>

147 <div class="hidden">Upload</div>461 <div class="hidden">Upload</div>

462 Upload vector store file

463 

464```python

465client.vector_stores.files.upload_and_poll(

466 vector_store_id="vs_123",

467 file=open("customer_policies.txt", "rb")

468)

469```

470 

471```javascript

472await client.vector_stores.files.upload_and_poll({

473 vector_store_id: "vs_123",

474 file: fs.createReadStream("customer_policies.txt"),

475});

476```

477 

148 </div>478 </div>

149 <div data-content-switcher-pane data-value="retrieve" hidden>479 <div data-content-switcher-pane data-value="retrieve" hidden>

150 <div class="hidden">Retrieve</div>480 <div class="hidden">Retrieve</div>

481 Retrieve vector store file

482 

483```python

484client.vector_stores.files.retrieve(

485 vector_store_id="vs_123",

486 file_id="file_123"

487)

488```

489 

490```javascript

491await client.vector_stores.files.retrieve({

492 vector_store_id: "vs_123",

493 file_id: "file_123"

494});

495```

496 

151 </div>497 </div>

152 <div data-content-switcher-pane data-value="update" hidden>498 <div data-content-switcher-pane data-value="update" hidden>

153 <div class="hidden">Update</div>499 <div class="hidden">Update</div>

500 Update vector store file

501 

502```python

503client.vector_stores.files.update(

504 vector_store_id="vs_123",

505 file_id="file_123",

506 attributes={"key": "value"}

507)

508```

509 

510```javascript

511await client.vector_stores.files.update({

512 vector_store_id: "vs_123",

513 file_id: "file_123",

514 attributes: { key: "value" }

515});

516```

517 

154 </div>518 </div>

155 <div data-content-switcher-pane data-value="delete" hidden>519 <div data-content-switcher-pane data-value="delete" hidden>

156 <div class="hidden">Delete</div>520 <div class="hidden">Delete</div>

521 Delete vector store file

522 

523```python

524client.vector_stores.files.delete(

525 vector_store_id="vs_123",

526 file_id="file_123"

527)

528```

529 

530```javascript

531await client.vector_stores.files.delete({

532 vector_store_id: "vs_123",

533 file_id: "file_123"

534});

535```

536 

157 </div>537 </div>

158 <div data-content-switcher-pane data-value="list" hidden>538 <div data-content-switcher-pane data-value="list" hidden>

159 <div class="hidden">List</div>539 <div class="hidden">List</div>

540 List vector store files

541 

542```python

543client.vector_stores.files.list(

544 vector_store_id="vs_123"

545)

546```

547 

548```javascript

549await client.vector_stores.files.list({

550 vector_store_id: "vs_123"

551});

552```

553 

160 </div>554 </div>

161 555 

162 556 


167 561 

168<div data-content-switcher-pane data-value="create">562<div data-content-switcher-pane data-value="create">

169 <div class="hidden">Create</div>563 <div class="hidden">Create</div>

564 Batch create operation

565 

566```python

567client.vector_stores.file_batches.create_and_poll(

568 vector_store_id="vs_123",

569 files=[

570 {

571 "file_id": "file_123",

572 "attributes": {"department": "finance"}

573 },

574 {

575 "file_id": "file_456",

576 "chunking_strategy": {

577 "type": "static",

578 "max_chunk_size_tokens": 1200,

579 "chunk_overlap_tokens": 200

580 }

581 }

582 ]

583)

584```

585 

586```javascript

587await client.vector_stores.file_batches.create_and_poll({

588 vector_store_id: "vs_123",

589 files: [

590 {

591 file_id: "file_123",

592 attributes: { department: "finance" }

593 },

594 {

595 file_id: "file_456",

596 chunking_strategy: {

597 type: "static",

598 max_chunk_size_tokens: 1200,

599 chunk_overlap_tokens: 200

600 }

601 }

602 ]

603});

604```

605 

170 </div>606 </div>

171 <div data-content-switcher-pane data-value="retrieve" hidden>607 <div data-content-switcher-pane data-value="retrieve" hidden>

172 <div class="hidden">Retrieve</div>608 <div class="hidden">Retrieve</div>

609 Batch retrieve operation

610 

611```python

612client.vector_stores.file_batches.retrieve(

613 vector_store_id="vs_123",

614 batch_id="vsfb_123"

615)

616```

617 

618```javascript

619await client.vector_stores.file_batches.retrieve({

620 vector_store_id: "vs_123",

621 batch_id: "vsfb_123"

622});

623```

624 

173 </div>625 </div>

174 <div data-content-switcher-pane data-value="cancel" hidden>626 <div data-content-switcher-pane data-value="cancel" hidden>

175 <div class="hidden">Cancel</div>627 <div class="hidden">Cancel</div>

628 Batch cancel operation

629 

630```python

631client.vector_stores.file_batches.cancel(

632 vector_store_id="vs_123",

633 batch_id="vsfb_123"

634)

635```

636 

637```javascript

638await client.vector_stores.file_batches.cancel({

639 vector_store_id: "vs_123",

640 batch_id: "vsfb_123"

641});

642```

643 

176 </div>644 </div>

177 <div data-content-switcher-pane data-value="list" hidden>645 <div data-content-switcher-pane data-value="list" hidden>

178 <div class="hidden">List</div>646 <div class="hidden">List</div>

647 Batch list operation

648 

649```python

650client.vector_stores.file_batches.list(

651 vector_store_id="vs_123"

652)

653```

654 

655```javascript

656await client.vector_stores.file_batches.list({

657 vector_store_id: "vs_123"

658});

659```

660 

179 </div>661 </div>

180 662 

181 663 


188 670 

189Each `vector_store.file` can have associated `attributes`, a dictionary of values that can be referenced when performing [semantic search](#semantic-search) with [attribute filtering](#attribute-filtering). The dictionary can have at most 16 keys, with a limit of 256 characters each.671Each `vector_store.file` can have associated `attributes`, a dictionary of values that can be referenced when performing [semantic search](#semantic-search) with [attribute filtering](#attribute-filtering). The dictionary can have at most 16 keys, with a limit of 256 characters each.

190 672 

673Create vector store file with attributes

674 

675```python

676client.vector_stores.files.create(

677 vector_store_id="<vector_store_id>",

678 file_id="file_123",

679 attributes={

680 "region": "US",

681 "category": "Marketing",

682 "date": 1672531200 # Jan 1, 2023

683 }

684)

685```

686 

687```javascript

688await client.vector_stores.files.create(<vector_store_id>, {

689 file_id: "file_123",

690 attributes: {

691 region: "US",

692 category: "Marketing",

693 date: 1672531200, // Jan 1, 2023

694 },

695});

696```

697 

698 

191### Expiration policies699### Expiration policies

192 700 

193You can set an expiration policy on `vector_store` objects with `expires_after`. Once a vector store expires, all associated `vector_store.file` objects will be deleted and you'll no longer be charged for them.701You can set an expiration policy on `vector_store` objects with `expires_after`. Once a vector store expires, all associated `vector_store.file` objects will be deleted and you'll no longer be charged for them.

194 702 

703Set expiration policy for vector store

704 

705```python

706client.vector_stores.update(

707 vector_store_id="vs_123",

708 expires_after={

709 "anchor": "last_active_at",

710 "days": 7

711 }

712)

713```

714 

715```javascript

716await client.vector_stores.update({

717 vector_store_id: "vs_123",

718 expires_after: {

719 anchor: "last_active_at",

720 days: 7,

721 },

722});

723```

724 

725 

195### Limits726### Limits

196 727 

197The maximum file size is 512 MB. Each file should contain no more than 5,000,000 tokens per file (computed automatically when you attach a file).728The maximum file size is 512 MB. Each file should contain no more than 5,000,000 tokens per file (computed automatically when you attach a file).


240 771 

241After performing a query you may want to synthesize a response based on the results. You can leverage our models to do so, by supplying the results and original query, to get back a grounded response.772After performing a query you may want to synthesize a response based on the results. You can leverage our models to do so, by supplying the results and original query, to get back a grounded response.

242 773 

774Perform search query to get results

775 

776```python

777from openai import OpenAI

778 

779client = OpenAI()

780 

781user_query = "What is the return policy?"

782 

783results = client.vector_stores.search(

784 vector_store_id=vector_store.id,

785 query=user_query,

786)

787```

788 

789```javascript

790import OpenAI from "openai";

791const client = new OpenAI();

792 

793const userQuery = "What is the return policy?";

794 

795const results = await client.vectorStores.search({

796 vector_store_id: vector_store.id,

797 query: userQuery,

798});

799```

800 

801 

802Synthesize a response based on results

803 

804```python

805formatted_results = format_results(results.data)

806 

807'\n'.join('\n'.join(c.text) for c in result.content for result in results.data)

808 

809completion = client.chat.completions.create(

810 model="gpt-5.6",

811 messages=[

812 {

813 "role": "developer",

814 "content": "Produce a concise answer to the query based on the provided sources."

815 },

816 {

817 "role": "user",

818 "content": f"Sources: {formatted_results}\n\nQuery: '{user_query}'"

819 }

820 ],

821)

822 

823print(completion.choices[0].message.content)

824```

825 

826```javascript

827const formattedResults = formatResults(results.data);

828// Join the text content of all results

829const textSources = results.data.map(result => result.content.map(c => c.text).join('\n')).join('\n');

830 

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

832 model: "gpt-5.6",

833 messages: [

834 {

835 role: "developer",

836 content: "Produce a concise answer to the query based on the provided sources."

837 },

838 {

839 role: "user",

840 content: `Sources: ${formattedResults}\n\nQuery: '${userQuery}'`

841 }

842 ],

843});

844 

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

846```

847 

848 

849```json

850"Our return policy allows returns within 30 days of purchase."

851```

852 

243This uses a sample `format_results` function, which could be implemented like853This uses a sample `format_results` function, which could be implemented like

244so:854so:

855 

856Sample result formatting function

857 

858```python

859def format_results(results):

860 formatted_results = ''

861 for result in results.data:

862 formatted_result = f"<result file_id='{result.file_id}' file_name='{result.file_name}'>"

863 for part in result.content:

864 formatted_result += f"<content>{part.text}</content>"

865 formatted_results += formatted_result + "</result>"

866 return f"<sources>{formatted_results}</sources>"

867```

868 

869```javascript

870function formatResults(results) {

871 let formattedResults = '';

872 for (const result of results.data) {

873 let formattedResult = `<result file_id='${result.file_id}' file_name='${result.file_name}'>`;

874 for (const part of result.content) {

875 formattedResult += `<content>${part.text}</content>`;

876 }

877 formattedResults += formattedResult + "</result>";

878 }

879 return `<sources>${formattedResults}</sources>`;

880}

881```

Details

9 9 

10To start streaming responses, set `stream=True` in your request to the Responses endpoint:10To start streaming responses, set `stream=True` in your request to the Responses endpoint:

11 11 

12```javascript

13import { OpenAI } from "openai";

14const client = new OpenAI();

15 

16const stream = await client.responses.create({

17 model: "gpt-5.6",

18 input: [

19 {

20 role: "user",

21 content: "Say 'double bubble bath' ten times fast.",

22 },

23 ],

24 stream: true,

25});

26 

27for await (const event of stream) {

28 console.log(event);

29}

30```

31 

32```python

33from openai import OpenAI

34client = OpenAI()

35 

36stream = client.responses.create(

37 model="gpt-5.6",

38 input=[

39 {

40 "role": "user",

41 "content": "Say 'double bubble bath' ten times fast.",

42 },

43 ],

44 stream=True,

45)

46 

47for event in stream:

48 print(event)

49```

50 

51```csharp

52using OpenAI.Responses;

53 

54string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

55OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

56 

57var responses = client.CreateResponseStreamingAsync([

58 ResponseItem.CreateUserMessageItem([

59 ResponseContentPart.CreateInputTextPart("Say 'double bubble bath' ten times fast."),

60 ]),

61]);

62 

63await foreach (var response in responses)

64{

65 if (response is StreamingResponseOutputTextDeltaUpdate delta)

66 {

67 Console.Write(delta.Delta);

68 }

69}

70```

71 

72```ruby

73require "openai"

74 

75openai = OpenAI::Client.new

76 

77stream = openai.responses.stream(

78 model: "gpt-5.6",

79 input: [

80 {

81 role: "user",

82 content: "Say 'double bubble bath' ten times fast."

83 }

84 ]

85)

86 

87stream.each do |event|

88 puts(event)

89end

90```

91 

92 

12The Responses API uses semantic events for streaming. Each event is typed with a predefined schema, so you can listen for events you care about.93The Responses API uses semantic events for streaming. Each event is typed with a predefined schema, so you can listen for events you care about.

13 94 

14For a full list of event types, see the [API reference for streaming](https://developers.openai.com/api/docs/api-reference/responses-streaming). Here are a few examples:95For a full list of event types, see the [API reference for streaming](https://developers.openai.com/api/docs/api-reference/responses-streaming). Here are a few examples:

Details

118 118 

119 119 

120 120 

121 The API response from a refusal will look something like this:121 ```python

122 122class Step(BaseModel):

123 123 explanation: str

124 124 output: str

125 125 

126 Tips and best practices126class MathReasoning(BaseModel):

127 steps: list[Step]

128 final_answer: str

129 

130response = client.responses.parse(

131 model="gpt-5.6",

132 input=[

133 {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."},

134 {"role": "user", "content": "how can I solve 8x + 7 = -23"},

135 ],

136 text_format=MathReasoning,

137)

138 

139for output in response.output:

140 if output.type != "message":

141 continue

142 

143 for item in output.content:

144 if item.type == "refusal":

145 # If the model refuses to respond, you will get a refusal message

146 print(item.refusal)

147 continue

148 

149 if not item.parsed:

150 raise Exception("Could not parse response")

151 

152 print(item.parsed)

153```

154 

155```javascript

156const Step = z.object({

157 explanation: z.string(),

158 output: z.string(),

159});

160 

161const MathReasoning = z.object({

162 steps: z.array(Step),

163 final_answer: z.string(),

164});

165 

166const response = await openai.responses.parse({

167 model: "gpt-5.6",

168 input: [

169 { role: "system", content: "You are a helpful math tutor. Guide the user through the solution step by step." },

170 { role: "user", content: "how can I solve 8x + 7 = -23" },

171 ],

172 text: {

173 format: zodTextFormat(MathReasoning, "math_response"),

174 },

175});

176 

177for (const output of response.output) {

178 if (output.type !== "message") {

179 continue;

180 }

181 

182 for (const item of output.content) {

183 if (item.type == "refusal") {

184 // If the model refuses to respond, you will get a refusal message

185 console.log(item.refusal);

186 continue;

187 }

188 

189 if (!item.parsed) {

190 throw new Error("Could not parse response");

191 }

192 

193 console.log(item.parsed);

194 }

195}

196```

197 

198 

199 

200The API response from a refusal will look something like this:

201 

202 

203 

204 

205 ```json

206{

207 "id": "resp_1234567890",

208 "object": "response",

209 "created_at": 1721596428,

210 "status": "completed",

211 "completed_at": 1721596429,

212 "error": null,

213 "incomplete_details": null,

214 "input": [],

215 "instructions": null,

216 "max_output_tokens": null,

217 "model": "gpt-4o-2024-08-06",

218 "output": [{

219 "id": "msg_1234567890",

220 "type": "message",

221 "role": "assistant",

222 "content": [

223 // highlight-start

224 {

225 "type": "refusal",

226 "refusal": "I'm sorry, I cannot assist with that request."

227 }

228 // highlight-end

229 ]

230 }],

231 "usage": {

232 "input_tokens": 81,

233 "output_tokens": 11,

234 "total_tokens": 92,

235 "output_tokens_details": {

236 "reasoning_tokens": 0,

237 }

238 },

239}

240```

241 

242 

243 

244 

245Tips and best practices

127 246 

128 247 

129 248 

guides/text.md +132 −0

Details

4 4 

5Use the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) for direct model requests like this text-generation call.5Use the [Responses API](https://developers.openai.com/api/docs/api-reference/responses) for direct model requests like this text-generation call.

6 6 

7Generate text from a simple prompt

8 

9```javascript

10import OpenAI from "openai";

11const client = new OpenAI();

12 

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

14 model: "gpt-5.6",

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

16});

17 

18console.log(response.output_text);

19```

20 

21```python

22from openai import OpenAI

23client = OpenAI()

24 

25response = client.responses.create(

26 model="gpt-5.6",

27 input="Write a one-sentence bedtime story about a unicorn."

28)

29 

30print(response.output_text)

31```

32 

33```cli

34openai responses create \

35 --model "gpt-5.6" \

36 --input "Write a one-sentence bedtime story about a unicorn." \

37 --raw-output \

38 --transform 'output.#(type=="message").content.0.text'

39```

40 

41```csharp

42using System;

43using System.Threading.Tasks;

44using OpenAI;

45 

46class Program

47{

48 static async Task Main()

49 {

50 var client = new OpenAIClient(

51 Environment.GetEnvironmentVariable("OPENAI_API_KEY")

52 );

53 

54 var response = await client.Responses.CreateAsync(new ResponseCreateRequest

55 {

56 Model = "gpt-5.6",

57 Input = "Say 'this is a test.'"

58 });

59 

60 Console.WriteLine($"[ASSISTANT]: {response.OutputText()}");

61 }

62}

63```

64 

65```java

66import com.openai.client.OpenAIClient;

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

68import com.openai.models.responses.Response;

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

70 

71public class Main {

72 public static void main(String[] args) {

73 OpenAIClient client = OpenAIOkHttpClient.fromEnv();

74 

75 ResponseCreateParams params = ResponseCreateParams.builder()

76 .input("Say this is a test")

77 .model("gpt-5.6")

78 .build();

79 

80 Response response = client.responses().create(params);

81 System.out.println(response.outputText());

82 }

83}

84```

85 

86```go

87package main

88 

89import (

90 "context"

91 "fmt"

92 

93 "github.com/openai/openai-go/v3"

94 "github.com/openai/openai-go/v3/option"

95 "github.com/openai/openai-go/v3/responses"

96)

97 

98func main() {

99 client := openai.NewClient(

100 option.WithAPIKey("My API Key"), // or set OPENAI_API_KEY in your env

101 )

102 

103 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

104 Model: "gpt-5.6",

105 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},

106 })

107 if err != nil {

108 panic(err.Error())

109 }

110 

111 fmt.Println(resp.OutputText())

112}

113```

114 

115```ruby

116require "openai"

117 

118openai = OpenAI::Client.new

119 

120response = openai.responses.create(

121 model: "gpt-5.6",

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

123)

124 

125puts(response.output_text)

126```

127 

128```bash

129curl "https://api.openai.com/v1/responses" \

130 -H "Content-Type: application/json" \

131 -H "Authorization: Bearer $OPENAI_API_KEY" \

132 -d '{

133 "model": "gpt-5.6",

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

135 }'

136```

137 

138 

7An array of content generated by the model is in the `output` property of the response. In this simple example, we have just one output which looks like this:139An array of content generated by the model is in the `output` property of the response. In this simple example, we have just one output which looks like this:

8 140 

9```json141```json

guides/tools.md +307 −4

Details

6 6 

7<div data-content-switcher-pane data-value="web-search">7<div data-content-switcher-pane data-value="web-search">

8 <div class="hidden">Web search</div>8 <div class="hidden">Web search</div>

9 Include web search results for the model response

10 

11```javascript

12import OpenAI from "openai";

13const client = new OpenAI();

14 

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

16 model: "gpt-5.6",

17 tools: [

18 { type: "web_search" },

19 ],

20 input: "What was a positive news story from today?",

21});

22 

23console.log(response.output_text);

24```

25 

26```python

27from openai import OpenAI

28client = OpenAI()

29 

30response = client.responses.create(

31 model="gpt-5.6",

32 tools=[{"type": "web_search"}],

33 input="What was a positive news story from today?"

34)

35 

36print(response.output_text)

37```

38 

39```bash

40curl "https://api.openai.com/v1/responses" \

41 -H "Content-Type: application/json" \

42 -H "Authorization: Bearer $OPENAI_API_KEY" \

43 -d '{

44 "model": "gpt-5.6",

45 "tools": [{"type": "web_search"}],

46 "input": "what was a positive news story from today?"

47}'

48```

49 

50```cli

51openai responses create \

52 --model gpt-5.6 \

53 --raw-output \

54 --transform 'output.#(type=="message").content.0.text' <<'YAML'

55tools:

56 - type: web_search

57input: What was a positive news story from today?

58YAML

59```

60 

61```csharp

62using OpenAI.Responses;

63 

64string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

65OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

66 

67ResponseCreationOptions options = new();

68options.Tools.Add(ResponseTool.CreateWebSearchTool());

69 

70OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

71 ResponseItem.CreateUserMessageItem([

72 ResponseContentPart.CreateInputTextPart("What was a positive news story from today?"),

73 ]),

74], options);

75 

76Console.WriteLine(response.GetOutputText());

77```

78 

79```ruby

80require "openai"

81 

82openai = OpenAI::Client.new

83 

84response = openai.responses.create(

85 model: "gpt-5.6",

86 tools: [{type: "web_search"}],

87 input: "What was a positive news story from today?"

88)

89 

90puts(response.output_text)

91```

92 

9 </div>93 </div>

10 <div data-content-switcher-pane data-value="file-search" hidden>94 <div data-content-switcher-pane data-value="file-search" hidden>

11 <div class="hidden">File search</div>95 <div class="hidden">File search</div>


59], options);143], options);

60 144 

61Console.WriteLine(response.GetOutputText());145Console.WriteLine(response.GetOutputText());

146```

147 

148```ruby

149require "openai"

150 

151openai = OpenAI::Client.new

152 

153response = openai.responses.create(

154 model: "gpt-5.6",

155 input: "What is deep research by OpenAI?",

156 tools: [

157 {

158 type: "file_search",

159 vector_store_ids: ["<vector_store_id>"]

160 }

161 ]

162)

163 

164puts(response)

62```165```

63 166 

64 </div>167 </div>


180 </div>283 </div>

181 <div data-content-switcher-pane data-value="function-calling" hidden>284 <div data-content-switcher-pane data-value="function-calling" hidden>

182 <div class="hidden">Function calling</div>285 <div class="hidden">Function calling</div>

286 Call your own function

287 

288```javascript

289import OpenAI from "openai";

290const client = new OpenAI();

291 

292const tools = [

293 {

294 type: "function",

295 name: "get_weather",

296 description: "Get current temperature for a given location.",

297 parameters: {

298 type: "object",

299 properties: {

300 location: {

301 type: "string",

302 description: "City and country e.g. Bogotá, Colombia",

303 },

304 },

305 required: ["location"],

306 additionalProperties: false,

307 },

308 strict: true,

309 },

310];

311 

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

313 model: "gpt-5.6",

314 input: [

315 { role: "user", content: "What is the weather like in Paris today?" },

316 ],

317 tools,

318});

319 

320console.log(response.output[0].to_json());

321```

322 

323```python

324from openai import OpenAI

325 

326client = OpenAI()

327 

328tools = [

329 {

330 "type": "function",

331 "name": "get_weather",

332 "description": "Get current temperature for a given location.",

333 "parameters": {

334 "type": "object",

335 "properties": {

336 "location": {

337 "type": "string",

338 "description": "City and country e.g. Bogotá, Colombia",

339 }

340 },

341 "required": ["location"],

342 "additionalProperties": False,

343 },

344 "strict": True,

345 },

346]

347 

348response = client.responses.create(

349 model="gpt-5.6",

350 input=[

351 {"role": "user", "content": "What is the weather like in Paris today?"},

352 ],

353 tools=tools,

354)

355 

356print(response.output[0].to_json())

357```

358 

359```csharp

360using System.Text.Json;

361using OpenAI.Responses;

362 

363string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

364OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

365 

366ResponseCreationOptions options = new();

367options.Tools.Add(ResponseTool.CreateFunctionTool(

368 functionName: "get_weather",

369 functionDescription: "Get current temperature for a given location.",

370 functionParameters: BinaryData.FromObjectAsJson(new

371 {

372 type = "object",

373 properties = new

374 {

375 location = new

376 {

377 type = "string",

378 description = "City and country e.g. Bogotá, Colombia"

379 }

380 },

381 required = new[] { "location" },

382 additionalProperties = false

383 }),

384 strictModeEnabled: true

385 )

386);

387 

388OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

389 ResponseItem.CreateUserMessageItem([

390 ResponseContentPart.CreateInputTextPart("What is the weather like in Paris today?")

391 ])

392], options);

393 

394Console.WriteLine(JsonSerializer.Serialize(response.OutputItems[0]));

395```

396 

397```bash

398curl -X POST https://api.openai.com/v1/responses \

399 -H "Authorization: Bearer $OPENAI_API_KEY" \

400 -H "Content-Type: application/json" \

401 -d '{

402 "model": "gpt-5.6",

403 "input": [

404 {"role": "user", "content": "What is the weather like in Paris today?"}

405 ],

406 "tools": [

407 {

408 "type": "function",

409 "name": "get_weather",

410 "description": "Get current temperature for a given location.",

411 "parameters": {

412 "type": "object",

413 "properties": {

414 "location": {

415 "type": "string",

416 "description": "City and country e.g. Bogotá, Colombia"

417 }

418 },

419 "required": ["location"],

420 "additionalProperties": false

421 },

422 "strict": true

423 }

424 ]

425 }'

426```

427 

428```ruby

429require "openai"

430 

431openai = OpenAI::Client.new

432 

433tools = [

434 {

435 type: "function",

436 name: "get_weather",

437 description: "Get current temperature for a given location.",

438 parameters: {

439 type: "object",

440 properties: {

441 location: {

442 type: "string",

443 description: "City and country e.g. Bogotá, Colombia"

444 }

445 },

446 required: ["location"],

447 additionalProperties: false

448 },

449 strict: true

450 }

451]

452 

453response = openai.responses.create(

454 model: "gpt-5.6",

455 input: [

456 {role: "user", content: "What is the weather like in Paris today?"}

457 ],

458 tools: tools

459)

460 

461puts(response.output.first.to_json)

462```

463 

183 </div>464 </div>

184 <div data-content-switcher-pane data-value="remote-mcp" hidden>465 <div data-content-switcher-pane data-value="remote-mcp" hidden>

185 <div class="hidden">Remote MCP</div>466 <div class="hidden">Remote MCP</div>


196 "type": "mcp",477 "type": "mcp",

197 "server_label": "dmcp",478 "server_label": "dmcp",

198 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",479 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

199 "server_url": "https://dmcp-server.deno.dev/sse",480 "server_url": "https://dmcp-server.deno.dev/mcp",

200 "require_approval": "never"481 "require_approval": "never"

201 }482 }

202 ],483 ],


215 type: "mcp",496 type: "mcp",

216 server_label: "dmcp",497 server_label: "dmcp",

217 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",498 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

218 server_url: "https://dmcp-server.deno.dev/sse",499 server_url: "https://dmcp-server.deno.dev/mcp",

219 require_approval: "never",500 require_approval: "never",

220 },501 },

221 ],502 ],


237 "type": "mcp",518 "type": "mcp",

238 "server_label": "dmcp",519 "server_label": "dmcp",

239 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",520 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

240 "server_url": "https://dmcp-server.deno.dev/sse",521 "server_url": "https://dmcp-server.deno.dev/mcp",

241 "require_approval": "never",522 "require_approval": "never",

242 },523 },

243 ],524 ],


256ResponseCreationOptions options = new();537ResponseCreationOptions options = new();

257options.Tools.Add(ResponseTool.CreateMcpTool(538options.Tools.Add(ResponseTool.CreateMcpTool(

258 serverLabel: "dmcp",539 serverLabel: "dmcp",

259 serverUri: new Uri("https://dmcp-server.deno.dev/sse"),540 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

260 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)541 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)

261));542));

262 543 


267], options);548], options);

268 549 

269Console.WriteLine(response.GetOutputText());550Console.WriteLine(response.GetOutputText());

551```

552 

553```ruby

554require "openai"

555 

556openai = OpenAI::Client.new

557 

558response = openai.responses.create(

559 model: "gpt-5.6",

560 tools: [

561 {

562 type: "mcp",

563 server_label: "dmcp",

564 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

565 server_url: "https://dmcp-server.deno.dev/mcp",

566 require_approval: "never"

567 }

568 ],

569 input: "Roll 2d4+1"

570)

571 

572puts(response.output_text)

270```573```

271 574 

272 </div>575 </div>

Details

38 "type": "mcp",38 "type": "mcp",

39 "server_label": "dmcp",39 "server_label": "dmcp",

40 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",40 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

41 "server_url": "https://dmcp-server.deno.dev/sse",41 "server_url": "https://dmcp-server.deno.dev/mcp",

42 "require_approval": "never"42 "require_approval": "never"

43 }43 }

44 ],44 ],


57 type: "mcp",57 type: "mcp",

58 server_label: "dmcp",58 server_label: "dmcp",

59 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",59 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

60 server_url: "https://dmcp-server.deno.dev/sse",60 server_url: "https://dmcp-server.deno.dev/mcp",

61 require_approval: "never",61 require_approval: "never",

62 },62 },

63 ],63 ],


79 "type": "mcp",79 "type": "mcp",

80 "server_label": "dmcp",80 "server_label": "dmcp",

81 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",81 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

82 "server_url": "https://dmcp-server.deno.dev/sse",82 "server_url": "https://dmcp-server.deno.dev/mcp",

83 "require_approval": "never",83 "require_approval": "never",

84 },84 },

85 ],85 ],


98ResponseCreationOptions options = new();98ResponseCreationOptions options = new();

99options.Tools.Add(ResponseTool.CreateMcpTool(99options.Tools.Add(ResponseTool.CreateMcpTool(

100 serverLabel: "dmcp",100 serverLabel: "dmcp",

101 serverUri: new Uri("https://dmcp-server.deno.dev/sse"),101 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

102 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)102 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)

103));103));

104 104 


111Console.WriteLine(response.GetOutputText());111Console.WriteLine(response.GetOutputText());

112```112```

113 113 

114```ruby

115require "openai"

116 

117openai = OpenAI::Client.new

118 

119response = openai.responses.create(

120 model: "gpt-5.6",

121 tools: [

122 {

123 type: "mcp",

124 server_label: "dmcp",

125 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

126 server_url: "https://dmcp-server.deno.dev/mcp",

127 require_approval: "never"

128 }

129 ],

130 input: "Roll 2d4+1"

131)

132 

133puts(response.output_text)

134```

135 

114 136 

115 It is very important that developers trust any remote MCP server they use with137 It is very important that developers trust any remote MCP server they use with

116 the Responses API. A malicious server can exfiltrate sensitive data from138 the Responses API. A malicious server can exfiltrate sensitive data from


324 "type": "mcp",346 "type": "mcp",

325 "server_label": "dmcp",347 "server_label": "dmcp",

326 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",348 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

327 "server_url": "https://dmcp-server.deno.dev/sse",349 "server_url": "https://dmcp-server.deno.dev/mcp",

328 "require_approval": "never",350 "require_approval": "never",

329 "allowed_tools": ["roll"]351 "allowed_tools": ["roll"]

330 }352 }


343 type: "mcp",365 type: "mcp",

344 server_label: "dmcp",366 server_label: "dmcp",

345 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",367 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

346 server_url: "https://dmcp-server.deno.dev/sse",368 server_url: "https://dmcp-server.deno.dev/mcp",

347 require_approval: "never",369 require_approval: "never",

348 allowed_tools: ["roll"],370 allowed_tools: ["roll"],

349 }],371 }],


364 "type": "mcp",386 "type": "mcp",

365 "server_label": "dmcp",387 "server_label": "dmcp",

366 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",388 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

367 "server_url": "https://dmcp-server.deno.dev/sse",389 "server_url": "https://dmcp-server.deno.dev/mcp",

368 "require_approval": "never",390 "require_approval": "never",

369 "allowed_tools": ["roll"],391 "allowed_tools": ["roll"],

370 }],392 }],


383ResponseCreationOptions options = new();405ResponseCreationOptions options = new();

384options.Tools.Add(ResponseTool.CreateMcpTool(406options.Tools.Add(ResponseTool.CreateMcpTool(

385 serverLabel: "dmcp",407 serverLabel: "dmcp",

386 serverUri: new Uri("https://dmcp-server.deno.dev/sse"),408 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

387 allowedTools: new McpToolFilter() { ToolNames = { "roll" } },409 allowedTools: new McpToolFilter() { ToolNames = { "roll" } },

388 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)410 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)

389));411));


448 "type": "mcp",470 "type": "mcp",

449 "server_label": "dmcp",471 "server_label": "dmcp",

450 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",472 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

451 "server_url": "https://dmcp-server.deno.dev/sse",473 "server_url": "https://dmcp-server.deno.dev/mcp",

452 "require_approval": "always",474 "require_approval": "always",

453 }475 }

454 ],476 ],


471 type: "mcp",493 type: "mcp",

472 server_label: "dmcp",494 server_label: "dmcp",

473 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",495 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

474 server_url: "https://dmcp-server.deno.dev/sse",496 server_url: "https://dmcp-server.deno.dev/mcp",

475 require_approval: "always",497 require_approval: "always",

476 }],498 }],

477 previous_response_id: "resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa",499 previous_response_id: "resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa",


496 "type": "mcp",518 "type": "mcp",

497 "server_label": "dmcp",519 "server_label": "dmcp",

498 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",520 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

499 "server_url": "https://dmcp-server.deno.dev/sse",521 "server_url": "https://dmcp-server.deno.dev/mcp",

500 "require_approval": "always",522 "require_approval": "always",

501 }],523 }],

502 previous_response_id="resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa",524 previous_response_id="resp_682d498bdefc81918b4a6aa477bfafd904ad1e533afccbfa",


519ResponseCreationOptions options = new();541ResponseCreationOptions options = new();

520options.Tools.Add(ResponseTool.CreateMcpTool(542options.Tools.Add(ResponseTool.CreateMcpTool(

521 serverLabel: "dmcp",543 serverLabel: "dmcp",

522 serverUri: new Uri("https://dmcp-server.deno.dev/sse"),544 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

523 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval)545 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval)

524));546));

525 547 


1178 "type": "mcp",1200 "type": "mcp",

1179 "server_label": "dmcp",1201 "server_label": "dmcp",

1180 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",1202 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

1181 "server_url": "https://dmcp-server.deno.dev/sse",1203 "server_url": "https://dmcp-server.deno.dev/mcp",

1182// highlight-start:subtle1204// highlight-start:subtle

1183 "defer_loading": true,1205 "defer_loading": true,

1184// highlight-end1206// highlight-end

quickstart.md +1079 −5

Details

1# Developer quickstart1# Developer quickstart

2 2 

3The OpenAI API provides a simple interface to state-of-the-art AI [models](https://developers.openai.com/api/docs/models) for text generation, natural language processing, computer vision, and more. Get started by creating an API Key and running your first API call. Discover how to generate text, analyze images, build agents, and more.3The OpenAI API provides a consistent interface to state-of-the-art AI [models](https://developers.openai.com/api/docs/models) for text generation, natural language processing, computer vision, and more. Get started by creating an API Key and running your first API call. Discover how to generate text, analyze images, build agents, and more.

4 4 

5## Create and export an API key5## Create and export an API key

6 6 


25 25 

26<div data-content-switcher-pane data-value="macOS">26<div data-content-switcher-pane data-value="macOS">

27 <div class="hidden">macOS / Linux</div>27 <div class="hidden">macOS / Linux</div>

28 Export an environment variable on macOS or Linux systems

29 

30```bash

31export OPENAI_API_KEY="your_api_key_here"

32```

33 

28 </div>34 </div>

29 <div data-content-switcher-pane data-value="windows" hidden>35 <div data-content-switcher-pane data-value="windows" hidden>

30 <div class="hidden">Windows</div>36 <div class="hidden">Windows</div>

37 Export an environment variable in PowerShell

38 

39```bash

40setx OPENAI_API_KEY "your_api_key_here"

41```

42 

31 </div>43 </div>

32 44 

33 45 

34 46 

35OpenAI SDKs are configured to automatically read your API key from the system environment.47Each OpenAI SDK automatically reads your API key from the system environment.

36 48 

37## Install the OpenAI SDK and Run an API Call49## Install the OpenAI SDK and Run an API Call

38 50 


53 <div data-content-switcher-pane data-value="golang" hidden>65 <div data-content-switcher-pane data-value="golang" hidden>

54 <div class="hidden">Go</div>66 <div class="hidden">Go</div>

55 </div>67 </div>

68 <div data-content-switcher-pane data-value="ruby" hidden>

69 <div class="hidden">Ruby</div>

70 </div>

56 71 

57 72 

58<a73<a


129 144 

130<div data-content-switcher-pane data-value="image-url">145<div data-content-switcher-pane data-value="image-url">

131 <div class="hidden">Image URL</div>146 <div class="hidden">Image URL</div>

147 Analyze the content of an image

148 

149```javascript

150import OpenAI from "openai";

151const client = new OpenAI();

152 

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

154 model: "gpt-5.6",

155 input: [

156 {

157 role: "user",

158 content: [

159 {

160 type: "input_text",

161 text: "What is in this image?",

162 },

163 {

164 type: "input_image",

165 image_url: "https://openai-documentation.vercel.app/images/cat_and_otter.png",

166 },

167 ],

168 },

169 ],

170});

171 

172console.log(response.output_text);

173```

174 

175```bash

176curl "https://api.openai.com/v1/responses" \

177 -H "Content-Type: application/json" \

178 -H "Authorization: Bearer $OPENAI_API_KEY" \

179 -d '{

180 "model": "gpt-5.6",

181 "input": [

182 {

183 "role": "user",

184 "content": [

185 {

186 "type": "input_text",

187 "text": "What is in this image?"

188 },

189 {

190 "type": "input_image",

191 "image_url": "https://openai-documentation.vercel.app/images/cat_and_otter.png"

192 }

193 ]

194 }

195 ]

196}'

197```

198 

199```cli

200openai responses create \

201 --model gpt-5.6 \

202 --raw-output \

203 --transform 'output.#(type=="message").content.0.text' <<'YAML'

204input:

205 - role: user

206 content:

207 - type: input_text

208 text: What is in this image?

209 - type: input_image

210 image_url: https://openai-documentation.vercel.app/images/cat_and_otter.png

211YAML

212```

213 

214```python

215from openai import OpenAI

216client = OpenAI()

217 

218response = client.responses.create(

219 model="gpt-5.6",

220 input=[

221 {

222 "role": "user",

223 "content": [

224 {

225 "type": "input_text",

226 "text": "What teams are playing in this image?",

227 },

228 {

229 "type": "input_image",

230 "image_url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg"

231 }

232 ]

233 }

234 ]

235)

236 

237print(response.output_text)

238```

239 

240```csharp

241using OpenAI.Responses;

242 

243string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

244OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

245 

246OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

247 ResponseItem.CreateUserMessageItem([

248 ResponseContentPart.CreateInputTextPart("What is in this image?"),

249 ResponseContentPart.CreateInputImagePart(new Uri("https://openai-documentation.vercel.app/images/cat_and_otter.png")),

250 ]),

251]);

252 

253Console.WriteLine(response.GetOutputText());

254```

255 

256```ruby

257require "openai"

258 

259openai = OpenAI::Client.new

260 

261response = openai.responses.create(

262 model: "gpt-5.6",

263 input: [

264 {

265 role: "user",

266 content: [

267 {

268 type: "input_text",

269 text: "What teams are playing in this image?"

270 },

271 {

272 type: "input_image",

273 image_url: "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg"

274 }

275 ]

276 }

277 ]

278)

279 

280puts(response.output_text)

281```

282 

132 </div>283 </div>

133 <div data-content-switcher-pane data-value="file-url" hidden>284 <div data-content-switcher-pane data-value="file-url" hidden>

134 <div class="hidden">File URL</div>285 <div class="hidden">File URL</div>

286 Use a file URL as input

287 

288```bash

289curl "https://api.openai.com/v1/responses" \

290 -H "Content-Type: application/json" \

291 -H "Authorization: Bearer $OPENAI_API_KEY" \

292 -d '{

293 "model": "gpt-5.6",

294 "input": [

295 {

296 "role": "user",

297 "content": [

298 {

299 "type": "input_text",

300 "text": "Analyze the letter and provide a summary of the key points."

301 },

302 {

303 "type": "input_file",

304 "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf"

305 }

306 ]

307 }

308 ]

309 }'

310```

311 

312```javascript

313import OpenAI from "openai";

314const client = new OpenAI();

315 

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

317 model: "gpt-5.6",

318 input: [

319 {

320 role: "user",

321 content: [

322 {

323 type: "input_text",

324 text: "Analyze the letter and provide a summary of the key points.",

325 },

326 {

327 type: "input_file",

328 file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf",

329 },

330 ],

331 },

332 ],

333});

334 

335console.log(response.output_text);

336```

337 

338```python

339from openai import OpenAI

340client = OpenAI()

341 

342response = client.responses.create(

343 model="gpt-5.6",

344 input=[

345 {

346 "role": "user",

347 "content": [

348 {

349 "type": "input_text",

350 "text": "Analyze the letter and provide a summary of the key points.",

351 },

352 {

353 "type": "input_file",

354 "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf",

355 },

356 ],

357 },

358 ]

359)

360 

361print(response.output_text)

362```

363 

364```ruby

365require "openai"

366 

367openai = OpenAI::Client.new

368 

369response = openai.responses.create(

370 model: "gpt-5.6",

371 input: [

372 {

373 role: "user",

374 content: [

375 {

376 type: "input_text",

377 text: "Analyze the letter and provide a summary of the key points."

378 },

379 {

380 type: "input_file",

381 file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf"

382 }

383 ]

384 }

385 ]

386)

387 

388puts(response.output_text)

389```

390 

391```csharp

392using OpenAI.Files;

393using OpenAI.Responses;

394 

395string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

396OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

397 

398using HttpClient http = new();

399using Stream stream = await http.GetStreamAsync("https://www.berkshirehathaway.com/letters/2024ltr.pdf");

400OpenAIFileClient files = new(key);

401OpenAIFile file = files.UploadFile(stream, "2024ltr.pdf", FileUploadPurpose.UserData);

402 

403OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

404 ResponseItem.CreateUserMessageItem([

405 ResponseContentPart.CreateInputTextPart("Analyze the letter and provide a summary of the key points."),

406 ResponseContentPart.CreateInputFilePart(file.Id),

407 ]),

408]);

409 

410Console.WriteLine(response.GetOutputText());

411```

412 

135 </div>413 </div>

136 <div data-content-switcher-pane data-value="file-upload" hidden>414 <div data-content-switcher-pane data-value="file-upload" hidden>

137 <div class="hidden">Upload file</div>415 <div class="hidden">Upload file</div>

416 Upload a file and use it as input

417 

418```bash

419curl https://api.openai.com/v1/files \

420 -H "Authorization: Bearer $OPENAI_API_KEY" \

421 -F purpose="user_data" \

422 -F file="@draconomicon.pdf"

423 

424curl "https://api.openai.com/v1/responses" \

425 -H "Content-Type: application/json" \

426 -H "Authorization: Bearer $OPENAI_API_KEY" \

427 -d '{

428 "model": "gpt-5.6",

429 "input": [

430 {

431 "role": "user",

432 "content": [

433 {

434 "type": "input_file",

435 "file_id": "file-6F2ksmvXxt4VdoqmHRw6kL"

436 },

437 {

438 "type": "input_text",

439 "text": "What is the first dragon in the book?"

440 }

441 ]

442 }

443 ]

444 }'

445```

446 

447```javascript

448import fs from "fs";

449import OpenAI from "openai";

450const client = new OpenAI();

451 

452const file = await client.files.create({

453 file: fs.createReadStream("draconomicon.pdf"),

454 purpose: "user_data",

455});

456 

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

458 model: "gpt-5.6",

459 input: [

460 {

461 role: "user",

462 content: [

463 {

464 type: "input_file",

465 file_id: file.id,

466 },

467 {

468 type: "input_text",

469 text: "What is the first dragon in the book?",

470 },

471 ],

472 },

473 ],

474});

475 

476console.log(response.output_text);

477```

478 

479```python

480from openai import OpenAI

481client = OpenAI()

482 

483file = client.files.create(

484 file=open("draconomicon.pdf", "rb"),

485 purpose="user_data"

486)

487 

488response = client.responses.create(

489 model="gpt-5.6",

490 input=[

491 {

492 "role": "user",

493 "content": [

494 {

495 "type": "input_file",

496 "file_id": file.id,

497 },

498 {

499 "type": "input_text",

500 "text": "What is the first dragon in the book?",

501 },

502 ]

503 }

504 ]

505)

506 

507print(response.output_text)

508```

509 

510```ruby

511require "openai"

512 

513openai = OpenAI::Client.new

514 

515file = openai.files.create(

516 file: File.open("draconomicon.pdf", "rb"),

517 purpose: "user_data"

518)

519 

520response = openai.responses.create(

521 model: "gpt-5.6",

522 input: [

523 {

524 role: "user",

525 content: [

526 {type: "input_file", file_id: file.id},

527 {type: "input_text", text: "What is the first dragon in the book?"}

528 ]

529 }

530 ]

531)

532 

533puts(response.output_text)

534```

535 

536```csharp

537using OpenAI.Files;

538using OpenAI.Responses;

539 

540string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

541OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

542 

543OpenAIFileClient files = new(key);

544OpenAIFile file = files.UploadFile("draconomicon.pdf", FileUploadPurpose.UserData);

545 

546OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

547 ResponseItem.CreateUserMessageItem([

548 ResponseContentPart.CreateInputFilePart(file.Id),

549 ResponseContentPart.CreateInputTextPart("What is the first dragon in the book?"),

550 ]),

551]);

552 

553Console.WriteLine(response.GetOutputText());

554```

555 

138 </div>556 </div>

139 557 

140 558 


163 581 

164<div data-content-switcher-pane data-value="web-search">582<div data-content-switcher-pane data-value="web-search">

165 <div class="hidden">Web search</div>583 <div class="hidden">Web search</div>

584 Use web search in a response

585 

586```javascript

587import OpenAI from "openai";

588const client = new OpenAI();

589 

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

591 model: "gpt-5.6",

592 tools: [

593 { type: "web_search" },

594 ],

595 input: "What was a positive news story from today?",

596});

597 

598console.log(response.output_text);

599```

600 

601```python

602from openai import OpenAI

603client = OpenAI()

604 

605response = client.responses.create(

606 model="gpt-5.6",

607 tools=[{"type": "web_search"}],

608 input="What was a positive news story from today?"

609)

610 

611print(response.output_text)

612```

613 

614```bash

615curl "https://api.openai.com/v1/responses" \

616 -H "Content-Type: application/json" \

617 -H "Authorization: Bearer $OPENAI_API_KEY" \

618 -d '{

619 "model": "gpt-5.6",

620 "tools": [{"type": "web_search"}],

621 "input": "what was a positive news story from today?"

622}'

623```

624 

625```cli

626openai responses create \

627 --model gpt-5.6 \

628 --raw-output \

629 --transform 'output.#(type=="message").content.0.text' <<'YAML'

630tools:

631 - type: web_search

632input: What was a positive news story from today?

633YAML

634```

635 

636```csharp

637using OpenAI.Responses;

638 

639string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

640OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

641 

642ResponseCreationOptions options = new();

643options.Tools.Add(ResponseTool.CreateWebSearchTool());

644 

645OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

646 ResponseItem.CreateUserMessageItem([

647 ResponseContentPart.CreateInputTextPart("What was a positive news story from today?"),

648 ]),

649], options);

650 

651Console.WriteLine(response.GetOutputText());

652```

653 

654```ruby

655require "openai"

656 

657openai = OpenAI::Client.new

658 

659response = openai.responses.create(

660 model: "gpt-5.6",

661 tools: [{type: "web_search"}],

662 input: "What was a positive news story from today?"

663)

664 

665puts(response.output_text)

666```

667 

166 </div>668 </div>

167 <div data-content-switcher-pane data-value="file-search" hidden>669 <div data-content-switcher-pane data-value="file-search" hidden>

168 <div class="hidden">File search</div>670 <div class="hidden">File search</div>

671 Search your files in a response

672 

673```python

674from openai import OpenAI

675client = OpenAI()

676 

677response = client.responses.create(

678 model="gpt-5.6",

679 input="What is deep research by OpenAI?",

680 tools=[{

681 "type": "file_search",

682 "vector_store_ids": ["<vector_store_id>"]

683 }]

684)

685print(response)

686```

687 

688```javascript

689import OpenAI from "openai";

690const openai = new OpenAI();

691 

692const response = await openai.responses.create({

693 model: "gpt-5.6",

694 input: "What is deep research by OpenAI?",

695 tools: [

696 {

697 type: "file_search",

698 vector_store_ids: ["<vector_store_id>"],

699 },

700 ],

701});

702console.log(response);

703```

704 

705```csharp

706using OpenAI.Responses;

707 

708string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

709OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

710 

711ResponseCreationOptions options = new();

712options.Tools.Add(ResponseTool.CreateFileSearchTool(["<vector_store_id>"]));

713 

714OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

715 ResponseItem.CreateUserMessageItem([

716 ResponseContentPart.CreateInputTextPart("What is deep research by OpenAI?"),

717 ]),

718], options);

719 

720Console.WriteLine(response.GetOutputText());

721```

722 

723```ruby

724require "openai"

725 

726openai = OpenAI::Client.new

727 

728response = openai.responses.create(

729 model: "gpt-5.6",

730 input: "What is deep research by OpenAI?",

731 tools: [

732 {

733 type: "file_search",

734 vector_store_ids: ["<vector_store_id>"]

735 }

736 ]

737)

738 

739puts(response)

740```

741 

169 </div>742 </div>

170 <div data-content-switcher-pane data-value="code-interpreter" hidden>743 <div data-content-switcher-pane data-value="code-interpreter" hidden>

171 <div class="hidden">Code Interpreter</div>744 <div class="hidden">Code Interpreter</div>

745 Use Code Interpreter in a response

746 

747```javascript

748import OpenAI from "openai";

749const client = new OpenAI();

750 

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

752 model: "gpt-5.6",

753 instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.",

754 tools: [

755 {

756 type: "code_interpreter",

757 container: { type: "auto" },

758 },

759 ],

760 input: "I need to solve the equation 3x + 11 = 14. Can you help me?",

761});

762 

763console.log(response.output_text);

764```

765 

766```python

767from openai import OpenAI

768client = OpenAI()

769 

770response = client.responses.create(

771 model="gpt-5.6",

772 instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.",

773 tools=[{

774 "type": "code_interpreter",

775 "container": {"type": "auto"}

776 }],

777 input="I need to solve the equation 3x + 11 = 14. Can you help me?"

778)

779 

780print(response.output_text)

781```

782 

783```bash

784curl https://api.openai.com/v1/responses \

785 -H "Content-Type: application/json" \

786 -H "Authorization: Bearer $OPENAI_API_KEY" \

787 -d '{

788 "model": "gpt-5.6",

789 "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.",

790 "tools": [

791 {

792 "type": "code_interpreter",

793 "container": { "type": "auto" }

794 }

795 ],

796 "input": "I need to solve the equation 3x + 11 = 14. Can you help me?"

797 }'

798```

799 

800```ruby

801require "openai"

802 

803openai = OpenAI::Client.new

804 

805response = openai.responses.create(

806 model: "gpt-5.6",

807 instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.",

808 tools: [

809 {

810 type: "code_interpreter",

811 container: {type: "auto"}

812 }

813 ],

814 input: "I need to solve the equation 3x + 11 = 14. Can you help me?"

815)

816 

817puts(response.output_text)

818```

819 

172 </div>820 </div>

173 <div data-content-switcher-pane data-value="function-calling" hidden>821 <div data-content-switcher-pane data-value="function-calling" hidden>

174 <div class="hidden">Function calling</div>822 <div class="hidden">Function calling</div>

823 Call your own function

824 

825```javascript

826import OpenAI from "openai";

827const client = new OpenAI();

828 

829const tools = [

830 {

831 type: "function",

832 name: "get_weather",

833 description: "Get current temperature for a given location.",

834 parameters: {

835 type: "object",

836 properties: {

837 location: {

838 type: "string",

839 description: "City and country e.g. Bogotá, Colombia",

840 },

841 },

842 required: ["location"],

843 additionalProperties: false,

844 },

845 strict: true,

846 },

847];

848 

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

850 model: "gpt-5.6",

851 input: [

852 { role: "user", content: "What is the weather like in Paris today?" },

853 ],

854 tools,

855});

856 

857console.log(response.output[0].to_json());

858```

859 

860```python

861from openai import OpenAI

862 

863client = OpenAI()

864 

865tools = [

866 {

867 "type": "function",

868 "name": "get_weather",

869 "description": "Get current temperature for a given location.",

870 "parameters": {

871 "type": "object",

872 "properties": {

873 "location": {

874 "type": "string",

875 "description": "City and country e.g. Bogotá, Colombia",

876 }

877 },

878 "required": ["location"],

879 "additionalProperties": False,

880 },

881 "strict": True,

882 },

883]

884 

885response = client.responses.create(

886 model="gpt-5.6",

887 input=[

888 {"role": "user", "content": "What is the weather like in Paris today?"},

889 ],

890 tools=tools,

891)

892 

893print(response.output[0].to_json())

894```

895 

896```csharp

897using System.Text.Json;

898using OpenAI.Responses;

899 

900string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

901OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

902 

903ResponseCreationOptions options = new();

904options.Tools.Add(ResponseTool.CreateFunctionTool(

905 functionName: "get_weather",

906 functionDescription: "Get current temperature for a given location.",

907 functionParameters: BinaryData.FromObjectAsJson(new

908 {

909 type = "object",

910 properties = new

911 {

912 location = new

913 {

914 type = "string",

915 description = "City and country e.g. Bogotá, Colombia"

916 }

917 },

918 required = new[] { "location" },

919 additionalProperties = false

920 }),

921 strictModeEnabled: true

922 )

923);

924 

925OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

926 ResponseItem.CreateUserMessageItem([

927 ResponseContentPart.CreateInputTextPart("What is the weather like in Paris today?")

928 ])

929], options);

930 

931Console.WriteLine(JsonSerializer.Serialize(response.OutputItems[0]));

932```

933 

934```bash

935curl -X POST https://api.openai.com/v1/responses \

936 -H "Authorization: Bearer $OPENAI_API_KEY" \

937 -H "Content-Type: application/json" \

938 -d '{

939 "model": "gpt-5.6",

940 "input": [

941 {"role": "user", "content": "What is the weather like in Paris today?"}

942 ],

943 "tools": [

944 {

945 "type": "function",

946 "name": "get_weather",

947 "description": "Get current temperature for a given location.",

948 "parameters": {

949 "type": "object",

950 "properties": {

951 "location": {

952 "type": "string",

953 "description": "City and country e.g. Bogotá, Colombia"

954 }

955 },

956 "required": ["location"],

957 "additionalProperties": false

958 },

959 "strict": true

960 }

961 ]

962 }'

963```

964 

965```ruby

966require "openai"

967 

968openai = OpenAI::Client.new

969 

970tools = [

971 {

972 type: "function",

973 name: "get_weather",

974 description: "Get current temperature for a given location.",

975 parameters: {

976 type: "object",

977 properties: {

978 location: {

979 type: "string",

980 description: "City and country e.g. Bogotá, Colombia"

981 }

982 },

983 required: ["location"],

984 additionalProperties: false

985 },

986 strict: true

987 }

988]

989 

990response = openai.responses.create(

991 model: "gpt-5.6",

992 input: [

993 {role: "user", content: "What is the weather like in Paris today?"}

994 ],

995 tools: tools

996)

997 

998puts(response.output.first.to_json)

999```

1000 

175 </div>1001 </div>

176 <div data-content-switcher-pane data-value="remote-mcp" hidden>1002 <div data-content-switcher-pane data-value="remote-mcp" hidden>

177 <div class="hidden">Remote MCP</div>1003 <div class="hidden">Remote MCP</div>

1004 Call a remote MCP server

1005 

1006```bash

1007curl https://api.openai.com/v1/responses \

1008-H "Content-Type: application/json" \

1009-H "Authorization: Bearer $OPENAI_API_KEY" \

1010-d '{

1011 "model": "gpt-5.6",

1012 "tools": [

1013 {

1014 "type": "mcp",

1015 "server_label": "dmcp",

1016 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

1017 "server_url": "https://dmcp-server.deno.dev/mcp",

1018 "require_approval": "never"

1019 }

1020 ],

1021 "input": "Roll 2d4+1"

1022 }'

1023```

1024 

1025```javascript

1026import OpenAI from "openai";

1027const client = new OpenAI();

1028 

1029const resp = await client.responses.create({

1030 model: "gpt-5.6",

1031 tools: [

1032 {

1033 type: "mcp",

1034 server_label: "dmcp",

1035 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

1036 server_url: "https://dmcp-server.deno.dev/mcp",

1037 require_approval: "never",

1038 },

1039 ],

1040 input: "Roll 2d4+1",

1041});

1042 

1043console.log(resp.output_text);

1044```

1045 

1046```python

1047from openai import OpenAI

1048 

1049client = OpenAI()

1050 

1051resp = client.responses.create(

1052 model="gpt-5.6",

1053 tools=[

1054 {

1055 "type": "mcp",

1056 "server_label": "dmcp",

1057 "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",

1058 "server_url": "https://dmcp-server.deno.dev/mcp",

1059 "require_approval": "never",

1060 },

1061 ],

1062 input="Roll 2d4+1",

1063)

1064 

1065print(resp.output_text)

1066```

1067 

1068```csharp

1069using OpenAI.Responses;

1070 

1071string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1072OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

1073 

1074ResponseCreationOptions options = new();

1075options.Tools.Add(ResponseTool.CreateMcpTool(

1076 serverLabel: "dmcp",

1077 serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),

1078 toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)

1079));

1080 

1081OpenAIResponse response = (OpenAIResponse)client.CreateResponse([

1082 ResponseItem.CreateUserMessageItem([

1083 ResponseContentPart.CreateInputTextPart("Roll 2d4+1")

1084 ])

1085], options);

1086 

1087Console.WriteLine(response.GetOutputText());

1088```

1089 

1090```ruby

1091require "openai"

1092 

1093openai = OpenAI::Client.new

1094 

1095response = openai.responses.create(

1096 model: "gpt-5.6",

1097 tools: [

1098 {

1099 type: "mcp",

1100 server_label: "dmcp",

1101 server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",

1102 server_url: "https://dmcp-server.deno.dev/mcp",

1103 require_approval: "never"

1104 }

1105 ],

1106 input: "Roll 2d4+1"

1107)

1108 

1109puts(response.output_text)

1110```

1111 

178 </div>1112 </div>

179 1113 

180 1114 


195 1129 

196](https://developers.openai.com/api/docs/guides/function-calling)1130](https://developers.openai.com/api/docs/guides/function-calling)

197 1131 

198## Stream responses and build realtime apps1132## Stream responses and build real-time apps

1133 

1134Use server‑sent [streaming events](https://developers.openai.com/api/docs/guides/streaming-responses) to show results as they’re generated, or use the [Realtime API](https://developers.openai.com/api/docs/guides/realtime) for interactive voice apps and apps with text, audio, and image inputs.

1135 

1136Stream server-sent events from the API

1137 

1138```javascript

1139import { OpenAI } from "openai";

1140const client = new OpenAI();

1141 

1142const stream = await client.responses.create({

1143 model: "gpt-5.6",

1144 input: [

1145 {

1146 role: "user",

1147 content: "Say 'double bubble bath' ten times fast.",

1148 },

1149 ],

1150 stream: true,

1151});

1152 

1153for await (const event of stream) {

1154 console.log(event);

1155}

1156```

1157 

1158```python

1159from openai import OpenAI

1160client = OpenAI()

1161 

1162stream = client.responses.create(

1163 model="gpt-5.6",

1164 input=[

1165 {

1166 "role": "user",

1167 "content": "Say 'double bubble bath' ten times fast.",

1168 },

1169 ],

1170 stream=True,

1171)

1172 

1173for event in stream:

1174 print(event)

1175```

1176 

1177```csharp

1178using OpenAI.Responses;

1179 

1180string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

1181OpenAIResponseClient client = new(model: "gpt-5.6", apiKey: key);

1182 

1183var responses = client.CreateResponseStreamingAsync([

1184 ResponseItem.CreateUserMessageItem([

1185 ResponseContentPart.CreateInputTextPart("Say 'double bubble bath' ten times fast."),

1186 ]),

1187]);

1188 

1189await foreach (var response in responses)

1190{

1191 if (response is StreamingResponseOutputTextDeltaUpdate delta)

1192 {

1193 Console.Write(delta.Delta);

1194 }

1195}

1196```

1197 

1198```ruby

1199require "openai"

1200 

1201openai = OpenAI::Client.new

1202 

1203stream = openai.responses.stream(

1204 model: "gpt-5.6",

1205 input: [

1206 {

1207 role: "user",

1208 content: "Say 'double bubble bath' ten times fast."

1209 }

1210 ]

1211)

1212 

1213stream.each do |event|

1214 puts(event)

1215end

1216```

199 1217 

200Use server‑sent [streaming events](https://developers.openai.com/api/docs/guides/streaming-responses) to show results as they’re generated, or the [Realtime API](https://developers.openai.com/api/docs/guides/realtime) for interactive voice and multimodal apps.

201 1218 

202[1219[

203 1220 


217 1234 

218## Build agents1235## Build agents

219 1236 

220Use the OpenAI platform to build [agents](https://developers.openai.com/api/docs/guides/agents) capable of taking action—like [controlling computers](https://developers.openai.com/api/docs/guides/tools-computer-use)—on behalf of your users. Use the [Agents SDK](https://developers.openai.com/api/docs/guides/agents) to create orchestration logic on the backend.1237Use the OpenAI platform to build [agents](https://developers.openai.com/api/docs/guides/agents) capable of taking action—like [controlling computers](https://developers.openai.com/api/docs/guides/tools-computer-use)—on behalf of your users. Use the [Agents SDK](https://developers.openai.com/api/docs/guides/agents) to create orchestration logic on your server.

1238 

1239Build a language triage agent

1240 

1241```javascript

1242import { Agent, run } from '@openai/agents';

1243 

1244const spanishAgent = new Agent({

1245 name: 'Spanish agent',

1246 instructions: 'You only speak Spanish.',

1247});

1248 

1249const englishAgent = new Agent({

1250 name: 'English agent',

1251 instructions: 'You only speak English',

1252});

1253 

1254const triageAgent = new Agent({

1255 name: 'Triage agent',

1256 instructions:

1257 'Handoff to the appropriate agent based on the language of the request.',

1258 handoffs: [spanishAgent, englishAgent],

1259});

1260 

1261const result = await run(triageAgent, 'Hola, ¿cómo estás?');

1262console.log(result.finalOutput);

1263```

1264 

1265```python

1266from agents import Agent, Runner

1267import asyncio

1268 

1269spanish_agent = Agent(

1270 name="Spanish agent",

1271 instructions="You only speak Spanish.",

1272)

1273 

1274english_agent = Agent(

1275 name="English agent",

1276 instructions="You only speak English",

1277)

1278 

1279triage_agent = Agent(

1280 name="Triage agent",

1281 instructions="Handoff to the appropriate agent based on the language of the request.",

1282 handoffs=[spanish_agent, english_agent],

1283)

1284 

1285 

1286async def main():

1287 result = await Runner.run(triage_agent, input="Hola, ¿cómo estás?")

1288 print(result.final_output)

1289 

1290 

1291if __name__ == "__main__":

1292 asyncio.run(main())

1293```

1294 

221 1295 

222[1296[

223 1297