SpyBara
Go Premium

Documentation 2026-10-01 22:59 UTC to 2026-10-02 23:58 UTC

22 files changed +3,408 −271. View all changes and history on the product overview
2026
Wed 7 13:00 Tue 6 22:58 Mon 5 22:59 Sun 4 22:58 Fri 2 23:58 Thu 1 22:59
Details

85 85 

86#### Python86#### Python

87 87 

88 

89 

90#### Thread object

91 

92```python

93thread = openai.beta.threads.create(

94 messages=[{"role": "user", "content": "what are the 5 Ds of dodgeball?"}],

95 metadata={"user_id": "peter_le_fleur"},

96)

97```

98 

99#### Conversation object

100 

101```python

102conversation = openai.conversations.create(

103 items=[{"role": "user", "content": "what are the 5 Ds of dodgeball?"}],

104 metadata={"user_id": "peter_le_fleur"},

105)

106```

107 

108 

109 

88#### Go110#### Go

89 111 

112 

113 

114#### Thread object (Go)

115 

116```go

117thread, err := client.Beta.Threads.New(context.Background(), openai.BetaThreadNewParams{

118 Messages: []openai.BetaThreadNewParamsMessage{{

119 Role: "user",

120 Content: openai.BetaThreadNewParamsMessageContentUnion{

121 OfString: openai.String("what are the 5 Ds of dodgeball?"),

122 },

123 }},

124 Metadata: shared.Metadata{"user_id": "peter_le_fleur"},

125})

126if err != nil {

127 panic(err)

128}

129```

130 

131#### Conversation object (Go)

132 

133```go

134conversation, err := client.Conversations.New(context.Background(), conversations.ConversationNewParams{

135 Items: []responses.ResponseInputItemUnionParam{

136 responses.ResponseInputItemParamOfMessage("what are the 5 Ds of dodgeball?", responses.EasyInputMessageRoleUser),

137 },

138 Metadata: shared.Metadata{"user_id": "peter_le_fleur"},

139})

140if err != nil {

141 panic(err)

142}

143```

144 

145 

146 

147#### JavaScript

148 

149 

150 

151#### Thread object (JavaScript)

152 

153```javascript

154import OpenAI from "openai";

155 

156const client = new OpenAI();

157const thread = await client.beta.threads.create({

158 messages: [{ role: "user", content: "what are the 5 Ds of dodgeball?" }],

159 metadata: { user_id: "peter_le_fleur" },

160});

161console.log(thread.id);

162```

163 

164#### Conversation object (JavaScript)

165 

166```javascript

167import OpenAI from "openai";

168 

169const client = new OpenAI();

170 

171const conversation = await client.conversations.create({

172 items: [{ role: "user", content: "What are the five Ds of dodgeball?" }],

173 metadata: { user_id: "peter_le_fleur" },

174});

175 

176console.log(conversation.id);

177```

178 

179 

180 

90### Response example181### Response example

91 182 

92 183 


132 223 

133#### Python224#### Python

134 225 

226 

227 

228#### Run object

229 

230```python

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

232import time

233 

234from openai import OpenAI

235 

236openai = OpenAI()

237thread_id = "thread_123"

238assistant_id = "asst_123"

239 

240run = openai.beta.threads.runs.create(

241 thread_id=thread_id,

242 assistant_id=assistant_id,

243)

244 

245while run.status in ("queued", "in_progress"):

246 time.sleep(1)

247 run = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)

248```

249 

250#### Response object

251 

252```python

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

254 

255from openai import OpenAI

256 

257openai = OpenAI()

258conversation_id = "conv_123"

259 

260response = openai.responses.create(

261 model="gpt-6-astra",

262 input=[{"role": "user", "content": "What are the 5 Ds of dodgeball?"}],

263 conversation=conversation_id,

264)

265```

266 

267 

268 

135#### Go269#### Go

136 270 

271 

272 

273#### Run object (Go)

274 

275```go

276run, err := client.Beta.Threads.Runs.New(context.Background(), "thread_abc123", openai.BetaThreadRunNewParams{

277 AssistantID: "asst_abc123",

278})

279if err != nil {

280 panic(err)

281}

282for run.Status == openai.RunStatusQueued || run.Status == openai.RunStatusInProgress {

283 time.Sleep(time.Second)

284 run, err = client.Beta.Threads.Runs.Get(context.Background(), "thread_abc123", run.ID)

285 if err != nil {

286 panic(err)

287 }

288}

289```

290 

291#### Response object (Go)

292 

293```go

294_, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

295 Model: "gpt-6-astra",

296 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{

297 responses.ResponseInputItemParamOfMessage("What are the 5 Ds of dodgeball?", responses.EasyInputMessageRoleUser),

298 }},

299 Conversation: responses.ResponseNewParamsConversationUnion{OfString: openai.String("conv_abc123")},

300})

301if err != nil {

302 panic(err)

303}

304```

305 

306 

307 

308#### JavaScript

309 

310 

311 

312#### Run object (JavaScript)

313 

314```javascript

315import { setTimeout } from "node:timers/promises";

316import OpenAI from "openai";

317 

318const client = new OpenAI();

319// Replace these illustrative IDs with your own resources.

320const threadId = "thread_123";

321const assistantId = "asst_123";

322let run = await client.beta.threads.runs.create(threadId, {

323 assistant_id: assistantId,

324});

325while (run.status === "queued" || run.status === "in_progress") {

326 await setTimeout(1000);

327 run = await client.beta.threads.runs.retrieve(run.id, {

328 thread_id: threadId,

329 });

330}

331console.log(run.status);

332```

333 

334#### Response object (JavaScript)

335 

336```javascript

337// Replace the illustrative IDs and URLs below with your own resource values.

338import OpenAI from "openai";

339 

340const client = new OpenAI();

341const conversationId = "conv_123";

342 

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

344 model: "gpt-6-astra",

345 input: [{ role: "user", content: "What are the five Ds of dodgeball?" }],

346 conversation: conversationId,

347});

348 

349console.log(response.output_text);

350```

351 

352 

353 

137### Response example354### Response example

138 355 

139 356 

deprecations.md +21 −0

Details

34 34 

35Upcoming deprecations are listed below, with the most recent announcements at the top.35Upcoming deprecations are listed below, with the most recent announcements at the top.

36 36 

37### 2026-10-01: GPT-5.3-Codex, GPT-5.1, GPT-5.4-Nano

38 

39The following models are deprecated and will be removed from the API on April 1, 2027, with six months' notice. Migrate to the recommended replacements before the shutdown date.

40 

41| Shutdown date | Model / system | Recommended replacement |

42| ------------- | --------------- | ----------------------- |

43| Apr 1, 2027 | `gpt-5.3-codex` | `gpt-6-sol` |

44| Apr 1, 2027 | `gpt-5.4-nano` | `gpt-6-luna` |

45| Apr 1, 2027 | `gpt-5.1` | `gpt-6-sol` |

46 

47### 2026-10-01: Text-to-speech models

48 

49The following text-to-speech models are deprecated and will be removed from the API on January 6, 2027, with at least three months' notice. Migrate to `gpt-realtime-2.1-mini` before the shutdown date. See the [Realtime API guide](https://developers.openai.com/api/docs/guides/realtime) to plan your migration.

50 

51| Shutdown date | Model / system | Recommended replacement |

52| ------------- | ---------------------------- | ----------------------- |

53| Jan 6, 2027 | `tts-1` | `gpt-realtime-2.1-mini` |

54| Jan 6, 2027 | `tts-1-hd` | `gpt-realtime-2.1-mini` |

55| Jan 6, 2027 | `gpt-4o-mini-tts-2025-03-20` | `gpt-realtime-2.1-mini` |

56| Jan 6, 2027 | `gpt-4o-mini-tts-2025-12-15` | `gpt-realtime-2.1-mini` |

57 

37### 2026-09-11: GPT-5.4-Cyber58### 2026-09-11: GPT-5.4-Cyber

38 59 

39The `gpt-5.4-cyber` model is deprecated and will be removed from the API on October 1, 2026. Migrate to the most capable cyber model available to you before the shutdown date.60The `gpt-5.4-cyber` model is deprecated and will be removed from the API on October 1, 2026. Migrate to the most capable cyber model available to you before the shutdown date.

Details

113 113 

114```javascript114```javascript

115import OpenAI from "openai";115import OpenAI from "openai";

116import { agentFileDestination } from "openai/helpers/beta/agents/filesystem";

116 117 

117const client = new OpenAI();118const client = new OpenAI();

118const stream = await client.beta.agents.sessions.create({119const stream = await client.beta.agents.sessions.create({


133 stream: true,134 stream: true,

134});135});

135 136 

136for await (const event of stream) {137stream.withResultCollection();

138try {

139 for await (const event of stream) {

137 console.log(event);140 console.log(event);

141 }

142 const result = await stream.finalResult();

143 await client.beta.agents.sessions.artifacts.forResult(result).download({

144 path: "/workspace/outputs/summary.json",

145 to: agentFileDestination("summary.json"),

146 });

147} finally {

148 stream.controller.abort();

138}149}

139```150```

140 151 


159 stream=True,170 stream=True,

160)171)

161 172 

162with stream:173with stream.with_result_collection():

163 for event in stream:174 for event in stream:

164 print(event.model_dump_json())175 print(event.model_dump_json())

176 result = stream.get_final_result()

177 

178client.beta.agents.sessions.artifacts.for_result(result).download(

179 "/workspace/outputs/summary.json", to="summary.json"

180)

165```181```

166 182 

167```go183```go


170import (186import (

171 "context"187 "context"

172 "fmt"188 "fmt"

189 "os"

173 190 

174 "github.com/openai/openai-go/v3"191 "github.com/openai/openai-go/v3"

175)192)


189 Input: openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it.")},206 Input: openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it.")},

190 })207 })

191 defer stream.Close()208 defer stream.Close()

192 209 openai.BetaAgentSessionWithResultCollection(stream)

193 for stream.Next() {210 for stream.Next() {

194 fmt.Println(stream.Current().RawJSON())211 fmt.Println(stream.Current().RawJSON())

195 }212 }

196 if err := stream.Err(); err != nil {213 

214 result, err := openai.BetaAgentSessionFinalResult(stream)

215 if err != nil {

216 panic(err)

217 }

218 destination, err := os.Create("summary.json")

219 if err != nil {

220 panic(err)

221 }

222 defer destination.Close()

223 _, err = client.Beta.Agents.Sessions.Artifacts.ForResult(result).Download(ctx, "/workspace/outputs/summary.json", destination)

224 if err != nil {

225 panic(err)

226 }

227 if err := destination.Close(); err != nil {

197 panic(err)228 panic(err)

198 }229 }

199}230}


201 232 

202```java233```java

203import com.openai.client.okhttp.OpenAIOkHttpClient;234import com.openai.client.okhttp.OpenAIOkHttpClient;

235import com.openai.helpers.beta.agents.AgentArtifactDownloads;

204import com.openai.models.beta.agents.EnvironmentParam;236import com.openai.models.beta.agents.EnvironmentParam;

205import com.openai.models.beta.agents.HostedEnvironmentFileParam;237import com.openai.models.beta.agents.HostedEnvironmentFileParam;

206import com.openai.models.beta.agents.sessions.SessionCreateParams;238import com.openai.models.beta.agents.sessions.SessionCreateParams;

239import com.openai.services.beta.agents.AgentTurnResults;

240import java.nio.file.Path;

207 241 

208public class HostedReport {242public class HostedReport {

209 public static void main(String[] args) throws Exception {243 public static void main(String[] args) throws Exception {


230 .build();264 .build();

231 265 

232 try (var stream = client.beta().agents().sessions().createStreaming(params)) {266 try (var stream = client.beta().agents().sessions().createStreaming(params)) {

267 AgentTurnResults.withResultCollection(stream);

233 stream.stream().forEach(System.out::println);268 stream.stream().forEach(System.out::println);

269 var result = AgentTurnResults.getFinalResult(stream);

270 AgentArtifactDownloads.forResult(client.beta().agents().sessions().artifacts(), result)

271 .download("/workspace/outputs/summary.json", Path.of("summary.json"));

234 }272 }

235 }273 }

236}274}


239```ruby277```ruby

240require "openai"278require "openai"

241require "json"279require "json"

280require "pathname"

242 281 

243client = OpenAI::Client.new282client = OpenAI::Client.new

244stream = client.beta.agents.sessions.create_streaming(283stream = client.beta.agents.sessions.create_streaming(


258)297)

259 298 

260begin299begin

300 stream.with_result_collection

261 stream.each { |event| puts event.to_json }301 stream.each { |event| puts event.to_json }

302 result = stream.get_final_result

303 puts result.output_text

304 client.beta.agents.sessions.artifacts.for_result(result).download(

305 path: "/workspace/outputs/summary.json",

306 to: Pathname("summary.json")

307 )

262ensure308ensure

263 stream.close309 stream.close

264end310end

Details

41 "Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",41 "Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",

42 stream: true,42 stream: true,

43});43});

44for await (const event of events) {44events.withResultCollection();

45try {

46 for await (const event of events) {

45 console.log(JSON.stringify(event));47 console.log(JSON.stringify(event));

48 }

49 console.log((await events.finalResult()).output_text);

50} finally {

51 events.controller.abort();

46}52}

47```53```

48 54 


60 environment={"type": "none"},66 environment={"type": "none"},

61 input="Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",67 input="Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",

62 stream=True,68 stream=True,

63) as events:69).with_result_collection() as stream:

64 for event in events:70 for event in stream:

65 print(event.model_dump_json())71 print(event.model_dump_json())

72 result = stream.get_final_result()

73print(result.output_text)

66```74```

67 75 

68```go76```go


81 Environment: openai.EnvironmentParamUnion{OfParamNone: &openai.EnvironmentParamNone{}},89 Environment: openai.EnvironmentParamUnion{OfParamNone: &openai.EnvironmentParamNone{}},

82 Input: openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.")}})90 Input: openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.")}})

83defer events.Close()91defer events.Close()

92openai.BetaAgentSessionWithResultCollection(events)

84for events.Next() {93for events.Next() {

85 fmt.Println(events.Current().RawJSON())94 fmt.Println(events.Current().RawJSON())

86}95}

87if err := events.Err(); err != nil {96result, err := openai.BetaAgentSessionFinalResult(events)

97if err != nil {

88 panic(err)98 panic(err)

89}99}

100fmt.Println(result.OutputText())

90```101```

91 102 

92```java103```java


94import com.openai.client.okhttp.OpenAIOkHttpClient;105import com.openai.client.okhttp.OpenAIOkHttpClient;

95import com.openai.models.beta.agents.MultiAgentConfigParam;106import com.openai.models.beta.agents.MultiAgentConfigParam;

96import com.openai.models.beta.agents.sessions.SessionCreateParams;107import com.openai.models.beta.agents.sessions.SessionCreateParams;

108import com.openai.services.beta.agents.AgentTurnResults;

97 109 

98OpenAIClient client = OpenAIOkHttpClient.fromEnv();110OpenAIClient client = OpenAIOkHttpClient.fromEnv();

99try (var events =111try (var events =


125 + " download URL instead of file bytes. Update clients to fetch that"137 + " download URL instead of file bytes. Update clients to fetch that"

126 + " URL.")138 + " URL.")

127 .build())) {139 .build())) {

140 AgentTurnResults.withResultCollection(events);

128 events.stream().forEach(System.out::println);141 events.stream().forEach(System.out::println);

142 System.out.println(AgentTurnResults.getFinalResult(events).outputText());

129}143}

130```144```

131 145 


148 input: "Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL."162 input: "Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL."

149)163)

150begin164begin

165 events.with_result_collection

151 events.each { |event| puts JSON.generate(event.to_h) }166 events.each { |event| puts JSON.generate(event.to_h) }

167 result = events.get_final_result

168 puts result.output_text

152ensure169ensure

153 events.close170 events.close

154end171end

Details

48 environment={"type": "openai_hosted"},48 environment={"type": "openai_hosted"},

49 input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",49 input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",

50 stream=True,50 stream=True,

51 ) as events:51 ).with_result_collection() as stream:

52 for event in events:52 for event in stream:

53 print(event.to_json(indent=None), flush=True)53 print(event.to_json(indent=None), flush=True)

54 result = stream.get_final_result()

55 print(result.output_text)

56 session_id = result.session_id

54```57```

55 58 

56 59 


93 "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",96 "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",

94 stream: true,97 stream: true,

95});98});

99events.withResultCollection();

96try {100try {

97 for await (const event of events) {101 for await (const event of events) {

98 console.log(JSON.stringify(event));102 console.log(JSON.stringify(event));

99 }103 }

104 const result = await events.finalResult();

105 console.log(result.output_text);

106 console.log("Session:", result.session_id);

100} finally {107} finally {

101 events.controller.abort();108 events.controller.abort();

102}109}


150 },157 },

151})158})

152defer events.Close()159defer events.Close()

160openai.BetaAgentSessionWithResultCollection(events)

153if events.Err() != nil {161if events.Err() != nil {

154 panic(events.Err())162 panic(events.Err())

155}163}


157 event := events.Current()165 event := events.Current()

158 fmt.Println(event.RawJSON())166 fmt.Println(event.RawJSON())

159}167}

160if err := events.Err(); err != nil {168result, err := openai.BetaAgentSessionFinalResult(events)

169if err != nil {

161 panic(err)170 panic(err)

162}171}

172fmt.Println(result.OutputText())

173sessionID := result.SessionID()

174fmt.Println("Session:", sessionID)

163```175```

164 176 

165 177 


201import com.openai.models.beta.agents.AgentSessionEvent;213import com.openai.models.beta.agents.AgentSessionEvent;

202import com.openai.models.beta.agents.EnvironmentParam;214import com.openai.models.beta.agents.EnvironmentParam;

203import com.openai.models.beta.agents.sessions.SessionCreateParams;215import com.openai.models.beta.agents.sessions.SessionCreateParams;

216import com.openai.services.beta.agents.AgentTurnResults;

204 217 

205OpenAIClient client = OpenAIOkHttpClient.fromEnv();218OpenAIClient client = OpenAIOkHttpClient.fromEnv();

206var json = new JsonMapper();219var json = new JsonMapper();


221 "Create tree.py, a Python script that prints a readable tree of the files"234 "Create tree.py, a Python script that prints a readable tree of the files"

222 + " in the current directory. Run it and show me the output.")235 + " in the current directory. Run it and show me the output.")

223 .build())) {236 .build())) {

237 AgentTurnResults.withResultCollection(events);

224 var iterator = events.stream().iterator();238 var iterator = events.stream().iterator();

225 while (iterator.hasNext()) {239 while (iterator.hasNext()) {

226 var event = iterator.next();240 var event = iterator.next();

227 System.out.println(json.writeValueAsString(event));241 System.out.println(json.writeValueAsString(event));

228 }242 }

243 var result = AgentTurnResults.getFinalResult(events);

244 System.out.println(result.outputText());

245 String sessionId = result.sessionId();

246 System.out.println(sessionId);

229}247}

230```248```

231 249 


269 input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."287 input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."

270)288)

271begin289begin

290 events.with_result_collection

272 events.each do |event|291 events.each do |event|

273 puts JSON.generate(event.to_h)292 puts JSON.generate(event.to_h)

274 end293 end

294 result = events.get_final_result

295 puts result.output_text

296 session_id = result.session_id

297 puts "Session: #{session_id}"

275ensure298ensure

276 events.close299 events.close

277end300end

Details

38 "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",38 "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",

39 stream: true,39 stream: true,

40});40});

41events.withResultCollection();

41try {42try {

42 for await (const event of events) {43 for await (const event of events) {

43 console.log(JSON.stringify(event));44 console.log(JSON.stringify(event));

44 }45 }

46 const result = await events.finalResult();

47 console.log(result.output_text);

48 console.log("Session:", result.session_id);

45} finally {49} finally {

46 events.controller.abort();50 events.controller.abort();

47}51}


59 environment={"type": "openai_hosted"},63 environment={"type": "openai_hosted"},

60 input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",64 input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",

61 stream=True,65 stream=True,

62 ) as events:66 ).with_result_collection() as stream:

63 for event in events:67 for event in stream:

64 print(event.to_json(indent=None), flush=True)68 print(event.to_json(indent=None), flush=True)

69 result = stream.get_final_result()

70 print(result.output_text)

71 session_id = result.session_id

65```72```

66 73 

67```go74```go


85 },92 },

86})93})

87defer events.Close()94defer events.Close()

95openai.BetaAgentSessionWithResultCollection(events)

88if events.Err() != nil {96if events.Err() != nil {

89 panic(events.Err())97 panic(events.Err())

90}98}


92 event := events.Current()100 event := events.Current()

93 fmt.Println(event.RawJSON())101 fmt.Println(event.RawJSON())

94}102}

95if err := events.Err(); err != nil {103result, err := openai.BetaAgentSessionFinalResult(events)

104if err != nil {

96 panic(err)105 panic(err)

97}106}

107fmt.Println(result.OutputText())

108sessionID := result.SessionID()

109fmt.Println("Session:", sessionID)

98```110```

99 111 

100```java112```java


105import com.openai.models.beta.agents.AgentSessionEvent;117import com.openai.models.beta.agents.AgentSessionEvent;

106import com.openai.models.beta.agents.EnvironmentParam;118import com.openai.models.beta.agents.EnvironmentParam;

107import com.openai.models.beta.agents.sessions.SessionCreateParams;119import com.openai.models.beta.agents.sessions.SessionCreateParams;

120import com.openai.services.beta.agents.AgentTurnResults;

108 121 

109OpenAIClient client = OpenAIOkHttpClient.fromEnv();122OpenAIClient client = OpenAIOkHttpClient.fromEnv();

110var json = new JsonMapper();123var json = new JsonMapper();


125 "Create tree.py, a Python script that prints a readable tree of the files"138 "Create tree.py, a Python script that prints a readable tree of the files"

126 + " in the current directory. Run it and show me the output.")139 + " in the current directory. Run it and show me the output.")

127 .build())) {140 .build())) {

141 AgentTurnResults.withResultCollection(events);

128 var iterator = events.stream().iterator();142 var iterator = events.stream().iterator();

129 while (iterator.hasNext()) {143 while (iterator.hasNext()) {

130 var event = iterator.next();144 var event = iterator.next();

131 System.out.println(json.writeValueAsString(event));145 System.out.println(json.writeValueAsString(event));

132 }146 }

147 var result = AgentTurnResults.getFinalResult(events);

148 System.out.println(result.outputText());

149 String sessionId = result.sessionId();

150 System.out.println(sessionId);

133}151}

134```152```

135 153 


147 input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."165 input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."

148)166)

149begin167begin

168 events.with_result_collection

150 events.each do |event|169 events.each do |event|

151 puts JSON.generate(event.to_h)170 puts JSON.generate(event.to_h)

152 end171 end

172 result = events.get_final_result

173 puts result.output_text

174 session_id = result.session_id

175 puts "Session: #{session_id}"

153ensure176ensure

154 events.close177 events.close

155end178end

Details

55}55}

56```56```

57 57 

58```java

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

60import com.openai.models.completions.CompletionCreateParams;

61 

62var completion =

63 client

64 .completions()

65 .create(

66 CompletionCreateParams.builder()

67 .model("gpt-3.5-turbo-instruct")

68 .prompt("Write a tagline for an ice cream shop.")

69 .build());

70completion.choices().forEach(choice -> System.out.println(choice.text()));

71```

72 

58```ruby73```ruby

59require "openai"74require "openai"

60 75 

Details

110}110}

111```111```

112 112 

113```java

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

115import com.openai.models.contentprovenancechecks.ContentProvenanceCheckCreateParams;

116import java.nio.file.Path;

117 

118var result =

119 client

120 .contentProvenanceChecks()

121 .create(

122 ContentProvenanceCheckCreateParams.builder().file(Path.of("myimage.png")).build());

123System.out.println(result);

124```

125 

113```ruby126```ruby

114require "openai"127require "openai"

115require "pathname"128require "pathname"

Details

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

233```233```

234 234 

235```go

236import (

237 "context"

238 "encoding/csv"

239 "encoding/json"

240 "fmt"

241 "log"

242 "os"

243 "strings"

244 

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

246)

247 

248func main() {

249 if err := run(); err != nil {

250 log.Fatal(err)

251 }

252}

253 

254func run() error {

255 client := openai.NewClient()

256 ctx := context.Background()

257 reviews := []string{"A rich cup of coffee.", "A bright herbal tea."}

258 if err := os.MkdirAll("output", 0755); err != nil {

259 return err

260 }

261 file, err := os.Create("output/embedded_1k_reviews.csv")

262 if err != nil {

263 return err

264 }

265 defer file.Close()

266 writer := csv.NewWriter(file)

267 if err := writer.Write([]string{"combined", "ada_embedding"}); err != nil {

268 return err

269 }

270 for _, review := range reviews {

271 vector, err := embedding(ctx, &client, strings.ReplaceAll(review, "\n", " "))

272 if err != nil {

273 return err

274 }

275 encoded, err := json.Marshal(vector)

276 if err != nil {

277 return err

278 }

279 if err := writer.Write([]string{review, string(encoded)}); err != nil {

280 return err

281 }

282 }

283 writer.Flush()

284 if err := writer.Error(); err != nil {

285 return err

286 }

287 if err := file.Close(); err != nil {

288 return err

289 }

290 fmt.Println("Saved output/embedded_1k_reviews.csv")

291 return nil

292}

293 

294func embedding(ctx context.Context, client *openai.Client, text string) ([]float64, error) {

295 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{

296 Model: openai.EmbeddingModelTextEmbedding3Small,

297 Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)},

298 })

299 if err != nil {

300 return nil, err

301 }

302 return response.Data[0].Embedding, nil

303}

304```

305 

235```java306```java

236import com.openai.client.OpenAIClient;307import com.openai.client.OpenAIClient;

237import com.openai.client.okhttp.OpenAIOkHttpClient;308import com.openai.client.okhttp.OpenAIOkHttpClient;


268System.out.println(output);339System.out.println(output);

269```340```

270 341 

342```csharp

343using System.Text.Json;

344using OpenAI.Embeddings;

345 

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

347string model = "text-embedding-3-small";

348EmbeddingClient client = new(model, key);

349 

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

351Directory.CreateDirectory("output");

352using StreamWriter writer = new("output/embedded_1k_reviews.csv");

353await writer.WriteLineAsync("combined,ada_embedding");

354foreach (string review in reviews)

355{

356 float[] vector = await EmbedAsync(client, review.Replace("\n", " ", StringComparison.Ordinal));

357 string encoded = JsonSerializer.Serialize(vector);

358 await writer.WriteLineAsync($"{CsvField(review)},{CsvField(encoded)}");

359}

360Console.WriteLine("Saved output/embedded_1k_reviews.csv");

361 

362static async Task<float[]> EmbedAsync(EmbeddingClient client, string text)

363{

364 OpenAIEmbedding result = await client.GenerateEmbeddingAsync(text);

365 return result.ToFloats().ToArray();

366}

367 

368static string CsvField(string value) => "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";

369```

370 

271```ruby371```ruby

272require "csv"372require "csv"

273require "fileutils"373require "fileutils"


502print(response.choices[0].message.content)602print(response.choices[0].message.content)

503```603```

504 604 

605```go

606import (

607 "context"

608 "fmt"

609 "log"

610 

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

612)

613 

614func main() {

615 if err := run(); err != nil {

616 log.Fatal(err)

617 }

618}

619 

620func run() error {

621 client := openai.NewClient()

622 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

623 Model: "gpt-4.1-mini", Temperature: openai.Float(0), Messages: []openai.ChatCompletionMessageParamUnion{

624 openai.SystemMessage("You answer questions about the 2022 Winter Olympics."),

625 openai.UserMessage("Use the article to answer the question. If the answer cannot be found, write \"I don't know.\"\n\nArticle: At the 2022 Winter Olympics, Great Britain won women's curling and Sweden won men's curling.\n\nQuestion: Which athletes won the gold medal in curling at the 2022 Winter Olympics?")},

626 })

627 if err != nil {

628 return err

629 }

630 fmt.Println(completion.Choices[0].Message.Content)

631 return nil

632}

633```

634 

505```java635```java

506import com.openai.client.OpenAIClient;636import com.openai.client.OpenAIClient;

507import com.openai.client.okhttp.OpenAIOkHttpClient;637import com.openai.client.okhttp.OpenAIOkHttpClient;


529 .forEach(System.out::println);659 .forEach(System.out::println);

530```660```

531 661 

662```csharp

663using OpenAI.Chat;

664 

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

666string model = "gpt-4.1-mini";

667ChatClient client = new(model, key);

668 

669string article = "At the 2022 Winter Olympics, Great Britain won women's curling and Sweden won men's curling.";

670string query = $"Use the article to answer the question. If the answer cannot be found, write I don't know.\nArticle: {article}\nQuestion: Which athletes won the gold medal in curling at the 2022 Winter Olympics?";

671ChatCompletion result = await client.CompleteChatAsync(

672 [new SystemChatMessage("You answer questions about the 2022 Winter Olympics."), new UserChatMessage(query)],

673 new ChatCompletionOptions { Temperature = 0 });

674Console.WriteLine(result.Content[0].Text);

675```

676 

532```ruby677```ruby

533require "openai"678require "openai"

534 679 


627res = search_reviews(df, "delicious beans", n=3)772res = search_reviews(df, "delicious beans", n=3)

628```773```

629 774 

775```go

776import (

777 "context"

778 "fmt"

779 "log"

780 "math"

781 "sort"

782 

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

784)

785 

786func main() {

787 if err := run(); err != nil {

788 log.Fatal(err)

789 }

790}

791 

792func run() error {

793 client := openai.NewClient()

794 ctx := context.Background()

795 texts := []string{"A rich cup of coffee.", "Crunchy crackers with sea salt.", "Dark chocolate with orange.", "A bright herbal tea.", "Smooth beans in tomato sauce.", "A mild cheese with herbs.", "Spicy roasted nuts.", "A crisp sparkling water."}

796 vectors := make([][]float64, len(texts))

797 for i, text := range texts {

798 vector, err := embedding(ctx, &client, text)

799 if err != nil {

800 return err

801 }

802 vectors[i] = vector

803 }

804 query, err := embedding(ctx, &client, "delicious beans")

805 if err != nil {

806 return err

807 }

808 matches := nearest(query, vectors)

809 for _, match := range matches[:min(3, len(matches))] {

810 fmt.Printf("%0.3f: %s\n", match.Similarity, texts[match.Index])

811 }

812 return nil

813}

814 

815func embedding(ctx context.Context, client *openai.Client, text string) ([]float64, error) {

816 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{

817 Model: openai.EmbeddingModelTextEmbedding3Small,

818 Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)},

819 })

820 if err != nil {

821 return nil, err

822 }

823 return response.Data[0].Embedding, nil

824}

825 

826func cosineSimilarity(a, b []float64) float64 {

827 var dot, left, right float64

828 for i := range a {

829 dot += a[i] * b[i]

830 left += a[i] * a[i]

831 right += b[i] * b[i]

832 }

833 return dot / math.Sqrt(left*right)

834}

835 

836type match struct {

837 Index int

838 Similarity float64

839}

840 

841func nearest(query []float64, vectors [][]float64) []match {

842 matches := make([]match, len(vectors))

843 for i, vector := range vectors {

844 matches[i] = match{Index: i, Similarity: cosineSimilarity(query, vector)}

845 }

846 sort.SliceStable(matches, func(i, j int) bool { return matches[i].Similarity > matches[j].Similarity })

847 return matches

848}

849```

850 

630```java851```java

631import com.openai.client.OpenAIClient;852import com.openai.client.OpenAIClient;

632import com.openai.client.okhttp.OpenAIOkHttpClient;853import com.openai.client.okhttp.OpenAIOkHttpClient;


673 .forEach(System.out::println);894 .forEach(System.out::println);

674```895```

675 896 

897```csharp

898using OpenAI.Embeddings;

899 

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

901string model = "text-embedding-3-small";

902EmbeddingClient client = new(model, key);

903 

904string[] texts = ["A rich cup of coffee.", "Crunchy crackers with sea salt.", "Dark chocolate with orange.", "A bright herbal tea.", "Smooth beans in tomato sauce.", "A mild cheese with herbs.", "Spicy roasted nuts.", "A crisp sparkling water."];

905OpenAIEmbeddingCollection batch = await client.GenerateEmbeddingsAsync(texts);

906float[][] vectors = batch.Select(item => item.ToFloats().ToArray()).ToArray();

907float[] query = await EmbedAsync(client, "delicious beans");

908var ranked = vectors.Select((vector, index) => new { Index = index, Similarity = CosineSimilarity(query, vector) }).OrderByDescending(match => match.Similarity);

909foreach (var match in ranked.Take(3))

910{

911 Console.WriteLine($"{match.Similarity:F3}: {texts[match.Index]}");

912}

913 

914static async Task<float[]> EmbedAsync(EmbeddingClient client, string text)

915{

916 OpenAIEmbedding result = await client.GenerateEmbeddingAsync(text);

917 return result.ToFloats().ToArray();

918}

919 

920static double CosineSimilarity(float[] left, float[] right)

921{

922 double dot = 0, leftNorm = 0, rightNorm = 0;

923 for (int i = 0; i < left.Length; i++)

924 {

925 dot += left[i] * right[i];

926 leftNorm += left[i] * left[i];

927 rightNorm += right[i] * right[i];

928 }

929 return dot / Math.Sqrt(leftNorm * rightNorm);

930}

931```

932 

676```ruby933```ruby

677require "openai"934require "openai"

678 935 


778res = search_functions(df, "Completions API tests", n=3)1035res = search_functions(df, "Completions API tests", n=3)

779```1036```

780 1037 

1038```go

1039import (

1040 "context"

1041 "fmt"

1042 "log"

1043 "math"

1044 "sort"

1045 

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

1047)

1048 

1049func main() {

1050 if err := run(); err != nil {

1051 log.Fatal(err)

1052 }

1053}

1054 

1055func run() error {

1056 client := openai.NewClient()

1057 ctx := context.Background()

1058 texts := []string{"def add(a, b): return a + b", "def complete(prompt): return prompt"}

1059 vectors := make([][]float64, len(texts))

1060 for i, text := range texts {

1061 vector, err := embedding(ctx, &client, text)

1062 if err != nil {

1063 return err

1064 }

1065 vectors[i] = vector

1066 }

1067 query, err := embedding(ctx, &client, "Completions API tests")

1068 if err != nil {

1069 return err

1070 }

1071 matches := nearest(query, vectors)

1072 for _, match := range matches[:min(3, len(matches))] {

1073 fmt.Printf("%0.3f: %s\n", match.Similarity, texts[match.Index])

1074 }

1075 return nil

1076}

1077 

1078func embedding(ctx context.Context, client *openai.Client, text string) ([]float64, error) {

1079 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{

1080 Model: openai.EmbeddingModelTextEmbedding3Small,

1081 Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)},

1082 })

1083 if err != nil {

1084 return nil, err

1085 }

1086 return response.Data[0].Embedding, nil

1087}

1088 

1089func cosineSimilarity(a, b []float64) float64 {

1090 var dot, left, right float64

1091 for i := range a {

1092 dot += a[i] * b[i]

1093 left += a[i] * a[i]

1094 right += b[i] * b[i]

1095 }

1096 return dot / math.Sqrt(left*right)

1097}

1098 

1099type match struct {

1100 Index int

1101 Similarity float64

1102}

1103 

1104func nearest(query []float64, vectors [][]float64) []match {

1105 matches := make([]match, len(vectors))

1106 for i, vector := range vectors {

1107 matches[i] = match{Index: i, Similarity: cosineSimilarity(query, vector)}

1108 }

1109 sort.SliceStable(matches, func(i, j int) bool { return matches[i].Similarity > matches[j].Similarity })

1110 return matches

1111}

1112```

1113 

781```java1114```java

782import com.openai.client.OpenAIClient;1115import com.openai.client.OpenAIClient;

783import com.openai.client.okhttp.OpenAIOkHttpClient;1116import com.openai.client.okhttp.OpenAIOkHttpClient;


819 .forEach(System.out::println);1152 .forEach(System.out::println);

820```1153```

821 1154 

1155```csharp

1156using OpenAI.Embeddings;

1157 

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

1159string model = "text-embedding-3-small";

1160EmbeddingClient client = new(model, key);

1161 

1162string[] texts = ["def add(a, b): return a + b", "def complete(prompt): return prompt"];

1163List<float[]> vectors = [];

1164foreach (string text in texts)

1165{

1166 vectors.Add(await EmbedAsync(client, text));

1167}

1168float[] query = await EmbedAsync(client, "Completions API tests");

1169var ranked = vectors.Select((vector, index) => new { Index = index, Similarity = CosineSimilarity(query, vector) }).OrderByDescending(match => match.Similarity);

1170foreach (var match in ranked.Take(3))

1171{

1172 Console.WriteLine($"{match.Similarity:F3}: {texts[match.Index]}");

1173}

1174 

1175static async Task<float[]> EmbedAsync(EmbeddingClient client, string text)

1176{

1177 OpenAIEmbedding result = await client.GenerateEmbeddingAsync(text);

1178 return result.ToFloats().ToArray();

1179}

1180 

1181static double CosineSimilarity(float[] left, float[] right)

1182{

1183 double dot = 0, leftNorm = 0, rightNorm = 0;

1184 for (int i = 0; i < left.Length; i++)

1185 {

1186 dot += left[i] * right[i];

1187 leftNorm += left[i] * left[i];

1188 rightNorm += right[i] * right[i];

1189 }

1190 return dot / Math.Sqrt(leftNorm * rightNorm);

1191}

1192```

1193 

822```ruby1194```ruby

823require "openai"1195require "openai"

824 1196 


928 return indices_of_nearest_neighbors1300 return indices_of_nearest_neighbors

929```1301```

930 1302 

1303```go

1304import (

1305 "context"

1306 "fmt"

1307 "log"

1308 "math"

1309 "sort"

1310 

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

1312)

1313 

1314func main() {

1315 if err := run(); err != nil {

1316 log.Fatal(err)

1317 }

1318}

1319 

1320func run() error {

1321 client := openai.NewClient()

1322 ctx := context.Background()

1323 texts := []string{"A cheetah is a fast land animal.", "A peregrine falcon is a fast bird.", "A tortoise moves slowly."}

1324 vectors := make([][]float64, len(texts))

1325 for i, text := range texts {

1326 vector, err := embedding(ctx, &client, text)

1327 if err != nil {

1328 return err

1329 }

1330 vectors[i] = vector

1331 }

1332 query := vectors[0]

1333 matches := nearest(query, vectors)

1334 for _, match := range matches {

1335 fmt.Println(match.Index)

1336 }

1337 return nil

1338}

1339 

1340func embedding(ctx context.Context, client *openai.Client, text string) ([]float64, error) {

1341 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{

1342 Model: openai.EmbeddingModelTextEmbedding3Small,

1343 Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)},

1344 })

1345 if err != nil {

1346 return nil, err

1347 }

1348 return response.Data[0].Embedding, nil

1349}

1350 

1351func cosineSimilarity(a, b []float64) float64 {

1352 var dot, left, right float64

1353 for i := range a {

1354 dot += a[i] * b[i]

1355 left += a[i] * a[i]

1356 right += b[i] * b[i]

1357 }

1358 return dot / math.Sqrt(left*right)

1359}

1360 

1361type match struct {

1362 Index int

1363 Similarity float64

1364}

1365 

1366func nearest(query []float64, vectors [][]float64) []match {

1367 matches := make([]match, len(vectors))

1368 for i, vector := range vectors {

1369 matches[i] = match{Index: i, Similarity: cosineSimilarity(query, vector)}

1370 }

1371 sort.SliceStable(matches, func(i, j int) bool { return matches[i].Similarity > matches[j].Similarity })

1372 return matches

1373}

1374```

1375 

931```java1376```java

932import com.openai.client.OpenAIClient;1377import com.openai.client.OpenAIClient;

933import com.openai.client.okhttp.OpenAIOkHttpClient;1378import com.openai.client.okhttp.OpenAIOkHttpClient;


975System.out.println(nearestNeighbors);1420System.out.println(nearestNeighbors);

976```1421```

977 1422 

1423```csharp

1424using OpenAI.Embeddings;

1425 

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

1427string model = "text-embedding-3-small";

1428EmbeddingClient client = new(model, key);

1429 

1430string[] texts = ["A cheetah is a fast land animal.", "A peregrine falcon is a fast bird.", "A tortoise moves slowly."];

1431List<float[]> vectors = [];

1432foreach (string text in texts)

1433{

1434 vectors.Add(await EmbedAsync(client, text));

1435}

1436float[] query = vectors[0];

1437var ranked = vectors.Select((vector, index) => new { Index = index, Similarity = CosineSimilarity(query, vector) }).OrderByDescending(match => match.Similarity);

1438foreach (var match in ranked)

1439{

1440 Console.WriteLine(match.Index);

1441}

1442 

1443static async Task<float[]> EmbedAsync(EmbeddingClient client, string text)

1444{

1445 OpenAIEmbedding result = await client.GenerateEmbeddingAsync(text);

1446 return result.ToFloats().ToArray();

1447}

1448 

1449static double CosineSimilarity(float[] left, float[] right)

1450{

1451 double dot = 0, leftNorm = 0, rightNorm = 0;

1452 for (int i = 0; i < left.Length; i++)

1453 {

1454 dot += left[i] * right[i];

1455 leftNorm += left[i] * left[i];

1456 rightNorm += right[i] * right[i];

1457 }

1458 return dot / Math.Sqrt(leftNorm * rightNorm);

1459}

1460```

1461 

978```ruby1462```ruby

979require "openai"1463require "openai"

980 1464 


1200)1684)

1201```1685```

1202 1686 

1687```go

1688import (

1689 "context"

1690 "fmt"

1691 "log"

1692 "math"

1693 

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

1695)

1696 

1697func main() {

1698 if err := run(); err != nil {

1699 log.Fatal(err)

1700 }

1701}

1702 

1703func run() error {

1704 client := openai.NewClient()

1705 ctx := context.Background()

1706 negative, err := embedding(ctx, &client, "negative")

1707 if err != nil {

1708 return err

1709 }

1710 positive, err := embedding(ctx, &client, "positive")

1711 if err != nil {

1712 return err

1713 }

1714 review, err := embedding(ctx, &client, "Sample Review")

1715 if err != nil {

1716 return err

1717 }

1718 score := cosineSimilarity(review, positive) - cosineSimilarity(review, negative)

1719 prediction := "negative"

1720 if score > 0 {

1721 prediction = "positive"

1722 }

1723 fmt.Println(prediction)

1724 return nil

1725}

1726 

1727func embedding(ctx context.Context, client *openai.Client, text string) ([]float64, error) {

1728 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{

1729 Model: openai.EmbeddingModelTextEmbedding3Small,

1730 Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)},

1731 })

1732 if err != nil {

1733 return nil, err

1734 }

1735 return response.Data[0].Embedding, nil

1736}

1737 

1738func cosineSimilarity(a, b []float64) float64 {

1739 var dot, left, right float64

1740 for i := range a {

1741 dot += a[i] * b[i]

1742 left += a[i] * a[i]

1743 right += b[i] * b[i]

1744 }

1745 return dot / math.Sqrt(left*right)

1746}

1747```

1748 

1203```java1749```java

1204import com.openai.client.OpenAIClient;1750import com.openai.client.OpenAIClient;

1205import com.openai.client.okhttp.OpenAIOkHttpClient;1751import com.openai.client.okhttp.OpenAIOkHttpClient;


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

1223```1769```

1224 1770 

1771```csharp

1772using OpenAI.Embeddings;

1773 

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

1775string model = "text-embedding-3-small";

1776EmbeddingClient client = new(model, key);

1777 

1778float[] negative = await EmbedAsync(client, "negative");

1779float[] positive = await EmbedAsync(client, "positive");

1780float[] review = await EmbedAsync(client, "Sample Review");

1781double score = CosineSimilarity(review, positive) - CosineSimilarity(review, negative);

1782Console.WriteLine(score > 0 ? "positive" : "negative");

1783 

1784static async Task<float[]> EmbedAsync(EmbeddingClient client, string text)

1785{

1786 OpenAIEmbedding result = await client.GenerateEmbeddingAsync(text);

1787 return result.ToFloats().ToArray();

1788}

1789 

1790static double CosineSimilarity(float[] left, float[] right)

1791{

1792 double dot = 0, leftNorm = 0, rightNorm = 0;

1793 for (int i = 0; i < left.Length; i++)

1794 {

1795 dot += left[i] * right[i];

1796 leftNorm += left[i] * left[i];

1797 rightNorm += right[i] * right[i];

1798 }

1799 return dot / Math.Sqrt(leftNorm * rightNorm);

1800}

1801```

1802 

1225```ruby1803```ruby

1226require "openai"1804require "openai"

1227 1805 

Details

810}810}

811```811```

812 812 

813```java

814import com.fasterxml.jackson.databind.JsonNode;

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

816import java.util.Map;

817 

818var argsJson = new ObjectMapper().readTree("{\"location\":\"Paris, France\"}");

819System.out.println(callFunction("get_weather", argsJson));

820 

821// These local fixtures demonstrate dispatch; replace them with your application services.

822// The email fixture prints its inputs and does not send a message.

823static Map<String, Object> callFunction(String name, JsonNode arguments) {

824 return switch (name) {

825 case "get_weather" -> getWeather(arguments.get("location").asText());

826 case "send_email" -> sendEmail(arguments.get("to").asText(), arguments.get("body").asText());

827 default -> throw new IllegalArgumentException("Unknown function: " + name);

828 };

829}

830 

831private static Map<String, Object> getWeather(String location) {

832 int temperature =

833 switch (location) {

834 case "Bogotá, Colombia" -> 18;

835 case "Paris, France" -> 15;

836 default -> 20;

837 };

838 return Map.of("location", location, "temperature_celsius", temperature);

839}

840 

841private static Map<String, Object> sendEmail(String to, String body) {

842 System.out.println("Sending email to " + to + ": " + body);

843 return Map.of("status", "sent");

844}

845```

846 

847```csharp

848using System.Text.Json;

849 

850using JsonDocument arguments = JsonDocument.Parse("{\"location\":\"Paris, France\"}");

851Console.WriteLine(FunctionDispatcher.CallFunction("get_weather", arguments.RootElement));

852 

853internal static class FunctionDispatcher

854{

855 // These local fixtures demonstrate dispatch; replace them with your application services.

856 // The email fixture prints its inputs and does not send a message.

857 internal static string CallFunction(string name, JsonElement arguments) => name switch

858 {

859 "get_weather" => GetWeather(arguments.GetProperty("location").GetString()!),

860 "send_email" => SendEmail(arguments.GetProperty("to").GetString()!, arguments.GetProperty("body").GetString()!),

861 _ => throw new ArgumentException($"Unknown function: {name}", nameof(name))

862 };

863 private static string GetWeather(string location) => JsonSerializer.Serialize(new { location, temperature_celsius = location switch { "Bogotá, Colombia" => 18, "Paris, France" => 15, _ => 20 } });

864 private static string SendEmail(string to, string body)

865 {

866 Console.WriteLine($"Sending email to {to}: {body}");

867 return "{\"status\":\"sent\"}";

868 }

869}

870```

871 

813```ruby872```ruby

814def call_function(name, arguments)873def call_function(name, arguments)

815 case name874 case name

Details

1604}1604}

1605```1605```

1606 1606 

1607```java

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

1609import com.openai.models.images.ImageGenerateParams;

1610import java.nio.file.Files;

1611import java.nio.file.Path;

1612import java.util.Base64;

1613 

1614var params =

1615 ImageGenerateParams.builder()

1616 .prompt(

1617 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape")

1618 .model("gpt-image-2.5-sunburst")

1619 .partialImages(2)

1620 .build();

1621try (var stream = client.images().generateStreaming(params)) {

1622 var events = stream.stream().iterator();

1623 while (events.hasNext()) {

1624 var event = events.next();

1625 if (event.generationPartialImage().isPresent()) {

1626 var partial = event.generationPartialImage().orElseThrow();

1627 Files.write(

1628 Path.of("river" + partial.partialImageIndex() + ".png"),

1629 Base64.getDecoder().decode(partial.b64Json()));

1630 }

1631 }

1632}

1633```

1634 

1607```ruby1635```ruby

1608require "base64"1636require "base64"

1609require "openai"1637require "openai"


1825}1853}

1826```1854```

1827 1855 

1856```java

1857import java.nio.file.Files;

1858import java.nio.file.Path;

1859import java.util.Base64;

1860 

1861System.out.println(encodeImage(Path.of("example.png")));

1862 

1863private static String encodeImage(Path path) throws java.io.IOException {

1864 return Base64.getEncoder().encodeToString(Files.readAllBytes(path));

1865}

1866```

1867 

1868```csharp

1869using System;

1870 

1871Console.WriteLine(EncodeImage("example.png"));

1872 

1873static string EncodeImage(string filePath) => Convert.ToBase64String(File.ReadAllBytes(filePath));

1874```

1875 

1828```ruby1876```ruby

1829require "base64"1877require "base64"

1830 1878 

Details

166 return completion.choices[0].message.content166 return completion.choices[0].message.content

167````167````

168 168 

169````go

170import (

171 "context"

172 "fmt"

173 "log"

174 

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

176)

177 

178func main() {

179 if err := run(); err != nil {

180 log.Fatal(err)

181 }

182}

183 

184func run() error {

185 client := openai.NewClient()

186 metaPrompt := "Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.\n" +

187 "\n" +

188 "# Guidelines\n" +

189 "\n" +

190 "- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +

191 "- 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.\n" +

192 "- 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!\n" +

193 " - 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.\n" +

194 " - Conclusion, classifications, or results should ALWAYS appear last.\n" +

195 "- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +

196 " - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +

197 "- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +

198 "- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.\n" +

199 "- 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.\n" +

200 "- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +

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

202 " - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.\n" +

203 " - JSON should never be wrapped in code blocks (```) unless explicitly requested.\n" +

204 "\n" +

205 "The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +

206 "\n" +

207 "[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +

208 "\n" +

209 "[Additional details as needed.]\n" +

210 "\n" +

211 "[Optional sections with headings or bullet points for detailed steps.]\n" +

212 "\n" +

213 "# Steps [optional]\n" +

214 "\n" +

215 "[optional: a detailed breakdown of the steps necessary to accomplish the task]\n" +

216 "\n" +

217 "# Output Format\n" +

218 "\n" +

219 "[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]\n" +

220 "\n" +

221 "# Examples [optional]\n" +

222 "\n" +

223 "[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.]\n" +

224 "[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! ]\n" +

225 "\n" +

226 "# Notes [optional]\n" +

227 "\n" +

228 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"

229 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

230 Model: "gpt-6-astra",

231 Messages: []openai.ChatCompletionMessageParamUnion{

232 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

233 }})

234 if err != nil {

235 return err

236 }

237 fmt.Println(completion.Choices[0].Message.Content)

238 return nil

239}

240````

241 

169````java242````java

170import com.openai.client.OpenAIClient;243import com.openai.client.OpenAIClient;

171import com.openai.client.okhttp.OpenAIOkHttpClient;244import com.openai.client.okhttp.OpenAIOkHttpClient;


232 .forEach(System.out::println);305 .forEach(System.out::println);

233````306````

234 307 

308````csharp

309using OpenAI.Chat;

310 

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

312string model = "gpt-6-astra";

313ChatClient client = new(model, key);

314 

315string metaPrompt = """"

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

317

318 # Guidelines

319

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

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

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

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

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

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

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

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

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

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

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

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

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

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

334

335 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

336

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

338

339 [Additional details as needed.]

340

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

342

343 # Steps [optional]

344

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

346

347 # Output Format

348

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

350

351 # Examples [optional]

352

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

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

355

356 # Notes [optional]

357

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

359 """";

360ChatCompletionOptions options = new();

361ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);

362Console.WriteLine(result.Content[0].Text);

363````

364 

235````ruby365````ruby

236require "openai"366require "openai"

237 367 


433 return completion.choices[0].message.content563 return completion.choices[0].message.content

434```564```

435 565 

566```go

567import (

568 "context"

569 "fmt"

570 "log"

571 

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

573)

574 

575func main() {

576 if err := run(); err != nil {

577 log.Fatal(err)

578 }

579}

580 

581func run() error {

582 client := openai.NewClient()

583 metaPrompt := "Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.\n" +

584 "\n" +

585 "# Guidelines\n" +

586 "\n" +

587 "- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +

588 "- 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.\n" +

589 "- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.\n" +

590 "- 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.\n" +

591 "- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +

592 " - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +

593 " - It is very important that any examples included reflect the short, conversational output responses of the model.\n" +

594 "Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.\n" +

595 " - 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.\n" +

596 " - 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.\n" +

597 "- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +

598 "- 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.\n" +

599 "- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +

600 "\n" +

601 "The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +

602 "\n" +

603 "[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +

604 "\n" +

605 "[Additional details as needed.]\n" +

606 "\n" +

607 "[Optional sections with headings or bullet points for detailed steps.]\n" +

608 "\n" +

609 "# Examples [optional]\n" +

610 "\n" +

611 "[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.]\n" +

612 "[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! ]\n" +

613 "\n" +

614 "# Notes [optional]\n" +

615 "\n" +

616 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"

617 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

618 Model: "gpt-6-astra",

619 Messages: []openai.ChatCompletionMessageParamUnion{

620 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

621 }})

622 if err != nil {

623 return err

624 }

625 fmt.Println(completion.Choices[0].Message.Content)

626 return nil

627}

628```

629 

436```java630```java

437import com.openai.client.OpenAIClient;631import com.openai.client.OpenAIClient;

438import com.openai.client.okhttp.OpenAIOkHttpClient;632import com.openai.client.okhttp.OpenAIOkHttpClient;


491 .forEach(System.out::println);685 .forEach(System.out::println);

492```686```

493 687 

688```csharp

689using OpenAI.Chat;

690 

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

692string model = "gpt-6-astra";

693ChatClient client = new(model, key);

694 

695string metaPrompt = """"

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

697

698 # Guidelines

699

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

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

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

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

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

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

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

707 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.

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

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

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

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

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

713

714 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

715

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

717

718 [Additional details as needed.]

719

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

721

722 # Examples [optional]

723

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

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

726

727 # Notes [optional]

728

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

730 """";

731ChatCompletionOptions options = new();

732ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);

733Console.WriteLine(result.Content[0].Text);

734```

735 

494```ruby736```ruby

495require "openai"737require "openai"

496 738 


742 return completion.choices[0].message.content984 return completion.choices[0].message.content

743````985````

744 986 

987````go

988import (

989 "context"

990 "fmt"

991 "log"

992 

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

994)

995 

996func main() {

997 if err := run(); err != nil {

998 log.Fatal(err)

999 }

1000}

1001 

1002func run() error {

1003 client := openai.NewClient()

1004 metaPrompt := "Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.\n" +

1005 "\n" +

1006 "Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:\n" +

1007 "<reasoning>\n" +

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

1009 "- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?\n" +

1010 " - Identify: (max 10 words) if so, which section(s) utilize reasoning?\n" +

1011 " - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?\n" +

1012 " - Ordering: (before/after) is the chain of though located before or after\n" +

1013 "- Structure: (yes/no) does the input prompt have a well defined structure\n" +

1014 "- Examples: (yes/no) does the input prompt have few-shot examples\n" +

1015 " - Representative: (1-5) if present, how representative are the examples?\n" +

1016 "- Complexity: (1-5) how complex is the input prompt?\n" +

1017 " - Task: (1-5) how complex is the implied task?\n" +

1018 " - Necessity: ()\n" +

1019 "- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)\n" +

1020 "- Prioritization: (list) what 1-3 categories are the MOST important to address.\n" +

1021 "- 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\n" +

1022 "</reasoning>\n" +

1023 "\n" +

1024 "# Guidelines\n" +

1025 "\n" +

1026 "- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +

1027 "- 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.\n" +

1028 "- 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!\n" +

1029 " - 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.\n" +

1030 " - Conclusion, classifications, or results should ALWAYS appear last.\n" +

1031 "- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +

1032 " - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +

1033 "- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +

1034 "- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.\n" +

1035 "- 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.\n" +

1036 "- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +

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

1038 " - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.\n" +

1039 " - JSON should never be wrapped in code blocks (```) unless explicitly requested.\n" +

1040 "\n" +

1041 "The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +

1042 "\n" +

1043 "[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +

1044 "\n" +

1045 "[Additional details as needed.]\n" +

1046 "\n" +

1047 "[Optional sections with headings or bullet points for detailed steps.]\n" +

1048 "\n" +

1049 "# Steps [optional]\n" +

1050 "\n" +

1051 "[optional: a detailed breakdown of the steps necessary to accomplish the task]\n" +

1052 "\n" +

1053 "# Output Format\n" +

1054 "\n" +

1055 "[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]\n" +

1056 "\n" +

1057 "# Examples [optional]\n" +

1058 "\n" +

1059 "[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.]\n" +

1060 "[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! ]\n" +

1061 "\n" +

1062 "# Notes [optional]\n" +

1063 "\n" +

1064 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +

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

1066 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

1067 Model: "gpt-6-astra",

1068 Messages: []openai.ChatCompletionMessageParamUnion{

1069 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

1070 }})

1071 if err != nil {

1072 return err

1073 }

1074 fmt.Println(completion.Choices[0].Message.Content)

1075 return nil

1076}

1077````

1078 

745````java1079````java

746import com.openai.client.OpenAIClient;1080import com.openai.client.OpenAIClient;

747import com.openai.client.okhttp.OpenAIOkHttpClient;1081import com.openai.client.okhttp.OpenAIOkHttpClient;


827 .forEach(System.out::println);1161 .forEach(System.out::println);

828````1162````

829 1163 

1164````csharp

1165using OpenAI.Chat;

1166 

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

1168string model = "gpt-6-astra";

1169ChatClient client = new(model, key);

1170 

1171string metaPrompt = """"

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

1173

1174 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:

1175 <reasoning>

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

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

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

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

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

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

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

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

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

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

1186 - Necessity: ()

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

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

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

1190 </reasoning>

1191

1192 # Guidelines

1193

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1208

1209 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

1210

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

1212

1213 [Additional details as needed.]

1214

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

1216

1217 # Steps [optional]

1218

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

1220

1221 # Output Format

1222

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

1224

1225 # Examples [optional]

1226

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

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

1229

1230 # Notes [optional]

1231

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

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

1234 """";

1235ChatCompletionOptions options = new();

1236ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);

1237Console.WriteLine(result.Content[0].Text);

1238````

1239 

830````ruby1240````ruby

831require "openai"1241require "openai"

832 1242 


1087 return completion.choices[0].message.content1497 return completion.choices[0].message.content

1088```1498```

1089 1499 

1500```go

1501import (

1502 "context"

1503 "fmt"

1504 "log"

1505 

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

1507)

1508 

1509func main() {

1510 if err := run(); err != nil {

1511 log.Fatal(err)

1512 }

1513}

1514 

1515func run() error {

1516 client := openai.NewClient()

1517 metaPrompt := "Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.\n" +

1518 "\n" +

1519 "Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:\n" +

1520 "<reasoning>\n" +

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

1522 "- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?\n" +

1523 " - Identify: (max 10 words) if so, which section(s) utilize reasoning?\n" +

1524 " - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?\n" +

1525 " - Ordering: (before/after) is the chain of though located before or after\n" +

1526 "- Structure: (yes/no) does the input prompt have a well defined structure\n" +

1527 "- Examples: (yes/no) does the input prompt have few-shot examples\n" +

1528 " - Representative: (1-5) if present, how representative are the examples?\n" +

1529 "- Complexity: (1-5) how complex is the input prompt?\n" +

1530 " - Task: (1-5) how complex is the implied task?\n" +

1531 " - Necessity: ()\n" +

1532 "- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)\n" +

1533 "- Prioritization: (list) what 1-3 categories are the MOST important to address.\n" +

1534 "- 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\n" +

1535 "</reasoning>\n" +

1536 "\n" +

1537 "# Guidelines\n" +

1538 "\n" +

1539 "- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +

1540 "- 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.\n" +

1541 "- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.\n" +

1542 "- 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.\n" +

1543 "- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +

1544 " - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +

1545 " - It is very important that any examples included reflect the short, conversational output responses of the model.\n" +

1546 "Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.\n" +

1547 " - 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.\n" +

1548 " - 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.\n" +

1549 "- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +

1550 "- 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.\n" +

1551 "- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +

1552 "\n" +

1553 "The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +

1554 "\n" +

1555 "[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +

1556 "\n" +

1557 "[Additional details as needed.]\n" +

1558 "\n" +

1559 "[Optional sections with headings or bullet points for detailed steps.]\n" +

1560 "\n" +

1561 "# Examples [optional]\n" +

1562 "\n" +

1563 "[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.]\n" +

1564 "[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! ]\n" +

1565 "\n" +

1566 "# Notes [optional]\n" +

1567 "\n" +

1568 "[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +

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

1570 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

1571 Model: "gpt-6-astra",

1572 Messages: []openai.ChatCompletionMessageParamUnion{

1573 openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),

1574 }})

1575 if err != nil {

1576 return err

1577 }

1578 fmt.Println(completion.Choices[0].Message.Content)

1579 return nil

1580}

1581```

1582 

1090```java1583```java

1091import com.openai.client.OpenAIClient;1584import com.openai.client.OpenAIClient;

1092import com.openai.client.okhttp.OpenAIOkHttpClient;1585import com.openai.client.okhttp.OpenAIOkHttpClient;


1163 .forEach(System.out::println);1656 .forEach(System.out::println);

1164```1657```

1165 1658 

1659```csharp

1660using OpenAI.Chat;

1661 

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

1663string model = "gpt-6-astra";

1664ChatClient client = new(model, key);

1665 

1666string metaPrompt = """"

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

1668

1669 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:

1670 <reasoning>

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

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

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

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

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

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

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

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

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

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

1681 - Necessity: ()

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

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

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

1685 </reasoning>

1686

1687 # Guidelines

1688

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

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

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

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

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

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

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

1696 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.

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

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

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

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

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

1702

1703 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")

1704

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

1706

1707 [Additional details as needed.]

1708

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

1710

1711 # Examples [optional]

1712

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

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

1715

1716 # Notes [optional]

1717

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

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

1720 """";

1721ChatCompletionOptions options = new();

1722ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);

1723Console.WriteLine(result.Content[0].Text);

1724```

1725 

1166```ruby1726```ruby

1167require "openai"1727require "openai"

1168 1728 


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

1861```2421```

1862 2422 

1863```java2423```go

1864import com.openai.client.OpenAIClient;2424import (

1865import com.openai.client.okhttp.OpenAIOkHttpClient;2425 "context"

1866import com.openai.core.JsonValue;2426 "encoding/json"

1867import com.openai.models.chat.completions.ChatCompletionCreateParams;2427 "fmt"

1868import java.util.List;2428 "log"

1869import java.util.Map;

1870 2429 

1871String metaPrompt =2430 "github.com/openai/openai-go/v3"

1872 """2431 "github.com/openai/openai-go/v3/shared"

1873 # Instructions2432)

1874 Return a valid schema for the described JSON.2433 

2434func main() {

2435 if err := run(); err != nil {

2436 log.Fatal(err)

2437 }

2438}

2439 

2440func run() error {

2441 client := openai.NewClient()

2442 metaPrompt := "# Instructions\n" +

2443 "Return a valid schema for the described JSON.\n" +

2444 "\n" +

2445 "You must also make sure:\n" +

2446 "- all fields in an object are set as required\n" +

2447 "- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED\n" +

2448 "- all objects must have additionalProperties set to false\n" +

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

2450 "- all objects must have properties defined\n" +

2451 "- field order matters. any form of \"thinking\" or \"explanation\" should come before the conclusion\n" +

2452 "- $defs must be defined under the schema param\n" +

2453 "\n" +

2454 "Notable keywords NOT supported include:\n" +

2455 "- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties\n" +

2456 "- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems\n" +

2457 "\n" +

2458 "Other notes:\n" +

2459 "- definitions and recursion are supported\n" +

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

2461 "\n" +

2462 "# Examples\n" +

2463 "Input: Generate a math reasoning schema with steps and a final answer.\n" +

2464 "Output: {\n" +

2465 " \"name\": \"math_reasoning\",\n" +

2466 " \"type\": \"object\",\n" +

2467 " \"properties\": {\n" +

2468 " \"steps\": {\n" +

2469 " \"type\": \"array\",\n" +

2470 " \"description\": \"A sequence of steps involved in solving the math problem.\",\n" +

2471 " \"items\": {\n" +

2472 " \"type\": \"object\",\n" +

2473 " \"properties\": {\n" +

2474 " \"explanation\": {\n" +

2475 " \"type\": \"string\",\n" +

2476 " \"description\": \"Description of the reasoning or method used in this step.\"\n" +

2477 " },\n" +

2478 " \"output\": {\n" +

2479 " \"type\": \"string\",\n" +

2480 " \"description\": \"Result or outcome of this specific step.\"\n" +

2481 " }\n" +

2482 " },\n" +

2483 " \"required\": [\n" +

2484 " \"explanation\",\n" +

2485 " \"output\"\n" +

2486 " ],\n" +

2487 " \"additionalProperties\": false\n" +

2488 " }\n" +

2489 " },\n" +

2490 " \"final_answer\": {\n" +

2491 " \"type\": \"string\",\n" +

2492 " \"description\": \"The final solution or answer to the math problem.\"\n" +

2493 " }\n" +

2494 " },\n" +

2495 " \"required\": [\n" +

2496 " \"steps\",\n" +

2497 " \"final_answer\"\n" +

2498 " ],\n" +

2499 " \"additionalProperties\": false\n" +

2500 "}\n" +

2501 "\n" +

2502 "Input: Give me a linked list\n" +

2503 "Output: {\n" +

2504 " \"name\": \"linked_list\",\n" +

2505 " \"type\": \"object\",\n" +

2506 " \"properties\": {\n" +

2507 " \"linked_list\": {\n" +

2508 " \"$ref\": \"#/$defs/linked_list_node\",\n" +

2509 " \"description\": \"The head node of the linked list.\"\n" +

2510 " }\n" +

2511 " },\n" +

2512 " \"$defs\": {\n" +

2513 " \"linked_list_node\": {\n" +

2514 " \"type\": \"object\",\n" +

2515 " \"description\": \"Defines a node in a singly linked list.\",\n" +

2516 " \"properties\": {\n" +

2517 " \"value\": {\n" +

2518 " \"type\": \"number\",\n" +

2519 " \"description\": \"The value stored in this node.\"\n" +

2520 " },\n" +

2521 " \"next\": {\n" +

2522 " \"anyOf\": [\n" +

2523 " {\n" +

2524 " \"$ref\": \"#/$defs/linked_list_node\"\n" +

2525 " },\n" +

2526 " {\n" +

2527 " \"type\": \"null\"\n" +

2528 " }\n" +

2529 " ],\n" +

2530 " \"description\": \"Reference to the next node; null if it is the last node.\"\n" +

2531 " }\n" +

2532 " },\n" +

2533 " \"required\": [\n" +

2534 " \"value\",\n" +

2535 " \"next\"\n" +

2536 " ],\n" +

2537 " \"additionalProperties\": false\n" +

2538 " }\n" +

2539 " },\n" +

2540 " \"required\": [\n" +

2541 " \"linked_list\"\n" +

2542 " ],\n" +

2543 " \"additionalProperties\": false\n" +

2544 "}\n" +

2545 "\n" +

2546 "Input: Dynamically generated UI\n" +

2547 "Output: {\n" +

2548 " \"name\": \"ui\",\n" +

2549 " \"type\": \"object\",\n" +

2550 " \"properties\": {\n" +

2551 " \"type\": {\n" +

2552 " \"type\": \"string\",\n" +

2553 " \"description\": \"The type of the UI component\",\n" +

2554 " \"enum\": [\n" +

2555 " \"div\",\n" +

2556 " \"button\",\n" +

2557 " \"header\",\n" +

2558 " \"section\",\n" +

2559 " \"field\",\n" +

2560 " \"form\"\n" +

2561 " ]\n" +

2562 " },\n" +

2563 " \"label\": {\n" +

2564 " \"type\": \"string\",\n" +

2565 " \"description\": \"The label of the UI component, used for buttons or form fields\"\n" +

2566 " },\n" +

2567 " \"children\": {\n" +

2568 " \"type\": \"array\",\n" +

2569 " \"description\": \"Nested UI components\",\n" +

2570 " \"items\": {\n" +

2571 " \"$ref\": \"#\"\n" +

2572 " }\n" +

2573 " },\n" +

2574 " \"attributes\": {\n" +

2575 " \"type\": \"array\",\n" +

2576 " \"description\": \"Arbitrary attributes for the UI component, suitable for any element\",\n" +

2577 " \"items\": {\n" +

2578 " \"type\": \"object\",\n" +

2579 " \"properties\": {\n" +

2580 " \"name\": {\n" +

2581 " \"type\": \"string\",\n" +

2582 " \"description\": \"The name of the attribute, for example onClick or className\"\n" +

2583 " },\n" +

2584 " \"value\": {\n" +

2585 " \"type\": \"string\",\n" +

2586 " \"description\": \"The value of the attribute\"\n" +

2587 " }\n" +

2588 " },\n" +

2589 " \"required\": [\n" +

2590 " \"name\",\n" +

2591 " \"value\"\n" +

2592 " ],\n" +

2593 " \"additionalProperties\": false\n" +

2594 " }\n" +

2595 " }\n" +

2596 " },\n" +

2597 " \"required\": [\n" +

2598 " \"type\",\n" +

2599 " \"label\",\n" +

2600 " \"children\",\n" +

2601 " \"attributes\"\n" +

2602 " ],\n" +

2603 " \"additionalProperties\": false\n" +

2604 "}\n"

2605 var schema map[string]any

2606 if err := json.Unmarshal([]byte(`{

2607 "type": "object",

2608 "properties": {

2609 "name": {

2610 "type": "string",

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

2612 },

2613 "type": {

2614 "type": "string",

2615 "enum": [

2616 "object",

2617 "array",

2618 "string",

2619 "number",

2620 "boolean",

2621 "null"

2622 ]

2623 },

2624 "properties": {

2625 "type": "object",

2626 "additionalProperties": {

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

2628 }

2629 },

2630 "items": {

2631 "anyOf": [

2632 {

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

2634 },

2635 {

2636 "type": "array",

2637 "items": {

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

2639 }

2640 }

2641 ]

2642 },

2643 "required": {

2644 "type": "array",

2645 "items": {

2646 "type": "string"

2647 }

2648 },

2649 "additionalProperties": {

2650 "type": "boolean"

2651 }

2652 },

2653 "required": [

2654 "type"

2655 ],

2656 "additionalProperties": false,

2657 "if": {

2658 "properties": {

2659 "type": {

2660 "const": "object"

2661 }

2662 }

2663 },

2664 "then": {

2665 "required": [

2666 "properties"

2667 ]

2668 },

2669 "$defs": {

2670 "schema_definition": {

2671 "type": "object",

2672 "properties": {

2673 "type": {

2674 "type": "string",

2675 "enum": [

2676 "object",

2677 "array",

2678 "string",

2679 "number",

2680 "boolean",

2681 "null"

2682 ]

2683 },

2684 "properties": {

2685 "type": "object",

2686 "additionalProperties": {

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

2688 }

2689 },

2690 "items": {

2691 "anyOf": [

2692 {

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

2694 },

2695 {

2696 "type": "array",

2697 "items": {

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

2699 }

2700 }

2701 ]

2702 },

2703 "required": {

2704 "type": "array",

2705 "items": {

2706 "type": "string"

2707 }

2708 },

2709 "additionalProperties": {

2710 "type": "boolean"

2711 }

2712 },

2713 "required": [

2714 "type"

2715 ],

2716 "additionalProperties": false,

2717 "if": {

2718 "properties": {

2719 "type": {

2720 "const": "object"

2721 }

2722 }

2723 },

2724 "then": {

2725 "required": [

2726 "properties"

2727 ]

2728 }

2729 }

2730 }

2731}`), &schema); err != nil {

2732 return err

2733 }

2734 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

2735 Model: "gpt-5.6-terra",

2736 Messages: []openai.ChatCompletionMessageParamUnion{

2737 openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),

2738 }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "metaschema", Schema: schema}}}})

2739 if err != nil {

2740 return err

2741 }

2742 var result any

2743 if err := json.Unmarshal([]byte(completion.Choices[0].Message.Content), &result); err != nil {

2744 return err

2745 }

2746 encoded, err := json.MarshalIndent(result, "", " ")

2747 if err != nil {

2748 return err

2749 }

2750 fmt.Println(string(encoded))

2751 return nil

2752}

2753```

2754 

2755```java

2756import com.openai.client.OpenAIClient;

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

2758import com.openai.core.JsonValue;

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

2760import java.util.List;

2761import java.util.Map;

2762 

2763String metaPrompt =

2764 """

2765 # Instructions

2766 Return a valid schema for the described JSON.

1875 2767 

1876 You must also make sure:2768 You must also make sure:

1877 - all fields in an object are set as required2769 - all fields in an object are set as required


2193 .forEach(System.out::println);3085 .forEach(System.out::println);

2194```3086```

2195 3087 

2196```ruby3088```csharp

2197require "openai"3089using System.Text.Json;

2198require "json"3090using OpenAI.Chat;

2199 3091 

2200META_SCHEMA = {3092string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

2201 "name" => "metaschema",3093string model = "gpt-5.6-terra";

2202 "schema" => {3094ChatClient client = new(model, key);

2203 "type" => "object",

2204 "properties" => {

2205 "name" => {

2206 "type" => "string",

2207 "description" => "The name of the schema"

2208 },

2209 "type" => {

2210 "type" => "string",

2211 "enum" => ["object", "array", "string", "number", "boolean", "null"]

2212 },

2213 "properties" => {

2214 "type" => "object",

2215 "additionalProperties" => {

2216 "$ref" => "#/$defs/schema_definition"

2217 }

2218 },

2219 "items" => {

2220 "anyOf" => [

2221 {

2222 "$ref" => "#/$defs/schema_definition"

2223 }, {

2224 "type" => "array",

2225 "items" => {

2226 "$ref" => "#/$defs/schema_definition"

2227 }

2228 }

2229 ]

2230 },

2231 "required" => {

2232 "type" => "array",

2233 "items" => {

2234 "type" => "string"

2235 }

2236 },

2237 "additionalProperties" => {

2238 "type" => "boolean"

2239 }

2240 },

2241 "required" => ["type"],

2242 "additionalProperties" => false,

2243 "if" => {

2244 "properties" => {

2245 "type" => {

2246 "const" => "object"

2247 }

2248 }

2249 },

2250 "then" => {

2251 "required" => ["properties"]

2252 },

2253 "$defs" => {

2254 "schema_definition" => {

2255 "type" => "object",

2256 "properties" => {

2257 "type" => {

2258 "type" => "string",

2259 "enum" => ["object", "array", "string", "number", "boolean", "null"]

2260 },

2261 "properties" => {

2262 "type" => "object",

2263 "additionalProperties" => {

2264 "$ref" => "#/$defs/schema_definition"

2265 }

2266 },

2267 "items" => {

2268 "anyOf" => [

2269 {

2270 "$ref" => "#/$defs/schema_definition"

2271 }, {

2272 "type" => "array",

2273 "items" => {

2274 "$ref" => "#/$defs/schema_definition"

2275 }

2276 }

2277 ]

2278 },

2279 "required" => {

2280 "type" => "array",

2281 "items" => {

2282 "type" => "string"

2283 }

2284 },

2285 "additionalProperties" => {

2286 "type" => "boolean"

2287 }

2288 },

2289 "required" => ["type"],

2290 "additionalProperties" => false,

2291 "if" => {

2292 "properties" => {

2293 "type" => {

2294 "const" => "object"

2295 }

2296 }

2297 },

2298 "then" => {

2299 "required" => ["properties"]

2300 }

2301 }

2302 }

2303 }

2304}

2305 3095 

2306META_PROMPT = <<~PROMPT.strip3096string metaPrompt = """"

2307 # Instructions3097 # Instructions

2308 Return a valid schema for the described JSON.3098 Return a valid schema for the described JSON.

2309 3099


2467 ],3257 ],

2468 "additionalProperties": false3258 "additionalProperties": false

2469 }3259 }

2470PROMPT3260 """";

2471 3261ChatCompletionOptions options = new();

2472client = OpenAI::Client.new3262options.ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat("metaschema", BinaryData.FromString("""

2473completion = client.chat.completions.create(

2474 model: "gpt-5.6-terra",

2475 response_format: {

2476 type: :json_schema,

2477 json_schema: META_SCHEMA

2478 },

2479 messages: [

2480 {3263 {

2481 role: :system,3264 "type": "object",

2482 content: META_PROMPT3265 "properties": {

3266 "name": {

3267 "type": "string",

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

2483 },3269 },

2484 {3270 "type": {

2485 role: :user,3271 "type": "string",

2486 content: "Description: Schedule a meeting with a title and start time."3272 "enum": [

2487 }3273 "object",

3274 "array",

3275 "string",

3276 "number",

3277 "boolean",

3278 "null"

2488 ]3279 ]

2489)3280 },

2490message = completion.choices.fetch(0).message3281 "properties": {

2491raise "Schema generation refused: #{message.refusal}" if message.refusal3282 "type": "object",

3283 "additionalProperties": {

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

3285 }

3286 },

3287 "items": {

3288 "anyOf": [

3289 {

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

3291 },

3292 {

3293 "type": "array",

3294 "items": {

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

3296 }

3297 }

3298 ]

3299 },

3300 "required": {

3301 "type": "array",

3302 "items": {

3303 "type": "string"

3304 }

3305 },

3306 "additionalProperties": {

3307 "type": "boolean"

3308 }

3309 },

3310 "required": [

3311 "type"

3312 ],

3313 "additionalProperties": false,

3314 "if": {

3315 "properties": {

3316 "type": {

3317 "const": "object"

3318 }

3319 }

3320 },

3321 "then": {

3322 "required": [

3323 "properties"

3324 ]

3325 },

3326 "$defs": {

3327 "schema_definition": {

3328 "type": "object",

3329 "properties": {

3330 "type": {

3331 "type": "string",

3332 "enum": [

3333 "object",

3334 "array",

3335 "string",

3336 "number",

3337 "boolean",

3338 "null"

3339 ]

3340 },

3341 "properties": {

3342 "type": "object",

3343 "additionalProperties": {

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

3345 }

3346 },

3347 "items": {

3348 "anyOf": [

3349 {

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

3351 },

3352 {

3353 "type": "array",

3354 "items": {

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

3356 }

3357 }

3358 ]

3359 },

3360 "required": {

3361 "type": "array",

3362 "items": {

3363 "type": "string"

3364 }

3365 },

3366 "additionalProperties": {

3367 "type": "boolean"

3368 }

3369 },

3370 "required": [

3371 "type"

3372 ],

3373 "additionalProperties": false,

3374 "if": {

3375 "properties": {

3376 "type": {

3377 "const": "object"

3378 }

3379 }

3380 },

3381 "then": {

3382 "required": [

3383 "properties"

3384 ]

3385 }

3386 }

3387 }

3388 }

3389 """));

3390ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Description: Schedule a meeting with a title and start time.")], options);

3391using JsonDocument parsed = JsonDocument.Parse(result.Content[0].Text);

3392Console.WriteLine(parsed.RootElement);

3393```

3394 

3395```ruby

3396require "openai"

3397require "json"

3398 

3399META_SCHEMA = {

3400 "name" => "metaschema",

3401 "schema" => {

3402 "type" => "object",

3403 "properties" => {

3404 "name" => {

3405 "type" => "string",

3406 "description" => "The name of the schema"

3407 },

3408 "type" => {

3409 "type" => "string",

3410 "enum" => ["object", "array", "string", "number", "boolean", "null"]

3411 },

3412 "properties" => {

3413 "type" => "object",

3414 "additionalProperties" => {

3415 "$ref" => "#/$defs/schema_definition"

3416 }

3417 },

3418 "items" => {

3419 "anyOf" => [

3420 {

3421 "$ref" => "#/$defs/schema_definition"

3422 }, {

3423 "type" => "array",

3424 "items" => {

3425 "$ref" => "#/$defs/schema_definition"

3426 }

3427 }

3428 ]

3429 },

3430 "required" => {

3431 "type" => "array",

3432 "items" => {

3433 "type" => "string"

3434 }

3435 },

3436 "additionalProperties" => {

3437 "type" => "boolean"

3438 }

3439 },

3440 "required" => ["type"],

3441 "additionalProperties" => false,

3442 "if" => {

3443 "properties" => {

3444 "type" => {

3445 "const" => "object"

3446 }

3447 }

3448 },

3449 "then" => {

3450 "required" => ["properties"]

3451 },

3452 "$defs" => {

3453 "schema_definition" => {

3454 "type" => "object",

3455 "properties" => {

3456 "type" => {

3457 "type" => "string",

3458 "enum" => ["object", "array", "string", "number", "boolean", "null"]

3459 },

3460 "properties" => {

3461 "type" => "object",

3462 "additionalProperties" => {

3463 "$ref" => "#/$defs/schema_definition"

3464 }

3465 },

3466 "items" => {

3467 "anyOf" => [

3468 {

3469 "$ref" => "#/$defs/schema_definition"

3470 }, {

3471 "type" => "array",

3472 "items" => {

3473 "$ref" => "#/$defs/schema_definition"

3474 }

3475 }

3476 ]

3477 },

3478 "required" => {

3479 "type" => "array",

3480 "items" => {

3481 "type" => "string"

3482 }

3483 },

3484 "additionalProperties" => {

3485 "type" => "boolean"

3486 }

3487 },

3488 "required" => ["type"],

3489 "additionalProperties" => false,

3490 "if" => {

3491 "properties" => {

3492 "type" => {

3493 "const" => "object"

3494 }

3495 }

3496 },

3497 "then" => {

3498 "required" => ["properties"]

3499 }

3500 }

3501 }

3502 }

3503}

3504 

3505META_PROMPT = <<~PROMPT.strip

3506 # Instructions

3507 Return a valid schema for the described JSON.

3508 

3509 You must also make sure:

3510 - all fields in an object are set as required

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

3512 - all objects must have additionalProperties set to false

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

3514 - all objects must have properties defined

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

3516 - $defs must be defined under the schema param

3517 

3518 Notable keywords NOT supported include:

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

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

3521 

3522 Other notes:

3523 - definitions and recursion are supported

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

3525 

3526 # Examples

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

3528 Output: {

3529 "name": "math_reasoning",

3530 "type": "object",

3531 "properties": {

3532 "steps": {

3533 "type": "array",

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

3535 "items": {

3536 "type": "object",

3537 "properties": {

3538 "explanation": {

3539 "type": "string",

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

3541 },

3542 "output": {

3543 "type": "string",

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

3545 }

3546 },

3547 "required": [

3548 "explanation",

3549 "output"

3550 ],

3551 "additionalProperties": false

3552 }

3553 },

3554 "final_answer": {

3555 "type": "string",

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

3557 }

3558 },

3559 "required": [

3560 "steps",

3561 "final_answer"

3562 ],

3563 "additionalProperties": false

3564 }

3565 

3566 Input: Give me a linked list

3567 Output: {

3568 "name": "linked_list",

3569 "type": "object",

3570 "properties": {

3571 "linked_list": {

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

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

3574 }

3575 },

3576 "$defs": {

3577 "linked_list_node": {

3578 "type": "object",

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

3580 "properties": {

3581 "value": {

3582 "type": "number",

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

3584 },

3585 "next": {

3586 "anyOf": [

3587 {

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

3589 },

3590 {

3591 "type": "null"

3592 }

3593 ],

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

3595 }

3596 },

3597 "required": [

3598 "value",

3599 "next"

3600 ],

3601 "additionalProperties": false

3602 }

3603 },

3604 "required": [

3605 "linked_list"

3606 ],

3607 "additionalProperties": false

3608 }

3609 

3610 Input: Dynamically generated UI

3611 Output: {

3612 "name": "ui",

3613 "type": "object",

3614 "properties": {

3615 "type": {

3616 "type": "string",

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

3618 "enum": [

3619 "div",

3620 "button",

3621 "header",

3622 "section",

3623 "field",

3624 "form"

3625 ]

3626 },

3627 "label": {

3628 "type": "string",

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

3630 },

3631 "children": {

3632 "type": "array",

3633 "description": "Nested UI components",

3634 "items": {

3635 "$ref": "#"

3636 }

3637 },

3638 "attributes": {

3639 "type": "array",

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

3641 "items": {

3642 "type": "object",

3643 "properties": {

3644 "name": {

3645 "type": "string",

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

3647 },

3648 "value": {

3649 "type": "string",

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

3651 }

3652 },

3653 "required": [

3654 "name",

3655 "value"

3656 ],

3657 "additionalProperties": false

3658 }

3659 }

3660 },

3661 "required": [

3662 "type",

3663 "label",

3664 "children",

3665 "attributes"

3666 ],

3667 "additionalProperties": false

3668 }

3669PROMPT

3670 

3671client = OpenAI::Client.new

3672completion = client.chat.completions.create(

3673 model: "gpt-5.6-terra",

3674 response_format: {

3675 type: :json_schema,

3676 json_schema: META_SCHEMA

3677 },

3678 messages: [

3679 {

3680 role: :system,

3681 content: META_PROMPT

3682 },

3683 {

3684 role: :user,

3685 content: "Description: Schedule a meeting with a title and start time."

3686 }

3687 ]

3688)

3689message = completion.choices.fetch(0).message

3690raise "Schema generation refused: #{message.refusal}" if message.refusal

2492 3691 

2493puts(JSON.pretty_generate(JSON.parse(message.content || raise("No schema returned"))))3692puts(JSON.pretty_generate(JSON.parse(message.content || raise("No schema returned"))))

2494```3693```


2802Pay 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.4001Pay 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.

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

2804 4003 

2805# Examples4004# Examples

2806Input: Assign values to NN hyperparameters4005Input: Assign values to NN hyperparameters

2807Output: {4006Output: {

4007 "name": "set_hyperparameters",

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

4009 "parameters": {

4010 "type": "object",

4011 "required": [

4012 "learning_rate",

4013 "epochs"

4014 ],

4015 "properties": {

4016 "epochs": {

4017 "type": "number",

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

4019 },

4020 "learning_rate": {

4021 "type": "number",

4022 "description": "Speed of model learning"

4023 }

4024 }

4025 }

4026}

4027 

4028Input: Plans a motion path for the robot

4029Output: {

4030 "name": "plan_motion",

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

4032 "parameters": {

4033 "type": "object",

4034 "required": [

4035 "start_position",

4036 "end_position"

4037 ],

4038 "properties": {

4039 "end_position": {

4040 "type": "object",

4041 "properties": {

4042 "x": {

4043 "type": "number",

4044 "description": "End X coordinate"

4045 },

4046 "y": {

4047 "type": "number",

4048 "description": "End Y coordinate"

4049 }

4050 }

4051 },

4052 "obstacles": {

4053 "type": "array",

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

4055 "items": {

4056 "type": "object",

4057 "properties": {

4058 "x": {

4059 "type": "number",

4060 "description": "Obstacle X coordinate"

4061 },

4062 "y": {

4063 "type": "number",

4064 "description": "Obstacle Y coordinate"

4065 }

4066 }

4067 }

4068 },

4069 "start_position": {

4070 "type": "object",

4071 "properties": {

4072 "x": {

4073 "type": "number",

4074 "description": "Start X coordinate"

4075 },

4076 "y": {

4077 "type": "number",

4078 "description": "Start Y coordinate"

4079 }

4080 }

4081 }

4082 }

4083 }

4084}

4085 

4086Input: Calculates various technical indicators

4087Output: {

4088 "name": "technical_indicator",

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

4090 "parameters": {

4091 "type": "object",

4092 "required": [

4093 "ticker",

4094 "indicators"

4095 ],

4096 "properties": {

4097 "indicators": {

4098 "type": "array",

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

4100 "items": {

4101 "type": "string",

4102 "description": "Technical indicator",

4103 "enum": [

4104 "RSI",

4105 "MACD",

4106 "Bollinger_Bands",

4107 "Stochastic_Oscillator"

4108 ]

4109 }

4110 },

4111 "period": {

4112 "type": "number",

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

4114 },

4115 "ticker": {

4116 "type": "string",

4117 "description": "Stock ticker symbol"

4118 }

4119 }

4120 }

4121}

4122""".strip()

4123 

4124 

4125def generate_function_schema(description: str):

4126 completion = client.chat.completions.create(

4127 model="gpt-5.6-terra",

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

4129 messages=[

4130 {

4131 "role": "system",

4132 "content": META_PROMPT,

4133 },

4134 {

4135 "role": "user",

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

4137 },

4138 ],

4139 )

4140 

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

4142```

4143 

4144```go

4145import (

4146 "context"

4147 "encoding/json"

4148 "fmt"

4149 "log"

4150 

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

4152 "github.com/openai/openai-go/v3/shared"

4153)

4154 

4155func main() {

4156 if err := run(); err != nil {

4157 log.Fatal(err)

4158 }

4159}

4160 

4161func run() error {

4162 client := openai.NewClient()

4163 metaPrompt := "# Instructions\n" +

4164 "Return a valid schema for the described function.\n" +

4165 "\n" +

4166 "Pay special attention to making sure that \"required\" and \"type\" are always at the correct level of nesting. For example, \"required\" should be at the same level as \"properties\", not inside it.\n" +

4167 "Make sure that every property, no matter how short, has a type and description correctly nested inside it.\n" +

4168 "\n" +

4169 "# Examples\n" +

4170 "Input: Assign values to NN hyperparameters\n" +

4171 "Output: {\n" +

4172 " \"name\": \"set_hyperparameters\",\n" +

4173 " \"description\": \"Assign values to NN hyperparameters\",\n" +

4174 " \"parameters\": {\n" +

4175 " \"type\": \"object\",\n" +

4176 " \"required\": [\n" +

4177 " \"learning_rate\",\n" +

4178 " \"epochs\"\n" +

4179 " ],\n" +

4180 " \"properties\": {\n" +

4181 " \"epochs\": {\n" +

4182 " \"type\": \"number\",\n" +

4183 " \"description\": \"Number of complete passes through dataset\"\n" +

4184 " },\n" +

4185 " \"learning_rate\": {\n" +

4186 " \"type\": \"number\",\n" +

4187 " \"description\": \"Speed of model learning\"\n" +

4188 " }\n" +

4189 " }\n" +

4190 " }\n" +

4191 "}\n" +

4192 "\n" +

4193 "Input: Plans a motion path for the robot\n" +

4194 "Output: {\n" +

4195 " \"name\": \"plan_motion\",\n" +

4196 " \"description\": \"Plans a motion path for the robot\",\n" +

4197 " \"parameters\": {\n" +

4198 " \"type\": \"object\",\n" +

4199 " \"required\": [\n" +

4200 " \"start_position\",\n" +

4201 " \"end_position\"\n" +

4202 " ],\n" +

4203 " \"properties\": {\n" +

4204 " \"end_position\": {\n" +

4205 " \"type\": \"object\",\n" +

4206 " \"properties\": {\n" +

4207 " \"x\": {\n" +

4208 " \"type\": \"number\",\n" +

4209 " \"description\": \"End X coordinate\"\n" +

4210 " },\n" +

4211 " \"y\": {\n" +

4212 " \"type\": \"number\",\n" +

4213 " \"description\": \"End Y coordinate\"\n" +

4214 " }\n" +

4215 " }\n" +

4216 " },\n" +

4217 " \"obstacles\": {\n" +

4218 " \"type\": \"array\",\n" +

4219 " \"description\": \"Array of obstacle coordinates\",\n" +

4220 " \"items\": {\n" +

4221 " \"type\": \"object\",\n" +

4222 " \"properties\": {\n" +

4223 " \"x\": {\n" +

4224 " \"type\": \"number\",\n" +

4225 " \"description\": \"Obstacle X coordinate\"\n" +

4226 " },\n" +

4227 " \"y\": {\n" +

4228 " \"type\": \"number\",\n" +

4229 " \"description\": \"Obstacle Y coordinate\"\n" +

4230 " }\n" +

4231 " }\n" +

4232 " }\n" +

4233 " },\n" +

4234 " \"start_position\": {\n" +

4235 " \"type\": \"object\",\n" +

4236 " \"properties\": {\n" +

4237 " \"x\": {\n" +

4238 " \"type\": \"number\",\n" +

4239 " \"description\": \"Start X coordinate\"\n" +

4240 " },\n" +

4241 " \"y\": {\n" +

4242 " \"type\": \"number\",\n" +

4243 " \"description\": \"Start Y coordinate\"\n" +

4244 " }\n" +

4245 " }\n" +

4246 " }\n" +

4247 " }\n" +

4248 " }\n" +

4249 "}\n" +

4250 "\n" +

4251 "Input: Calculates various technical indicators\n" +

4252 "Output: {\n" +

4253 " \"name\": \"technical_indicator\",\n" +

4254 " \"description\": \"Calculates various technical indicators\",\n" +

4255 " \"parameters\": {\n" +

4256 " \"type\": \"object\",\n" +

4257 " \"required\": [\n" +

4258 " \"ticker\",\n" +

4259 " \"indicators\"\n" +

4260 " ],\n" +

4261 " \"properties\": {\n" +

4262 " \"indicators\": {\n" +

4263 " \"type\": \"array\",\n" +

4264 " \"description\": \"List of technical indicators to calculate\",\n" +

4265 " \"items\": {\n" +

4266 " \"type\": \"string\",\n" +

4267 " \"description\": \"Technical indicator\",\n" +

4268 " \"enum\": [\n" +

4269 " \"RSI\",\n" +

4270 " \"MACD\",\n" +

4271 " \"Bollinger_Bands\",\n" +

4272 " \"Stochastic_Oscillator\"\n" +

4273 " ]\n" +

4274 " }\n" +

4275 " },\n" +

4276 " \"period\": {\n" +

4277 " \"type\": \"number\",\n" +

4278 " \"description\": \"Time period for the analysis\"\n" +

4279 " },\n" +

4280 " \"ticker\": {\n" +

4281 " \"type\": \"string\",\n" +

4282 " \"description\": \"Stock ticker symbol\"\n" +

4283 " }\n" +

4284 " }\n" +

4285 " }\n" +

4286 "}\n"

4287 var schema map[string]any

4288 if err := json.Unmarshal([]byte(`{

4289 "type": "object",

4290 "properties": {

4291 "name": {

4292 "type": "string",

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

4294 },

4295 "description": {

4296 "type": "string",

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

4298 },

4299 "parameters": {

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

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

4302 }

4303 },

4304 "required": [

4305 "name",

4306 "description",

4307 "parameters"

4308 ],

4309 "additionalProperties": false,

4310 "$defs": {

4311 "schema_definition": {

4312 "type": "object",

4313 "properties": {

4314 "type": {

4315 "type": "string",

4316 "enum": [

4317 "object",

4318 "array",

4319 "string",

4320 "number",

4321 "boolean",

4322 "null"

4323 ]

4324 },

4325 "properties": {

4326 "type": "object",

4327 "additionalProperties": {

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

4329 }

4330 },

4331 "items": {

4332 "anyOf": [

4333 {

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

4335 },

4336 {

4337 "type": "array",

4338 "items": {

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

4340 }

4341 }

4342 ]

4343 },

4344 "required": {

4345 "type": "array",

4346 "items": {

4347 "type": "string"

4348 }

4349 },

4350 "additionalProperties": {

4351 "type": "boolean"

4352 }

4353 },

4354 "required": [

4355 "type"

4356 ],

4357 "additionalProperties": false,

4358 "if": {

4359 "properties": {

4360 "type": {

4361 "const": "object"

4362 }

4363 }

4364 },

4365 "then": {

4366 "required": [

4367 "properties"

4368 ]

4369 }

4370 }

4371 }

4372}`), &schema); err != nil {

4373 return err

4374 }

4375 completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{

4376 Model: "gpt-5.6-terra",

4377 Messages: []openai.ChatCompletionMessageParamUnion{

4378 openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),

4379 }, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "function-metaschema", Schema: schema}}}})

4380 if err != nil {

4381 return err

4382 }

4383 var result any

4384 if err := json.Unmarshal([]byte(completion.Choices[0].Message.Content), &result); err != nil {

4385 return err

4386 }

4387 encoded, err := json.MarshalIndent(result, "", " ")

4388 if err != nil {

4389 return err

4390 }

4391 fmt.Println(string(encoded))

4392 return nil

4393}

4394```

4395 

4396```java

4397import com.openai.client.OpenAIClient;

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

4399import com.openai.core.JsonValue;

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

4401import java.util.List;

4402import java.util.Map;

4403 

4404String metaPrompt =

4405 """

4406 # Instructions

4407 Return a valid schema for the described function.

4408 

4409 Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.

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

4411 

4412 # Examples

4413 Input: Assign values to NN hyperparameters

4414 Output: {

2808 "name": "set_hyperparameters",4415 "name": "set_hyperparameters",

2809 "description": "Assign values to NN hyperparameters",4416 "description": "Assign values to NN hyperparameters",

2810 "parameters": {4417 "parameters": {


2824 }4431 }

2825 }4432 }

2826 }4433 }

2827}4434 }

2828 4435 

2829Input: Plans a motion path for the robot4436 Input: Plans a motion path for the robot

2830Output: {4437 Output: {

2831 "name": "plan_motion",4438 "name": "plan_motion",

2832 "description": "Plans a motion path for the robot",4439 "description": "Plans a motion path for the robot",

2833 "parameters": {4440 "parameters": {


2882 }4489 }

2883 }4490 }

2884 }4491 }

2885}4492 }

2886 4493 

2887Input: Calculates various technical indicators4494 Input: Calculates various technical indicators

2888Output: {4495 Output: {

2889 "name": "technical_indicator",4496 "name": "technical_indicator",

2890 "description": "Calculates various technical indicators",4497 "description": "Calculates various technical indicators",

2891 "parameters": {4498 "parameters": {


2919 }4526 }

2920 }4527 }

2921 }4528 }

2922}4529 }

2923""".strip()4530 """

2924 4531 .strip();

4532Map<String, Object> schemaDefinition =

4533 Map.of(

4534 "type", "object",

4535 "properties",

4536 Map.of(

4537 "type",

4538 Map.of(

4539 "type",

4540 "string",

4541 "enum",

4542 List.of("object", "array", "string", "number", "boolean", "null")),

4543 "properties",

4544 Map.of(

4545 "type",

4546 "object",

4547 "additionalProperties",

4548 Map.of("$ref", "#/$defs/schema_definition")),

4549 "items",

4550 Map.of(

4551 "anyOf",

4552 List.of(

4553 Map.of("$ref", "#/$defs/schema_definition"),

4554 Map.of(

4555 "type",

4556 "array",

4557 "items",

4558 Map.of("$ref", "#/$defs/schema_definition")))),

4559 "required", Map.of("type", "array", "items", Map.of("type", "string")),

4560 "additionalProperties", Map.of("type", "boolean")),

4561 "required", List.of("type"),

4562 "additionalProperties", false,

4563 "if", Map.of("properties", Map.of("type", Map.of("const", "object"))),

4564 "then", Map.of("required", List.of("properties")));

4565Map<String, Object> functionSchema =

4566 Map.of(

4567 "type", "object",

4568 "properties",

4569 Map.of(

4570 "name", Map.of("type", "string", "description", "The name of the function"),

4571 "description",

4572 Map.of(

4573 "type",

4574 "string",

4575 "description",

4576 "A description of what the function does"),

4577 "parameters",

4578 Map.of(

4579 "$ref",

4580 "#/$defs/schema_definition",

4581 "description",

4582 "A JSON schema that defines the function's parameters")),

4583 "required", List.of("name", "description", "parameters"),

4584 "additionalProperties", false,

4585 "$defs", Map.of("schema_definition", schemaDefinition));

2925 4586 

2926def generate_function_schema(description: str):4587ChatCompletionCreateParams params =

2927 completion = client.chat.completions.create(4588 ChatCompletionCreateParams.builder()

2928 model="gpt-5.6-terra",4589 .model("gpt-5.6-terra")

2929 response_format={"type": "json_schema", "json_schema": META_SCHEMA},4590 .addSystemMessage(metaPrompt)

2930 messages=[4591 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")

2931 {4592 .putAdditionalBodyProperty(

2932 "role": "system",4593 "response_format",

2933 "content": META_PROMPT,4594 JsonValue.from(

2934 },4595 Map.of(

2935 {4596 "type",

2936 "role": "user",4597 "json_schema",

2937 "content": "Description:\n" + description,4598 "json_schema",

2938 },4599 Map.of("name", "function-metaschema", "schema", functionSchema))))

2939 ],4600 .build();

2940 )

2941 4601 

2942 return json.loads(completion.choices[0].message.content)4602client.chat().completions().create(params).choices().stream()

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

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

2943```4605```

2944 4606 

2945```java4607```csharp

2946import com.openai.client.OpenAIClient;4608using System.Text.Json;

2947import com.openai.client.okhttp.OpenAIOkHttpClient;4609using OpenAI.Chat;

2948import com.openai.core.JsonValue;

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

2950import java.util.List;

2951import java.util.Map;

2952 4610 

2953String metaPrompt =4611string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

2954 """4612string model = "gpt-5.6-terra";

4613ChatClient client = new(model, key);

4614 

4615string metaPrompt = """"

2955 # Instructions4616 # Instructions

2956 Return a valid schema for the described function.4617 Return a valid schema for the described function.

2957 4618


3076 }4737 }

3077 }4738 }

3078 }4739 }

3079 """4740 """";

3080 .strip();4741ChatCompletionOptions options = new();

3081Map<String, Object> schemaDefinition =4742options.ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat("function-metaschema", BinaryData.FromString("""

3082 Map.of(4743 {

3083 "type", "object",4744 "type": "object",

3084 "properties",4745 "properties": {

3085 Map.of(4746 "name": {

3086 "type",4747 "type": "string",

3087 Map.of(4748 "description": "The name of the function"

3088 "type",4749 },

3089 "string",4750 "description": {

3090 "enum",4751 "type": "string",

3091 List.of("object", "array", "string", "number", "boolean", "null")),4752 "description": "A description of what the function does"

3092 "properties",4753 },

3093 Map.of(4754 "parameters": {

3094 "type",4755 "$ref": "#/$defs/schema_definition",

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

4757 }

4758 },

4759 "required": [

4760 "name",

4761 "description",

4762 "parameters"

4763 ],

4764 "additionalProperties": false,

4765 "$defs": {

4766 "schema_definition": {

4767 "type": "object",

4768 "properties": {

4769 "type": {

4770 "type": "string",

4771 "enum": [

3095 "object",4772 "object",

3096 "additionalProperties",

3097 Map.of("$ref", "#/$defs/schema_definition")),

3098 "items",

3099 Map.of(

3100 "anyOf",

3101 List.of(

3102 Map.of("$ref", "#/$defs/schema_definition"),

3103 Map.of(

3104 "type",

3105 "array",4773 "array",

3106 "items",

3107 Map.of("$ref", "#/$defs/schema_definition")))),

3108 "required", Map.of("type", "array", "items", Map.of("type", "string")),

3109 "additionalProperties", Map.of("type", "boolean")),

3110 "required", List.of("type"),

3111 "additionalProperties", false,

3112 "if", Map.of("properties", Map.of("type", Map.of("const", "object"))),

3113 "then", Map.of("required", List.of("properties")));

3114Map<String, Object> functionSchema =

3115 Map.of(

3116 "type", "object",

3117 "properties",

3118 Map.of(

3119 "name", Map.of("type", "string", "description", "The name of the function"),

3120 "description",

3121 Map.of(

3122 "type",

3123 "string",4774 "string",

3124 "description",4775 "number",

3125 "A description of what the function does"),4776 "boolean",

3126 "parameters",4777 "null"

3127 Map.of(4778 ]

3128 "$ref",4779 },

3129 "#/$defs/schema_definition",4780 "properties": {

3130 "description",4781 "type": "object",

3131 "A JSON schema that defines the function's parameters")),4782 "additionalProperties": {

3132 "required", List.of("name", "description", "parameters"),4783 "$ref": "#/$defs/schema_definition"

3133 "additionalProperties", false,4784 }

3134 "$defs", Map.of("schema_definition", schemaDefinition));4785 },

3135 4786 "items": {

3136ChatCompletionCreateParams params =4787 "anyOf": [

3137 ChatCompletionCreateParams.builder()4788 {

3138 .model("gpt-5.6-terra")4789 "$ref": "#/$defs/schema_definition"

3139 .addSystemMessage(metaPrompt)4790 },

3140 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")4791 {

3141 .putAdditionalBodyProperty(4792 "type": "array",

3142 "response_format",4793 "items": {

3143 JsonValue.from(4794 "$ref": "#/$defs/schema_definition"

3144 Map.of(4795 }

3145 "type",4796 }

3146 "json_schema",4797 ]

3147 "json_schema",4798 },

3148 Map.of("name", "function-metaschema", "schema", functionSchema))))4799 "required": {

3149 .build();4800 "type": "array",

3150 4801 "items": {

3151client.chat().completions().create(params).choices().stream()4802 "type": "string"

3152 .flatMap(choice -> choice.message().content().stream())4803 }

3153 .forEach(System.out::println);4804 },

4805 "additionalProperties": {

4806 "type": "boolean"

4807 }

4808 },

4809 "required": [

4810 "type"

4811 ],

4812 "additionalProperties": false,

4813 "if": {

4814 "properties": {

4815 "type": {

4816 "const": "object"

4817 }

4818 }

4819 },

4820 "then": {

4821 "required": [

4822 "properties"

4823 ]

4824 }

4825 }

4826 }

4827 }

4828 """));

4829ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Description: Schedule a meeting with a title and start time.")], options);

4830using JsonDocument parsed = JsonDocument.Parse(result.Content[0].Text);

4831Console.WriteLine(parsed.RootElement);

3154```4832```

3155 4833 

3156```ruby4834```ruby

Details

2263}2263}

2264```2264```

2265 2265 

2266```java

2267import com.openai.models.vectorstores.VectorStoreSearchResponse;

2268import java.util.List;

2269 

2270System.out.println(formatResults(results.data()));

2271 

2272static String formatResults(List<VectorStoreSearchResponse> results) {

2273 var formatted = new StringBuilder("<sources>");

2274 for (var result : results) {

2275 formatted

2276 .append("<result file_id='")

2277 .append(result.fileId())

2278 .append("' file_name='")

2279 .append(result.filename())

2280 .append("'>");

2281 for (var part : result.content()) {

2282 formatted.append("<content>").append(part.text()).append("</content>");

2283 }

2284 formatted.append("</result>");

2285 }

2286 return formatted.append("</sources>").toString();

2287}

2288```

2289 

2266```ruby2290```ruby

2267results = [2291results = [

2268 {2292 {

Details

19 19 

20## Implementing safety identifiers for individual users20## Implementing safety identifiers for individual users

21 21 

22To route warning and deactivation notices for a safety identifier to your investigation or support workflow, see [Safety enforcement notifications](https://developers.openai.com/api/docs/guides/safety-enforcement).

23 

22The `safety_identifier` parameter is available in both the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) and older [Chat Completions API](https://developers.openai.com/api/reference/resources/chat). The Realtime API supports the same concept through the `OpenAI-Safety-Identifier` header. To use safety identifiers, provide a stable ID for your end user on each request. Hash user email or internal user IDs to avoid passing any personal information.24The `safety_identifier` parameter is available in both the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create) and older [Chat Completions API](https://developers.openai.com/api/reference/resources/chat). The Realtime API supports the same concept through the `OpenAI-Safety-Identifier` header. To use safety identifiers, provide a stable ID for your end user on each request. Hash user email or internal user IDs to avoid passing any personal information.

23 25 

24Safety identifiers do not carry over between APIs or sessions. If your application already sends `safety_identifier` with Responses API requests, pass the same stable value separately when you create or connect each Realtime session.26Safety identifiers do not carry over between APIs or sessions. If your application already sends `safety_identifier` with Responses API requests, pass the same stable value separately when you create or connect each Realtime session.

guides/safety-enforcement.md +124 −0 created

Details

1# Safety enforcement notifications

2 

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

4 

5Use safety webhooks and the Safety Case Read API to connect OpenAI enforcement notices to your team's workflows. For example, when a warning arrives, your application can retrieve its case details, identify the affected user, and create an internal review ticket.

6 

7## When to use this

8 

9Use this integration to:

10 

11- Route warning and deactivation notices to your trust and safety, security, or support team.

12- Add case details to an investigation or support ticket.

13- Associate a notice with a user through your application's safety-identifier mapping.

14 

15The steps in this guide use a warning to illustrate the workflow. You can use the same integration for deactivation notices.

16 

17## How it works

18 

19Safety webhooks notify your application that a notice was issued. The Safety Case Read API provides the details for that notice.

20 

21| Event | Notice |

22| ---------------------------- | ------------------------------------------------------------ |

23| `safety.warning_issued` | A warning for a safety identifier in your organization. |

24| `safety.deactivation_issued` | A deactivation for a safety identifier in your organization. |

25 

26Each event contains a case ID. Use it with `GET /v1/safety/cases/{id}` to retrieve the safety identifier, notice type, case creation timestamp, and available policy reason.

27 

28These organization-level notifications are separate from project-level [misalignment alerts](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring#receive-project-safety-alerts). Retrieving a case does not change or reverse the enforcement. The API returns case metadata, not the underlying conversation or a full investigation report.

29 

30## Integrate with your application

31 

32Start by configuring an organization-level webhook and a key for case lookups. Then connect the notifications to your review workflow.

33 

34### 1. Configure your webhook and API key

35 

36Use a stable [safety identifier](https://developers.openai.com/api/docs/guides/safety-best-practices#implement-safety-identifiers) for each user, and keep your application's mapping from that identifier to the user. Avoid including personal information in the identifier.

37 

38Open your [organization webhook settings](https://platform.openai.com/settings/organization/webhooks) and select **Create**. Enter your receiver's HTTPS URL and subscribe to `safety.warning_issued` and `safety.deactivation_issued`. Save the signing secret securely so your receiver can verify incoming events. These events use an organization endpoint, not a project endpoint.

39 

40Your account needs `api.webhooks.read` and `organization.read` to view organization webhooks, plus `api.webhooks.write` and `organization.write` to create them. See [Permissions](https://developers.openai.com/api/docs/guides/rbac) for role configuration.

41 

42For case lookups, configure an API key for the same organization with **Restricted** permissions and set **Safety** to **Read** (`api.safety.read`). The API key authenticates case lookups; it is separate from the webhook signing secret.

43 

44### 2. Receive and verify the event

45 

46A warning notification has this structure. The IDs are illustrative:

47 

48```json

49{

50 "id": "evt_example",

51 "object": "event",

52 "created_at": 1787659200,

53 "type": "safety.warning_issued",

54 "data": {

55 "id": "C-example"

56 }

57}

58```

59 

60Verify the signature before processing the event. Save the verified event for processing, return a successful `2xx` response promptly, and retrieve the case in a background worker. See the Webhooks guide for [signature verification](https://developers.openai.com/api/docs/guides/webhooks#verifying-webhook-signatures) and [acknowledgments, retries, and duplicate deliveries](https://developers.openai.com/api/docs/guides/webhooks#handling-webhook-requests-on-a-server).

61 

62The event's `id` identifies the webhook event. Its `data.id` identifies the safety case to retrieve.

63 

64### 3. Retrieve the case

65 

66Set `OPENAI_API_KEY` to your API key. Replace `C-example` with `data.id` from the verified event:

67 

68```bash

69curl "https://api.openai.com/v1/safety/cases/C-example" \

70 -H "Authorization: Bearer ${OPENAI_API_KEY}"

71```

72 

73A successful lookup returns HTTP `200` and a case object. For example:

74 

75```json

76{

77 "id": "C-example",

78 "object": "safety.case",

79 "created_at": 1787659100,

80 "entity_identifier": "safety-id-example",

81 "reason": "cyber_abuse",

82 "notice": {

83 "type": "warning"

84 }

85}

86```

87 

88Use `entity_identifier` to find the affected user in your application. The `reason` can be `null`; continue processing the notice when no reason is available.

89 

90The case creation timestamp is not necessarily the event timestamp or the time of an individual request. See the [Safety Case API reference](https://developers.openai.com/api/reference/resources/safety/subresources/cases/methods/retrieve) for field definitions.

91 

92### 4. Create a review ticket

93 

94Add the case ID, notice type, safety identifier, case creation timestamp, and available policy reason to your internal ticket. Link the matching user record so your team can investigate using its own application records. If you cannot find a matching user, preserve the case details and flag the missing mapping for review.

95 

96Make ticket creation safe to retry. Follow the [webhook deduplication guidance](https://developers.openai.com/api/docs/guides/webhooks#handling-webhook-requests-on-a-server) so repeated deliveries do not create duplicate tickets. Retries of your own background processing should also reuse the existing ticket.

97 

98If an agent helps with triage, limit its access to the records it needs and keep customer-facing actions subject to your existing approval controls.

99 

100## Confirm it's working

101 

102For a real event and an accessible case in your organization, check that:

103 

1041. Your receiver verifies the signature and returns a successful acknowledgment.

1052. The lookup returns HTTP `200`, with a case `id` matching the event's `data.id`.

1063. Your application identifies the expected user or flags a missing mapping.

1074. One review ticket contains the available case details. Reprocessing the event does not create another ticket.

108 

109Before receiving a real notice, test your processing logic with local example events and mocked case responses. Include both notice types, a `null` reason, a missing user mapping, and duplicate deliveries. Test signature verification separately, including rejection of invalid signatures; keep it enabled on your production receiver.

110 

111The example IDs on this page are not retrievable cases. Mocked tests validate your processing logic, not live delivery or API permissions. Do not trigger an actual enforcement to test your integration. An absence of enforcement notifications alone does not indicate a broken integration.

112 

113## Troubleshoot

114 

115| Symptom | What to check |

116| ----------------------------------------- | -------------------------------------------------------------------------------------------------------- |

117| Signature verification fails | Check the signing secret and preserve the raw request body as described in the Webhooks guide. |

118| Lookup returns `401` | Check that the API key is present and valid. |

119| Lookup returns `403` | Check that the key has the `api.safety.read` permission. |

120| Lookup returns `404` | Use `data.id`, not the event ID. Check that the case belongs to the key's organization. |

121| Lookup returns `429` or a transient `5xx` | Retry with backoff and a bounded retry policy. Preserve the event for later processing or investigation. |

122| A ticket is created more than once | Check that ticket creation remains safe across repeated deliveries and worker retries. |

123 

124Do not silently discard a verified notification when its case lookup fails. Keep it available for retry or investigation.

Details

121 file: audio,121 file: audio,

122 model: "gpt-transcribe"122 model: "gpt-transcribe"

123)123)

124raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

125 

124puts(transcript.text)126puts(transcript.text)

125```127```

126 128 


273 model: "gpt-transcribe",275 model: "gpt-transcribe",

274 keywords: ["OpenAI", "Responses API", "Codex"]276 keywords: ["OpenAI", "Responses API", "Codex"]

275)277)

278raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

279 

276puts(transcript.text)280puts(transcript.text)

277```281```

278 282 


626client = OpenAI::Client.new630client = OpenAI::Client.new

627audio = Pathname("german.wav")631audio = Pathname("german.wav")

628translation = client.audio.translations.create(file: audio, model: "whisper-1")632translation = client.audio.translations.create(file: audio, model: "whisper-1")

633raise "Expected a JSON translation response" if translation.is_a?(StringIO)

634 

629puts(translation.text)635puts(translation.text)

630```636```

631 637 


796 response_format: :verbose_json,802 response_format: :verbose_json,

797 timestamp_granularities: [:word]803 timestamp_granularities: [:word]

798)804)

805raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

806 

799pp(transcript[:words])807pp(transcript[:words])

800```808```

801 809 


936}944}

937```945```

938 946 

947```java

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

949import com.openai.models.audio.transcriptions.TranscriptionCreateParams;

950import java.nio.file.Path;

951 

952var params =

953 TranscriptionCreateParams.builder()

954 .model("gpt-transcribe")

955 .file(Path.of("speech.wav"))

956 .build();

957try (var stream = client.audio().transcriptions().createStreaming(params)) {

958 stream.stream().forEach(event -> System.out.println(event));

959}

960```

961 

962```csharp

963using OpenAI.Audio;

964#pragma warning disable OPENAI001

965 

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

967string model = "gpt-transcribe";

968AudioClient client = new(model, key);

969 

970await foreach (StreamingAudioTranscriptionUpdate update in client.TranscribeAudioStreamingAsync("speech.wav"))

971{

972 if (update is StreamingAudioTranscriptionTextDeltaUpdate delta)

973 {

974 Console.Write(delta.Delta);

975 }

976}

977Console.WriteLine();

978```

979 

939```ruby980```ruby

940require "openai"981require "openai"

941require "pathname"982require "pathname"


1126 model: "whisper-1",1167 model: "whisper-1",

1127 prompt: "The speaker says OpenAI and Responses API"1168 prompt: "The speaker says OpenAI and Responses API"

1128)1169)

1170raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

1171 

1129puts(transcript.text)1172puts(transcript.text)

1130```1173```

1131 1174 


1359 model: "gpt-4o-mini-transcribe"1402 model: "gpt-4o-mini-transcribe"

1360)1403)

1361 1404 

1405raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

1406 

1362response = client.responses.create(1407response = client.responses.create(

1363 model: "gpt-4.1",1408 model: "gpt-4.1",

1364 input: "Add punctuation and paragraph breaks without changing the words:\n#{transcript.text}"1409 input: "Add punctuation and paragraph breaks without changing the words:\n#{transcript.text}"

Details

43 43 

44### Connect your own runtime44### Connect your own runtime

45 45 

46The following example shows the API loop for a runtime you provide. Python and Ruby send Python code to a desktop runtime that uses PyAutoGUI; JavaScript uses Playwright to operate a browser. Each client exposes an ordinary function tool and returns text or images with the original `call_id`.46The following example shows the API loop for a runtime you provide. Python, Ruby, and Go send Python code to a desktop runtime that uses PyAutoGUI; JavaScript uses Playwright to operate a browser. Each client exposes an ordinary function tool and returns text or images with the original `call_id`.

47 47 

48The `execute_in_sandbox` or `executeInSandbox` helper sends code to your execution environment and returns its observations. It must preserve the browser or desktop session, enforce execution limits, and apply your permission rules. These are integration examples, separate from running the sample app.48The `execute_in_sandbox` or `executeInSandbox` helper sends code to your execution environment and returns its observations. It must preserve the browser or desktop session, enforce execution limits, and apply your permission rules. These are integration examples, separate from running the sample app.

49 49 


285 285 

286 286

287 287 

288

289 

290

291Go

292 

293 Run computer use with code execution

294 

295```go

296func runComputerUse(ctx context.Context, client openai.Client, endpoint, prompt string, terminal *bufio.Scanner, output io.Writer) error {

297 session := make([]byte, 16)

298 if _, err := rand.Read(session); err != nil {

299 return err

300 }

301 sessionID := hex.EncodeToString(session)

302 tool := responses.ToolParamOfFunction("exec_py", map[string]any{

303 "type": "object", "properties": map[string]any{"code": map[string]any{"type": "string"}},

304 "required": []string{"code"}, "additionalProperties": false,

305 }, true)

306 tool.OfFunction.Description = openai.String("Run Python in a persistent desktop. Variables persist across calls. " +

307 "PyAutoGUI operations are synchronous. Available: pyautogui, time, " +

308 "log(value), and display(PIL_image). Inspect the screen with " +

309 "display(pyautogui.screenshot()) before acting. Use screenshot " +

310 "coordinates and check the screen after a short group of actions. " +

311 "Keep screenshots in memory and PyAutoGUI's fail-safe enabled.")

312 params := responses.ResponseNewParams{

313 Model: "gpt-6-astra", Tools: []responses.ToolUnionParam{tool},

314 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(prompt)},

315 }

316 for turn := 0; turn < 20; turn++ {

317 response, err := client.Responses.New(ctx, params)

318 if err != nil {

319 return err

320 }

321 if response.Status != "completed" {

322 return fmt.Errorf("response stopped with status: %s", response.Status)

323 }

324 var calls []responses.ResponseFunctionToolCall

325 finalMessage := false

326 for _, item := range response.Output {

327 if item.Type == "function_call" {

328 calls = append(calls, item.AsFunctionCall())

329 }

330 if item.Type == "message" && item.AsMessage().Phase != "commentary" {

331 finalMessage = true

332 }

333 }

334 if len(calls) == 0 && finalMessage {

335 fmt.Fprintln(output, response.OutputText())

336 return nil

337 }

338 if turn == 19 {

339 return fmt.Errorf("task reached the 20-response limit; inspect the last result")

340 }

341 nextInput := responses.ResponseInputParam{}

342 for _, call := range calls {

343 if call.Name != "exec_py" {

344 return fmt.Errorf("unexpected tool: %s", call.Name)

345 }

346 var arguments struct {

347 Code *string `json:"code"`

348 }

349 if err := json.Unmarshal([]byte(call.Arguments), &arguments); err != nil {

350 return err

351 }

352 if arguments.Code == nil {

353 return fmt.Errorf("exec_py requires code")

354 }

355 observations, err := executeInSandbox(ctx, endpoint, sessionID, *arguments.Code, terminal, output)

356 if err != nil {

357 return err

358 }

359 nextInput = append(nextInput, responses.ResponseInputItemUnionParam{

360 OfFunctionCallOutput: &responses.ResponseInputItemFunctionCallOutputParam{

361 CallID: openai.String(call.CallID),

362 Output: responses.ResponseInputItemFunctionCallOutputOutputUnionParam{OfResponseFunctionCallOutputItemArray: observations},

363 },

364 })

365 }

366 params.Input = responses.ResponseNewParamsInputUnion{OfInputItemList: nextInput}

367 params.PreviousResponseID = openai.String(response.ID)

368 }

369 return nil

370}

371```

372 

373 

374 

288<a id="connect-to-your-execution-service"></a>375<a id="connect-to-your-execution-service"></a>

289 376 

290For a complete client adapter and the expected text and image output shape, see [Connect to your execution service](https://developers.openai.com/api/docs/guides/tools-computer-use-integration#connect-to-your-execution-service). The service interface in those examples belongs to your application; it is not an OpenAI-hosted endpoint.377For a complete client adapter and the expected text and image output shape, see [Connect to your execution service](https://developers.openai.com/api/docs/guides/tools-computer-use-integration#connect-to-your-execution-service). The service interface in those examples belongs to your application; it is not an OpenAI-hosted endpoint.

Details

640}640}

641```641```

642 642 

643```java

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

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

646import com.openai.core.JsonValue;

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

648import java.util.ArrayList;

649import java.util.List;

650import java.util.Map;

651 

652var json = new ObjectMapper();

653var tools =

654 List.of(

655 Tool.ofFunction(function("get_inventory", "available_units")),

656 Tool.ofFunction(function("get_demand", "requested_units")),

657 Tool.ofProgrammaticToolCalling());

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

659input.add(

660 ResponseInputItem.ofEasyInputMessage(

661 EasyInputMessage.builder()

662 .role(EasyInputMessage.Role.USER)

663 .content("Compare inventory with demand for sku_123.")

664 .build()));

665 

666while (true) {

667 var response =

668 client

669 .responses()

670 .create(

671 ResponseCreateParams.builder()

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

673 .store(false)

674 .inputOfResponse(input)

675 .tools(tools)

676 .build());

677 if (!response.status().orElseThrow().equals(ResponseStatus.COMPLETED)) {

678 throw new IllegalStateException("Response ended with status " + response.status());

679 }

680 // Preserve every replayable output item, including program and reasoning items.

681 response.output().stream()

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

683 .forEach(input::add);

684 var calls = response.output().stream().flatMap(item -> item.functionCall().stream()).toList();

685 if (calls.isEmpty()) {

686 var messages = response.output().stream().flatMap(item -> item.message().stream()).toList();

687 if (!messages.isEmpty()) {

688 messages.forEach(

689 message ->

690 message

691 .content()

692 .forEach(

693 content -> {

694 content.outputText().ifPresent(text -> System.out.println(text.text()));

695 content

696 .refusal()

697 .ifPresent(refusal -> System.out.println(refusal.refusal()));

698 }));

699 break;

700 }

701 continue;

702 }

703 for (var call : calls) {

704 String sku = json.readTree(call.arguments()).get("sku").asText();

705 var result =

706 switch (call.name()) {

707 case "get_inventory" -> Map.of("sku", sku, "available_units", 42);

708 case "get_demand" -> Map.of("sku", sku, "requested_units", 31);

709 default -> throw new IllegalArgumentException("Unknown tool: " + call.name());

710 };

711 var output =

712 ResponseInputItem.FunctionCallOutput.builder()

713 .callId(call.callId())

714 .output(json.writeValueAsString(result));

715 // Preserve caller so the runtime can resume the correct program.

716 call.caller()

717 .ifPresent(

718 caller ->

719 output.caller(

720 JsonValue.from(caller)

721 .convert(ResponseInputItem.FunctionCallOutput.Caller.class)));

722 input.add(ResponseInputItem.ofFunctionCallOutput(output.build()));

723 }

724}

725 

726private static FunctionTool function(String name, String outputField) {

727 var parameters =

728 Map.of(

729 "type",

730 "object",

731 "properties",

732 Map.of("sku", Map.of("type", "string")),

733 "required",

734 List.of("sku"),

735 "additionalProperties",

736 false);

737 var outputSchema =

738 Map.of(

739 "type",

740 "object",

741 "properties",

742 Map.of("sku", Map.of("type", "string"), outputField, Map.of("type", "number")),

743 "required",

744 List.of("sku", outputField),

745 "additionalProperties",

746 false);

747 return FunctionTool.builder()

748 .name(name)

749 .description("Return an object with sku (string) and " + outputField + " (number).")

750 .parameters(JsonValue.from(parameters).convert(FunctionTool.Parameters.class))

751 .outputSchema(JsonValue.from(outputSchema).convert(FunctionTool.OutputSchema.class))

752 .allowedCallers(List.of(FunctionTool.AllowedCaller.PROGRAMMATIC))

753 .strict(true)

754 .build();

755}

756```

757 

643```ruby758```ruby

644require "json"759require "json"

645require "openai"760require "openai"

Details

6 6 

7To receive misalignment monitoring notifications for an API project, see [Receive project safety alerts](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring#receive-project-safety-alerts).7To receive misalignment monitoring notifications for an API project, see [Receive project safety alerts](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring#receive-project-safety-alerts).

8 8 

9To receive organization-level warning and deactivation notices for safety identifiers, see [Safety enforcement notifications](https://developers.openai.com/api/docs/guides/safety-enforcement).

10 

9For Agents API sessions, see [Session webhooks](https://developers.openai.com/api/docs/guides/agents-api/sessions/webhooks) for session events and recovery patterns. Use the endpoint setup, signature verification, and delivery guidance on this page for the webhook receiver.11For Agents API sessions, see [Session webhooks](https://developers.openai.com/api/docs/guides/agents-api/sessions/webhooks) for session events and recovery patterns. Use the endpoint setup, signature verification, and delivery guidance on this page for the webhook receiver.

10 12 

11[API reference for webhook events13[API reference for webhook events


273 275 

274## Creating webhook endpoints276## Creating webhook endpoints

275 277 

276To start receiving webhook requests on your server, log in to the dashboard and [open the webhook settings page](https://platform.openai.com/settings/project/webhooks). Webhooks are configured per-project.278To start receiving project webhook requests on your server, log in to the dashboard and [open the webhook settings page](https://platform.openai.com/settings/project/webhooks). The setup in this section is for project endpoints. For organization-level safety events, see [Safety enforcement notifications](https://developers.openai.com/api/docs/guides/safety-enforcement).

277 279 

278Click the "Create" button to create a new webhook endpoint. You will configure three things:280Click the "Create" button to create a new webhook endpoint. You will configure three things:

279 281 

libraries.md +1 −1

Details

173<dependency>173<dependency>

174 <groupId>com.openai</groupId>174 <groupId>com.openai</groupId>

175 <artifactId>openai-java</artifactId>175 <artifactId>openai-java</artifactId>

176 <version>4.74.0</version>176 <version>4.75.1</version>

177</dependency>177</dependency>

178```178```

179 179 

models/all.md +5 −5

Details

39- [GPT-4o Transcribe](/api/docs/models/gpt-4o-transcribe.md): Speech-to-text model powered by GPT-4o39- [GPT-4o Transcribe](/api/docs/models/gpt-4o-transcribe.md): Speech-to-text model powered by GPT-4o

40- [GPT-4o Mini Transcribe](/api/docs/models/gpt-4o-mini-transcribe.md): Speech-to-text model powered by GPT-4o Mini40- [GPT-4o Mini Transcribe](/api/docs/models/gpt-4o-mini-transcribe.md): Speech-to-text model powered by GPT-4o Mini

41- [GPT-4o Transcribe Diarize](/api/docs/models/gpt-4o-transcribe-diarize.md): Transcription model that identifies who's speaking when41- [GPT-4o Transcribe Diarize](/api/docs/models/gpt-4o-transcribe-diarize.md): Transcription model that identifies who's speaking when

42- [TTS-1](/api/docs/models/tts-1.md): Text-to-speech model optimized for speed

43- [TTS-1 HD](/api/docs/models/tts-1-hd.md): Text-to-speech model optimized for quality

44- [Whisper](/api/docs/models/whisper-1.md): General-purpose speech recognition model42- [Whisper](/api/docs/models/whisper-1.md): General-purpose speech recognition model

45- [GPT-4o Mini TTS](/api/docs/models/gpt-4o-mini-tts.md): Text-to-speech model powered by GPT-4o Mini43- [GPT-4o Mini TTS](/api/docs/models/gpt-4o-mini-tts.md): Text-to-speech model powered by GPT-4o Mini

46 44 


86- [GPT-5.4](/api/docs/models/gpt-5.4.md): A more affordable model for coding and professional work.84- [GPT-5.4](/api/docs/models/gpt-5.4.md): A more affordable model for coding and professional work.

87- [GPT-5.4 Pro](/api/docs/models/gpt-5.4-pro.md): Version of GPT-5.4 that produces smarter and more precise responses.85- [GPT-5.4 Pro](/api/docs/models/gpt-5.4-pro.md): Version of GPT-5.4 that produces smarter and more precise responses.

88- [GPT-5.4 Mini](/api/docs/models/gpt-5.4-mini.md): Our strongest mini model yet for coding, computer use, and subagents86- [GPT-5.4 Mini](/api/docs/models/gpt-5.4-mini.md): Our strongest mini model yet for coding, computer use, and subagents

89- [GPT-5.4 nano](/api/docs/models/gpt-5.4-nano.md): Our cheapest GPT-5.4-class model for simple high-volume tasks

90- [GPT-5.3-Codex](/api/docs/models/gpt-5.3-codex.md): The most capable agentic coding model to date.

91- [GPT-5.2](/api/docs/models/gpt-5.2.md): Previous flagship model for professional work with configurable reasoning effort87- [GPT-5.2](/api/docs/models/gpt-5.2.md): Previous flagship model for professional work with configurable reasoning effort

92- [GPT-5.2 Pro](/api/docs/models/gpt-5.2-pro.md): Previous pro model for professional work that produces smarter and more precise responses.88- [GPT-5.2 Pro](/api/docs/models/gpt-5.2-pro.md): Previous pro model for professional work that produces smarter and more precise responses.

93- [GPT-5.1](/api/docs/models/gpt-5.1.md): The best model for coding and agentic tasks with configurable reasoning effort

94- [GPT-5](/api/docs/models/gpt-5.md): Previous intelligent reasoning model for coding and agentic tasks with configurable reasoning effort89- [GPT-5](/api/docs/models/gpt-5.md): Previous intelligent reasoning model for coding and agentic tasks with configurable reasoning effort

95- [GPT-5 Mini](/api/docs/models/gpt-5-mini.md): Strong intelligence for cost sensitive, low latency, high volume workloads90- [GPT-5 Mini](/api/docs/models/gpt-5-mini.md): Strong intelligence for cost sensitive, low latency, high volume workloads

96- [GPT-5 nano](/api/docs/models/gpt-5-nano.md): Fastest, most cost-efficient version of GPT-591- [GPT-5 nano](/api/docs/models/gpt-5-nano.md): Fastest, most cost-efficient version of GPT-5


102- [omni-moderation](/api/docs/models/omni-moderation-latest.md): Identify potentially harmful content in text and images97- [omni-moderation](/api/docs/models/omni-moderation-latest.md): Identify potentially harmful content in text and images

103- [GPT-4o Mini](/api/docs/models/gpt-4o-mini.md): Fast, affordable small model for focused tasks98- [GPT-4o Mini](/api/docs/models/gpt-4o-mini.md): Fast, affordable small model for focused tasks

104- [GPT-4o](/api/docs/models/gpt-4o.md): Fast, intelligent, flexible GPT model99- [GPT-4o](/api/docs/models/gpt-4o.md): Fast, intelligent, flexible GPT model

100- [GPT-5.4 nano](/api/docs/models/gpt-5.4-nano.md): Deprecated. Our cheapest GPT-5.4-class model for simple high-volume tasks

101- [GPT-5.3-Codex](/api/docs/models/gpt-5.3-codex.md): Deprecated. The most capable agentic coding model to date.

102- [GPT-5.1](/api/docs/models/gpt-5.1.md): Deprecated. The best model for coding and agentic tasks with configurable reasoning effort

105- [GPT-Realtime](/api/docs/models/gpt-realtime.md): Deprecated. Model capable of realtime text and audio inputs and outputs103- [GPT-Realtime](/api/docs/models/gpt-realtime.md): Deprecated. Model capable of realtime text and audio inputs and outputs

106- [GPT-Audio](/api/docs/models/gpt-audio.md): Deprecated. For audio inputs and outputs with Chat Completions API104- [GPT-Audio](/api/docs/models/gpt-audio.md): Deprecated. For audio inputs and outputs with Chat Completions API

105- [TTS-1](/api/docs/models/tts-1.md): Deprecated. Text-to-speech model optimized for speed

106- [TTS-1 HD](/api/docs/models/tts-1-hd.md): Deprecated. Text-to-speech model optimized for quality

107- [GPT-5.3 Chat](/api/docs/models/gpt-5.3-chat-latest.md): Deprecated. GPT-5.3 Instant model used in ChatGPT107- [GPT-5.3 Chat](/api/docs/models/gpt-5.3-chat-latest.md): Deprecated. GPT-5.3 Instant model used in ChatGPT

108- [GPT-5.2 Chat](/api/docs/models/gpt-5.2-chat-latest.md): Deprecated. GPT-5.2 model used in ChatGPT108- [GPT-5.2 Chat](/api/docs/models/gpt-5.2-chat-latest.md): Deprecated. GPT-5.2 model used in ChatGPT

109- [GPT-5.2-Codex](/api/docs/models/gpt-5.2-codex.md): Deprecated. Our most intelligent coding model optimized for long-horizon, agentic coding tasks.109- [GPT-5.2-Codex](/api/docs/models/gpt-5.2-codex.md): Deprecated. Our most intelligent coding model optimized for long-horizon, agentic coding tasks.

quickstart.md +1 −1

Details

190<dependency>190<dependency>

191 <groupId>com.openai</groupId>191 <groupId>com.openai</groupId>

192 <artifactId>openai-java</artifactId>192 <artifactId>openai-java</artifactId>

193 <version>4.74.0</version>193 <version>4.75.1</version>

194</dependency>194</dependency>

195```195```

196 196