SpyBara
Go Premium

Documentation 2026-11-18 22:59 UTC to 2026-11-19 22:59 UTC

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

deprecations.md +1 −0

Details

76| **Nov 30, 2026** | Evals dashboard, API, and graders for eval workflows | Read-only | [Migrate to Promptfoo](https://developers.openai.com/cookbook/examples/evaluation/moving-from-openai-evals-to-promptfoo). For fine-tuning graders, see the [fine-tuning timeline](#update-to-openais-self-serve-fine-tuning). | Jun 3, 2026 |76| **Nov 30, 2026** | Evals dashboard, API, and graders for eval workflows | Read-only | [Migrate to Promptfoo](https://developers.openai.com/cookbook/examples/evaluation/moving-from-openai-evals-to-promptfoo). For fine-tuning graders, see the [fine-tuning timeline](#update-to-openais-self-serve-fine-tuning). | Jun 3, 2026 |

77| **Nov 30, 2026** | Agent Builder | Deprecated | Agents SDK or ChatGPT Workspace Agents. [Migration guide](https://developers.openai.com/api/docs/guides/agent-builder/migrate-from-agent-builder). ChatKit remains available. | Jun 3, 2026 |77| **Nov 30, 2026** | Agent Builder | Deprecated | Agents SDK or ChatGPT Workspace Agents. [Migration guide](https://developers.openai.com/api/docs/guides/agent-builder/migrate-from-agent-builder). ChatKit remains available. | Jun 3, 2026 |

78| **Jan 6, 2027** | Self-serve fine-tuning job creation | Restricted access | See the [fine-tuning timeline](#update-to-openais-self-serve-fine-tuning). | May 7, 2026 |78| **Jan 6, 2027** | Self-serve fine-tuning job creation | Restricted access | See the [fine-tuning timeline](#update-to-openais-self-serve-fine-tuning). | May 7, 2026 |

79| **Jan 11, 2027** | GPT-5.2, GPT-5.4, and GPT-5.4 mini with EU data residency and `service_tier: fast` or `priority` | Deprecated | The same models with EU data residency and Standard processing (`service_tier: default`), or the [GPT-6.2 model family](https://developers.openai.com/api/docs/guides/latest-model). | Nov 18, 2026 |

79| **Feb 26, 2027** | `/v1/audio/translations` | Deprecated | [`/v1/realtime/translations`](https://developers.openai.com/api/docs/guides/realtime-translation) | Aug 26, 2026 |80| **Feb 26, 2027** | `/v1/audio/translations` | Deprecated | [`/v1/realtime/translations`](https://developers.openai.com/api/docs/guides/realtime-translation) | Aug 26, 2026 |

80 81 

81 82 

Details

51 51 

52This local counter applies only to text messages for that historical snapshot. Message formatting varies by model.52This local counter applies only to text messages for that historical snapshot. Message formatting varies by model.

53 53 

54 

55 

56 

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

58 

59 

60 

61 

54Count chat message tokens62Count chat message tokens

55 63 

56```python64```python


78 )86 )

79```87```

80 88 

89```go

90package main

91 

92import (

93 "fmt"

94 "github.com/tiktoken-go/tokenizer"

95)

96 

97// numTokensFromMessages estimates the historical model's message framing.

98// Other models and tool definitions require different accounting.

99func numTokensFromMessages(messages []map[string]string, model string) (int, error) {

100 if model != "gpt-3.5-turbo-0613" {

101 return 0, fmt.Errorf("unsupported token-counting model: %s", model)

102 }

103 encoding, err := tokenizer.Get(tokenizer.Cl100kBase)

104 if err != nil {

105 return 0, err

106 }

107 total := 3

108 for _, message := range messages {

109 total += 3

110 for key, value := range message {

111 ids, _, err := encoding.Encode(value)

112 if err != nil {

113 return 0, err

114 }

115 total += len(ids)

116 if key == "name" {

117 total++

118 }

119 }

120 }

121 return total, nil

122}

123 

124func main() {

125 count, err := numTokensFromMessages([]map[string]string{{"role": "user", "content": "Hi"}}, "gpt-3.5-turbo-0613")

126 if err != nil {

127 panic(err)

128 }

129 fmt.Println(count)

130}

131```

132 

81```ruby133```ruby

82require "tiktoken_ruby"134require "tiktoken_ruby"

83 135 


134# 129 prompt tokens counted.186# 129 prompt tokens counted.

135```187```

136 188 

189```go

190package main

191 

192import (

193 "fmt"

194 "github.com/tiktoken-go/tokenizer"

195)

196 

197// numTokensFromMessages estimates the historical model's message framing.

198// Other models and tool definitions require different accounting.

199func numTokensFromMessages(messages []map[string]string, model string) (int, error) {

200 if model != "gpt-3.5-turbo-0613" {

201 return 0, fmt.Errorf("unsupported token-counting model: %s", model)

202 }

203 encoding, err := tokenizer.Get(tokenizer.Cl100kBase)

204 if err != nil {

205 return 0, err

206 }

207 total := 3

208 for _, message := range messages {

209 total += 3

210 for key, value := range message {

211 ids, _, err := encoding.Encode(value)

212 if err != nil {

213 return 0, err

214 }

215 total += len(ids)

216 if key == "name" {

217 total++

218 }

219 }

220 }

221 return total, nil

222}

223 

224var messages = []map[string]string{

225 {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},

226 {"role": "system", "name": "example_user", "content": "New synergies will help drive top-line growth."},

227 {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},

228 {"role": "system", "name": "example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},

229 {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},

230 {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},

231}

232 

233const model = "gpt-3.5-turbo-0613"

234 

235func main() {

236 count, err := numTokensFromMessages(messages, model)

237 if err != nil {

238 panic(err)

239 }

240 fmt.Printf("%d prompt tokens counted.\n", count)

241}

242```

243 

137```ruby244```ruby

138require "json"245require "json"

139 246 


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

215```322```

216 323 

324```go

325package main

326 

327import (

328 "context"

329 "fmt"

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

331)

332 

333func main() {

334 client := openai.NewClient()

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

336 Model: "gpt-6.2-astra",

337 Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Translate this sentence into plain English.")},

338 })

339 if err != nil {

340 panic(err)

341 }

342 fmt.Printf("%d prompt tokens used.\n", response.Usage.PromptTokens)

343}

344```

345 

217```java346```java

218import com.openai.client.OpenAIClient;347import com.openai.client.OpenAIClient;

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


273mu[j] = mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence402mu[j] = mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence

274```403```

275 404 

405```go

406mu[j] -= counts[j] * frequency

407if counts[j] > 0 {

408 mu[j] -= presence

409}

410```

411 

276```ruby412```ruby

277mu[j] = mu[j] - c[j] * alpha_frequency - ((c[j] > 0) ? alpha_presence : 0.0)413mu[j] = mu[j] - c[j] * alpha_frequency - ((c[j] > 0) ? alpha_presence : 0.0)

278```414```

Details

480 480 

481You cannot update `reasoning.summary`, `text`, `instructions`, or `multi_agent` through this endpoint. Create a new session to change those settings. See the [Update session reference](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/update) for request fields.481You cannot update `reasoning.summary`, `text`, `instructions`, or `multi_agent` through this endpoint. Create a new session to change those settings. See the [Update session reference](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/update) for request fields.

482 482 

483## Use Daybreak in a session

484 

485The Agents API supports Daybreak Blue and Daybreak Red. Use an API key from a project with access to both your [chosen model and its cyber access program](https://developers.openai.com/api/docs/guides/daybreak#choose-the-model-and-access-program).

486 

487When you [create a session](https://developers.openai.com/api/docs/guides/agents-api/quickstart?lang=cURL), include the fields for your program in the request body.

488 

489**Daybreak Blue**

490 

491```json

492{

493 "agent": { "model": "gpt-6-sol" },

494 "access_programs": { "cyber": "daybreak_blue" }

495}

496```

497 

498**Daybreak Red**

499 

500```json

501{

502 "agent": { "model": "gpt-5.6-cyber" },

503 "access_programs": { "cyber": "daybreak_red" }

504}

505```

506 

483## Automatic action review507## Automatic action review

484 508 

485Set the session-level `review` field to `"auto_review"` to automatically review supported approval requests. Set it alongside `agent` or `agent_id`, rather than inside the agent configuration. If you omit `review` when creating a session, the value defaults to `"none"`.509Set the session-level `review` field to `"auto_review"` to automatically review supported approval requests. Set it alongside `agent` or `agent_id`, rather than inside the agent configuration. If you omit `review` when creating a session, the value defaults to `"none"`.

Details

97 raise FileNotFoundError(f"No artifact for {path!r} in turn {turn_id}")97 raise FileNotFoundError(f"No artifact for {path!r} in turn {turn_id}")

98```98```

99 99 

100```go

101package main

102 

103import (

104 "context"

105 "fmt"

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

107 "io"

108 "log"

109 "os"

110 "time"

111)

112 

113func downloadArtifact(ctx context.Context, client *openai.Client, sessionID, turnID, path, destination string) error {

114 artifacts := client.Beta.Agents.Sessions.Artifacts.ListAutoPaging(ctx, sessionID, openai.BetaAgentSessionArtifactListParams{})

115 for artifacts.Next() {

116 artifact := artifacts.Current()

117 if artifact.TurnID != turnID || artifact.Path != path {

118 continue

119 }

120 content, err := client.Beta.Agents.Sessions.Artifacts.Content(ctx, sessionID, artifact.ID)

121 if err != nil {

122 return err

123 }

124 defer content.Body.Close()

125 output, err := os.Create(destination)

126 if err != nil {

127 return err

128 }

129 _, copyErr := io.Copy(output, content.Body)

130 closeErr := output.Close()

131 if copyErr != nil {

132 return copyErr

133 }

134 return closeErr

135 }

136 if err := artifacts.Err(); err != nil {

137 return err

138 }

139 return fmt.Errorf("no artifact for %q in turn %s", path, turnID)

140}

141func main() {

142 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)

143 defer cancel()

144 client := openai.NewClient()

145 if err := downloadArtifact(ctx, &client, "sess_123", "turn_123", "/workspace/outputs/report.pdf", "report.pdf"); err != nil {

146 log.Fatal(err)

147 }

148}

149```

150 

100```ruby151```ruby

101require "openai"152require "openai"

102 153 

Details

88print(environment_id)88print(environment_id)

89```89```

90 90 

91```go

92ctx := context.Background()

93client := openai.NewClient()

94environment, err := client.Beta.Agents.Environments.New(ctx, openai.BetaAgentEnvironmentNewParams{

95 Environment: openai.BetaAgentEnvironmentNewParamsEnvironment{

96 Packages: openai.BetaAgentEnvironmentNewParamsEnvironmentPackages{Python: []string{"pandas==2.2.3"}},

97 Files: []openai.HostedEnvironmentFileParamUnion{{OfParamInline: &openai.HostedEnvironmentFileParamInline{Path: "/workspace/amounts.csv", Data: "YW1vdW50CjEwCjIwCjMwCg=="}}},

98 SetupCommands: []openai.SetupCommandParam{{Command: `python -c "import pandas; print(pandas.__version__)"`, Cwd: openai.String("/workspace")}},

99 },

100})

101if err != nil {

102 panic(err)

103}

104environmentID := environment.ID

105fmt.Println(environmentID)

106```

107 

91```java108```java

92import com.openai.client.okhttp.OpenAIOkHttpClient;109import com.openai.client.okhttp.OpenAIOkHttpClient;

93 110 


181```198```

182 199 

183```go200```go

184current, err := client.Beta.Agents.Environments.Get(context.Background(), environmentID)201current, err := client.Beta.Agents.Environments.Get(ctx, environmentID)

185if err != nil {202if err != nil {

186 panic(err)203 panic(err)

187}204}


247 print(event.model_dump_json())264 print(event.model_dump_json())

248```265```

249 266 

267```go

268stream := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{

269 Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra")},

270 Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{EnvironmentID: openai.String(environmentID)}},

271 Input: openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Use pandas to read /workspace/amounts.csv, calculate the sum of the amount column, and report the total.")},

272})

273defer stream.Close()

274completed := false

275for stream.Next() {

276 event := stream.Current()

277 fmt.Println(event.RawJSON())

278 switch event.Type {

279 case "agent.session.turn.failed", "error":

280 panic("Agent turn failed")

281 case "agent.session.turn.completed":

282 completed = true

283 }

284}

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

286 panic(err)

287}

288if !completed {

289 panic("Stream ended before the turn completed")

290}

291```

292 

250```java293```java

251import com.openai.models.beta.agents.EnvironmentParam;294import com.openai.models.beta.agents.EnvironmentParam;

252 295 


328print(environment.id)371print(environment.id)

329```372```

330 373 

374```go

375environment, err := client.Beta.Agents.Environments.New(context.Background(), openai.BetaAgentEnvironmentNewParams{

376 Environment: openai.BetaAgentEnvironmentNewParamsEnvironment{

377 EnvironmentTemplateID: openai.String("envtmpl_REPLACE_WITH_TEMPLATE_ID"),

378 },

379})

380if err != nil {

381 panic(err)

382}

383fmt.Println(environment.ID)

384```

385 

331```java386```java

332import com.openai.client.okhttp.OpenAIOkHttpClient;387import com.openai.client.okhttp.OpenAIOkHttpClient;

333import com.openai.models.beta.agents.environments.EnvironmentCreateParams;388import com.openai.models.beta.agents.environments.EnvironmentCreateParams;


396print(environment.id)451print(environment.id)

397```452```

398 453 

454```go

455environment, err := client.Beta.Agents.Environments.New(context.Background(), openai.BetaAgentEnvironmentNewParams{

456 Environment: openai.BetaAgentEnvironmentNewParamsEnvironment{

457 Desktop: openai.BetaAgentEnvironmentNewParamsEnvironmentDesktop{Enabled: openai.Bool(true)},

458 },

459})

460if err != nil {

461 panic(err)

462}

463fmt.Println(environment.ID)

464```

465 

399```java466```java

400import com.openai.client.okhttp.OpenAIOkHttpClient;467import com.openai.client.okhttp.OpenAIOkHttpClient;

401import com.openai.models.beta.agents.environments.EnvironmentCreateParams;468import com.openai.models.beta.agents.environments.EnvironmentCreateParams;


457 print(item.model_dump_json())524 print(item.model_dump_json())

458```525```

459 526 

527```go

528environments, err := client.Beta.Agents.Environments.List(ctx, openai.BetaAgentEnvironmentListParams{Limit: openai.Int(20), Order: "desc"})

529if err != nil {

530 panic(err)

531}

532for _, item := range environments.Data {

533 fmt.Println(item.ID)

534}

535```

536 

460```java537```java

461import com.openai.models.beta.agents.environments.EnvironmentListParams;538import com.openai.models.beta.agents.environments.EnvironmentListParams;

462 539 

Details

229| E2B | [E2B setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/e2b) |229| E2B | [E2B setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/e2b) |

230| Modal | [Modal setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/modal) |230| Modal | [Modal setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/modal) |

231| Oracle Cloud Infrastructure (OCI) | [OCI setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/oci) |231| Oracle Cloud Infrastructure (OCI) | [OCI setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/oci) |

232| Render | [Render setup](https://render.com/docs/sandboxes-openai-agents-api) |

232| Vercel | [Vercel setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/vercel) |233| Vercel | [Vercel setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/vercel) |

233 234 

234For webhook-managed provisioning, implement a handler using [Sandbox lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle#start-compute-from-webhooks) and your provider's SDK or API. Keep provisioning ownership and cleanup policies explicit.235For webhook-managed provisioning, implement a handler using [Sandbox lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle#start-compute-from-webhooks) and your provider's SDK or API. Keep provisioning ownership and cleanup policies explicit.

Details

141 server.run(transport=transport)141 server.run(transport=transport)

142```142```

143 143 

144```go

145package main

146 

147import (

148 "context"

149 "errors"

150 "fmt"

151 "log"

152 "net"

153 "net/http"

154 "os"

155 "os/signal"

156 "syscall"

157 "time"

158 

159 "github.com/modelcontextprotocol/go-sdk/mcp"

160)

161 

162type lookupInput struct {

163 CustomerID string `json:"customer_id" jsonschema:"Customer ID to look up"`

164}

165type customer struct {

166 Name string `json:"name"`

167 Plan string `json:"plan"`

168}

169type lookupOutput struct {

170 Customer *customer `json:"customer"`

171}

172 

173func main() {

174 ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)

175 defer cancel()

176 server := mcp.NewServer(&mcp.Implementation{Name: "customer-lookup", Version: "1.0.0"}, nil)

177 mcp.AddTool(server, &mcp.Tool{Name: "get_customer", Description: "Look up a customer in the example data."},

178 func(_ context.Context, _ *mcp.CallToolRequest, input lookupInput) (*mcp.CallToolResult, lookupOutput, error) {

179 customers := map[string]*customer{"123": {Name: "Example Customer", Plan: "pro"}}

180 return nil, lookupOutput{Customer: customers[input.CustomerID]}, nil

181 })

182 // Default to stdio. Run `go run . http` to expose /mcp over HTTP.

183 if len(os.Args) < 2 || os.Args[1] != "http" {

184 if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil && ctx.Err() == nil {

185 log.Fatal(err)

186 }

187 return

188 }

189 port := "8765"

190 handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})

191 mux := http.NewServeMux()

192 mux.Handle("/mcp", handler)

193 listener, err := net.Listen("tcp", "127.0.0.1:"+port)

194 if err != nil {

195 log.Fatal(err)

196 }

197 httpServer := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}

198 fmt.Println("Listening on http://" + listener.Addr().String())

199 shutdownDone := make(chan struct{})

200 go func() {

201 defer close(shutdownDone)

202 <-ctx.Done()

203 shutdownCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)

204 defer stop()

205 if err := httpServer.Shutdown(shutdownCtx); err != nil {

206 log.Print(err)

207 }

208 }()

209 if err := httpServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {

210 log.Fatal(err)

211 }

212 <-shutdownDone

213}

214```

215 

144```ruby216```ruby

145require "mcp"217require "mcp"

146require "json"218require "json"

Details

173 173 

174 174 

175 175 

176The Go program uses the OpenAI SDK and standard-library ZIP support. It creates a temporary example plugin, uploads it, and removes the local directory. To upload your own plugin, call `uploadPlugin` with its directory. The program rejects symbolic links and other non-regular files when creating the archive.

177 

178 

179 

180 

181 

182 

183 

176The Ruby helper requires the `openai` and `rubyzip` gems. Install them with `gem install openai rubyzip` and set `OPENAI_API_KEY` before creating the client.184The Ruby helper requires the `openai` and `rubyzip` gems. Install them with `gem install openai rubyzip` and set `OPENAI_API_KEY` before creating the client.

177 185 

178 186 


220 )228 )

221```229```

222 230 

231```go

232package main

233 

234import (

235 "archive/zip"

236 "bytes"

237 "context"

238 "encoding/base64"

239 "encoding/json"

240 "fmt"

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

242 "io"

243 "io/fs"

244 "log"

245 "os"

246 "path/filepath"

247 "time"

248)

249 

250func uploadPlugin(ctx context.Context, client *openai.Client, directory string) (*openai.AgentSession, error) {

251 directory, err := filepath.Abs(directory)

252 if err != nil {

253 return nil, err

254 }

255 data, err := os.ReadFile(filepath.Join(directory, ".codex-plugin/plugin.json"))

256 if err != nil {

257 return nil, err

258 }

259 var manifest struct {

260 Name string `json:"name"`

261 Description string `json:"description"`

262 }

263 if err := json.Unmarshal(data, &manifest); err != nil {

264 return nil, err

265 }

266 if manifest.Name == "" || manifest.Description == "" {

267 return nil, fmt.Errorf("plugin manifest requires name and description")

268 }

269 var buffer bytes.Buffer

270 archive := zip.NewWriter(&buffer)

271 err = filepath.WalkDir(directory, func(path string, entry fs.DirEntry, walkErr error) error {

272 if walkErr != nil {

273 return walkErr

274 }

275 if entry.IsDir() {

276 return nil

277 }

278 if !entry.Type().IsRegular() {

279 return fmt.Errorf("plugin archive requires regular files: %s", path)

280 }

281 relative, err := filepath.Rel(directory, path)

282 if err != nil {

283 return err

284 }

285 member, err := archive.Create(filepath.ToSlash(filepath.Join(filepath.Base(directory), relative)))

286 if err != nil {

287 return err

288 }

289 file, err := os.Open(path)

290 if err != nil {

291 return err

292 }

293 defer file.Close()

294 _, err = io.Copy(member, file)

295 return err

296 })

297 closeErr := archive.Close()

298 if err != nil {

299 return nil, err

300 }

301 if closeErr != nil {

302 return nil, closeErr

303 }

304 return client.Beta.Agents.Sessions.New(ctx, openai.BetaAgentSessionNewParams{Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra")}, Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{Plugins: []openai.HostedPluginParam{{Name: manifest.Name, Description: manifest.Description, Source: openai.InlineCapabilitySourceParam{Data: base64.StdEncoding.EncodeToString(buffer.Bytes())}}}}}})

305}

306func run() error {

307 temporary, err := os.MkdirTemp("", "docs-plugin-")

308 if err != nil {

309 return err

310 }

311 defer os.RemoveAll(temporary)

312 directory := filepath.Join(temporary, "docs-helper")

313 files := map[string]string{

314 ".codex-plugin/plugin.json": `{"name":"docs-helper","version":"1.0.0","description":"Find answers in OpenAI developer documentation.","skills":"./skills/","mcpServers":"./.mcp.json"}`,

315 ".mcp.json": `{"mcpServers":{"openai_docs":{"type":"http","url":"https://developers.openai.com/mcp"}}}`,

316 "skills/docs-search/SKILL.md": "---\nname: docs-search\ndescription: Find answers in OpenAI developer documentation.\n---\n\nUse the openai_docs MCP server to find relevant documentation.\nAnswer the question and link to the sources you used.\n",

317 }

318 for name, content := range files {

319 path := filepath.Join(directory, name)

320 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {

321 return err

322 }

323 if err := os.WriteFile(path, []byte(content), 0600); err != nil {

324 return err

325 }

326 }

327 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)

328 defer cancel()

329 client := openai.NewClient()

330 session, err := uploadPlugin(ctx, &client, directory)

331 if err != nil {

332 return err

333 }

334 fmt.Println(session.ID)

335 return nil

336}

337func main() {

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

339 log.Fatal(err)

340 }

341}

342```

343 

223```ruby344```ruby

224require "openai"345require "openai"

225require "json"346require "json"

Details

187 187 

188## Use discounted completion windows188## Use discounted completion windows

189 189 

190Starting with GPT-6.2 Astra and Sol, new models launch without Flex processing

191(`service_tier: flex`). For long-running Responses API requests, use discounted

192completion windows with Standard processing on supported models.

193 

190Discounted completion windows are in public beta on GPT-6.2 Astra, GPT-6.2194Discounted completion windows are in public beta on GPT-6.2 Astra, GPT-6.2

191 Sol, GPT-6.1 Terra, and GPT-6 Luna.195 Sol, GPT-6.1 Terra, and GPT-6 Luna.

192 196 

Details

108 108 

109async function respond() {109async function respond() {

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

111 model: "gpt-5.3-codex",111 model: "gpt-6.2-astra",

112 input: conversation,112 input: conversation,

113 store: false,113 store: false,

114 context_management: [{ type: "compaction", compact_threshold: 200_000 }],114 context_management: [{ type: "compaction", compact_threshold: 200_000 }],


141 141 

142while keep_going:142while keep_going:

143 response = client.responses.create(143 response = client.responses.create(

144 model="gpt-5.3-codex",144 model="gpt-6.2-astra",

145 input=conversation,145 input=conversation,

146 store=False,146 store=False,

147 context_management=[{"type": "compaction", "compact_threshold": 200000}],147 context_management=[{"type": "compaction", "compact_threshold": 200000}],


184 scanner := bufio.NewScanner(os.Stdin)184 scanner := bufio.NewScanner(os.Stdin)

185 for {185 for {

186 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{186 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

187 Model: "gpt-5.3-codex",187 Model: "gpt-6.2-astra",

188 Store: openai.Bool(false),188 Store: openai.Bool(false),

189 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: conversation},189 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: conversation},

190 ContextManagement: []responses.ResponseNewParamsContextManagement{{190 ContextManagement: []responses.ResponseNewParamsContextManagement{{


242 242 

243ResponseCreateParams params =243ResponseCreateParams params =

244 ResponseCreateParams.builder()244 ResponseCreateParams.builder()

245 .model("gpt-5.3-codex")245 .model("gpt-6.2-astra")

246 .inputOfResponse(conversation)246 .inputOfResponse(conversation)

247 .store(false)247 .store(false)

248 .putAdditionalBodyProperty(248 .putAdditionalBodyProperty(


286 286 

287loop do287loop do

288 response = client.responses.create(288 response = client.responses.create(

289 model: "gpt-5.3-codex",289 model: "gpt-6.2-astra",

290 input: conversation,290 input: conversation,

291 store: false,291 store: false,

292 context_management: [292 context_management: [


334import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";334import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

335 335 

336const client = new OpenAI();336const client = new OpenAI();

337const model = "gpt-6-astra";337const model = "gpt-6.2-astra";

338const lookupTicket: OpenAI.Responses.FunctionTool = {338const lookupTicket: OpenAI.Responses.FunctionTool = {

339 type: "function",339 type: "function",

340 name: "lookup_ticket",340 name: "lookup_ticket",


393from openai import OpenAI393from openai import OpenAI

394 394 

395client = OpenAI()395client = OpenAI()

396model = "gpt-6-astra"396model = "gpt-6.2-astra"

397lookup_ticket = {397lookup_ticket = {

398 "type": "function",398 "type": "function",

399 "name": "lookup_ticket",399 "name": "lookup_ticket",


462func main() {462func main() {

463 client := openai.NewClient()463 client := openai.NewClient()

464 ctx := context.Background()464 ctx := context.Background()

465 model := shared.ResponsesModel("gpt-6-astra")465 model := shared.ResponsesModel("gpt-6.2-astra")

466 lookupTicket := responses.ToolUnionParam{OfFunction: &responses.FunctionToolParam{466 lookupTicket := responses.ToolUnionParam{OfFunction: &responses.FunctionToolParam{

467 Name: "lookup_ticket", Description: openai.String("Look up a ticket by ID."),467 Name: "lookup_ticket", Description: openai.String("Look up a ticket by ID."),

468 Parameters: map[string]any{468 Parameters: map[string]any{


539import java.util.List;539import java.util.List;

540import java.util.Map;540import java.util.Map;

541 541 

542String model = "gpt-6-astra";542String model = "gpt-6.2-astra";

543var tool =543var tool =

544 FunctionTool.builder()544 FunctionTool.builder()

545 .name("lookup_ticket")545 .name("lookup_ticket")


642require "openai"642require "openai"

643 643 

644client = OpenAI::Client.new644client = OpenAI::Client.new

645model = "gpt-6-astra"645model = "gpt-6.2-astra"

646lookup_ticket = {646lookup_ticket = {

647 type: :function,647 type: :function,

648 648 

Details

263});263});

264```264```

265 265 

266```go

267sessionConfig := map[string]any{

268 "session": map[string]any{

269 "type": "realtime",

270 "model": "gpt-realtime-2.1-mini",

271 "instructions": "Read the user's text aloud without adding commentary.",

272 "output_modalities": []string{"audio"},

273 "audio": map[string]any{"output": map[string]any{"voice": map[string]any{"id": "voice_123abc"}}},

274 },

275}

276```

277 

266```ruby278```ruby

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

268require "json"280require "json"

Details

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

61 61 

62```python62```python

63from openai import OpenAI63import os

64 64 

65from openai import OpenAI, omit

66 

67eu_api_key = os.environ["OPENAI_EU_API_KEY"]

65client = OpenAI()68client = OpenAI()

66 69 

67# No processing constraint.70# No processing constraint.


80)83)

81print(response.output_text)84print(response.output_text)

82 85 

83# EU processing and storage.86# EU processing and storage require a key from an EU project.

84response = client.with_options(87response = client.with_options(

85 base_url="https://eu.api.openai.com/v1",88 base_url="https://eu.api.openai.com/v1",

89 api_key=eu_api_key,

86).responses.create(90).responses.create(

87 model="gpt-6.1-terra",91 model="gpt-6.1-terra",

88 input="Reply with OK.",92 input="Reply with OK.",

93 extra_headers={"OpenAI-Project": omit, "OpenAI-Organization": omit},

89)94)

90print(response.output_text)95print(response.output_text)

91```96```

92 97 

98```go

99package main

100 

101import (

102 "context"

103 "fmt"

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

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

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

107 "os"

108)

109 

110func main() {

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

112 euKey := os.Getenv("OPENAI_EU_API_KEY")

113 if euKey == "" {

114 panic("Set OPENAI_EU_API_KEY to an EU-project credential")

115 }

116 client := openai.NewClient()

117 ctx := context.Background()

118 params := responses.ResponseNewParams{Model: "gpt-6.1-terra", Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Reply with OK.")}}

119 response, err := client.Responses.New(ctx, params)

120 if err != nil {

121 panic(err)

122 }

123 fmt.Println(response.OutputText())

124 response, err = client.Responses.New(ctx, params, option.WithDataResidency(option.DataResidencyUS))

125 if err != nil {

126 panic(err)

127 }

128 fmt.Println(response.OutputText())

129 response, err = client.Responses.New(ctx, params,

130 option.WithDataResidency(option.DataResidencyEU), option.WithAPIKey(euKey),

131 option.WithHeaderDel("OpenAI-Organization"), option.WithHeaderDel("OpenAI-Project"),

132 )

133 if err != nil {

134 panic(err)

135 }

136 fmt.Println(response.OutputText())

137}

138```

139 

93```ruby140```ruby

94require "openai"141require "openai"

95 142 

guides/daybreak.md +64 −13

Details

4 4 

5Set `access_programs.cyber` in a Responses API request to select [Daybreak Blue or Daybreak Red](https://help.openai.com/en/articles/20001258-trusted-access-for-cyber). Other [API cybersecurity safeguards](https://developers.openai.com/api/docs/guides/safety-checks/cybersecurity) still apply.5Set `access_programs.cyber` in a Responses API request to select [Daybreak Blue or Daybreak Red](https://help.openai.com/en/articles/20001258-trusted-access-for-cyber). Other [API cybersecurity safeguards](https://developers.openai.com/api/docs/guides/safety-checks/cybersecurity) still apply.

6 6 

7Before sending a request, complete [organization approval and project setup](https://help.openai.com/en/articles/20001261-enterprise-daybreak-onboarding). Use an API key from a project with access to both the program and the model. The parameter doesn't grant access.7After OpenAI approves your API organization for Daybreak, ask an API organization owner to enable the approved access level in a named (non-default) project. Default projects cannot enable Daybreak. Follow the [API project setup instructions](https://help.openai.com/en/articles/20001531-openai-daybreak-set-up-access-for-your-team#set-up-api-project-access).

8 

9Use an API key from that project for your requests.

10 

11You can also [use Daybreak in the Agents API](https://developers.openai.com/api/docs/guides/agents-api/configuration#use-daybreak-in-a-session). Set `access_programs.cyber` when you create or update a session, not on individual messages. The request and response examples below use the Responses API.

8 12 

9All Daybreak Red organizations must [require SSO](https://help.openai.com/en/articles/9534785-single-sign-on-sso-setup-for-openai-products) for the API organization that holds Cyber access and enforce MFA through your identity provider. If you use a separate Cyber organization, verify its domain and test SSO there.13All Daybreak Red organizations must [require SSO](https://help.openai.com/en/articles/9534785-single-sign-on-sso-setup-for-openai-products) for the API organization that holds Cyber access and enforce MFA through your identity provider. If you use a separate Cyber organization, verify its domain and test SSO there.

10 14 


40 `daybreak_blue`44 `daybreak_blue`

41 </td>45 </td>

42 </tr>46 </tr>

47 <tr>

48 <td>GPT-6 Luna</td>

49 <td>Blue or Red</td>

50 <td>

51 `daybreak_blue`

52 </td>

53 </tr>

43 <tr>54 <tr>

44 <td className="align-top">55 <td className="align-top">

45 56

46 57 

47 58

48GPT-6.1 Sol59GPT-6.2 Astra

49 60 

50 61

51GPT-6 Astra62GPT-6.2 Sol

52 63 

53 64

54GPT-5.5-Cyber (existing access only)65GPT-6.1 Sol

55 66 

56 67

57GPT-5.6 Cyber68GPT-6.1 Terra

69 

70

71GPT-6 Astra

58 72 

59 73

60 74 


75 89 

76 90

77 91 

78 `daybreak_red`92 `daybreak_blue`

79 93

80 94 

81 95

82 96 

83 `daybreak_red`97 `daybreak_blue`

98

99 

100

101 

102 `daybreak_blue`

84 103

85 104 

86 105


92 <td>Red + additional model approval</td>111 <td>Red + additional model approval</td>

93 <td>112 <td>

94 `daybreak_red`113 `daybreak_red`

114 </td>

115 </tr>

116 <tr>

117 <td className="align-top">

118

119 

120

121GPT-5.6 Cyber

122 

123

124GPT-5.5-Cyber (existing access only)

125 

126

127 

128 </td>

129 <td className="align-top">Red</td>

130 <td className="align-top">

131

132 

133

134 

135 `daybreak_red`

136

137 

138

139 

140 `daybreak_red`

141

142 

143

144 

95 </td>145 </td>

96 </tr>146 </tr>

97 </tbody>147 </tbody>


101 151 

102Use the value listed for the model even if your organization has a higher approval level. For example, `gpt-6-sol` accepts `daybreak_blue`, but returns `invalid_access_program` for `daybreak_red`.152Use the value listed for the model even if your organization has a higher approval level. For example, `gpt-6-sol` accepts `daybreak_blue`, but returns `invalid_access_program` for `daybreak_red`.

103 153 

104For reduced refusals on `gpt-6-astra` and `gpt-6.1-sol`, your organization154For reduced refusals on `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6.1-sol`,

105 needs Daybreak Red approval and your project needs the required access155 `gpt-6.1-terra`, and `gpt-6-astra`, your organization needs Daybreak Red

106 enabled. Send `daybreak_blue`. Both models reject `daybreak_red`, and Blue156 approval and your project needs the required access enabled. Send

107 approval alone isn't sufficient.157 `daybreak_blue`. Blue approval alone isn't sufficient. `gpt-6-astra` and

158 `gpt-6.1-sol` reject `daybreak_red`.

108 159 

109## Send a request160## Send a request

110 161 


144 195 

145## Understand defaults when omitted196## Understand defaults when omitted

146 197 

147Starting with `gpt-6.1-terra`, requests that omit `access_programs.cyber` default to `standard` instead of the highest available Daybreak tier.198For `gpt-6.1-terra` and newer models, including `gpt-6.2-astra` and `gpt-6.2-sol`, requests that omit `access_programs.cyber` default to `standard` instead of the highest available Daybreak tier.

148 199 

149These models use the following defaults when you omit the parameter:200These models use the following defaults when you omit the parameter:

150 201 

151- **Mainline models such as `gpt-6-sol`:** Daybreak Blue treatment when your organization and project have the required access; otherwise, standard safeguards.202- **Mainline models such as `gpt-6-sol` and `gpt-6-luna`:** Daybreak Blue treatment when your organization and project have the required access; otherwise, standard safeguards.

152- **Red models such as `gpt-5.6-cyber`:** The API selects `daybreak_red`. The request fails if the required access is missing.203- **Red models such as `gpt-5.6-cyber`:** The API selects `daybreak_red`. The request fails if the required access is missing.

153- **`gpt-6-astra` and `gpt-6.1-sol`:** Reduced refusals for eligible callers with Daybreak Red access enabled for their project; otherwise, standard safeguards.204- **`gpt-6-astra` and `gpt-6.1-sol`:** Reduced refusals for eligible callers with Daybreak Red access enabled for their project; otherwise, standard safeguards.

154 205 

Details

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

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

1851 1851 

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

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

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

1855 1855 

Details

196 196 

197 197 

198 198 

199 

200 

201 

202For Go, save the review CSV as `data/fine_food_reviews_1k.csv`. Keep the `Summary`, `Text`, `Score`, `UserId`, and `ProductId` columns. The program preserves the input columns and adds `combined` and `ada_embedding` for the analysis steps.

203 

204 

205 

206 

199Create review embeddings207Create review embeddings

200 208 

201```typescript209```typescript


250 "fmt"258 "fmt"

251 "log"259 "log"

252 "os"260 "os"

261 "slices"

253 "strings"262 "strings"

254 263 

255 "github.com/openai/openai-go/v3"264 "github.com/openai/openai-go/v3"


264func run() error {273func run() error {

265 client := openai.NewClient()274 client := openai.NewClient()

266 ctx := context.Background()275 ctx := context.Background()

267 reviews := []string{"A rich cup of coffee.", "A bright herbal tea."}276 input, err := os.Open("data/fine_food_reviews_1k.csv")

277 if err != nil {

278 return err

279 }

280 defer input.Close()

281 rows, err := csv.NewReader(input).ReadAll()

282 if err != nil {

283 return err

284 }

285 if len(rows) < 2 {

286 return fmt.Errorf("review CSV needs a header and at least one review")

287 }

288 headers := rows[0]

289 for _, name := range []string{"Summary", "Text", "Score", "UserId", "ProductId"} {

290 if !slices.Contains(headers, name) {

291 return fmt.Errorf("missing %s column", name)

292 }

293 }

294 summaryColumn, textColumn := slices.Index(headers, "Summary"), slices.Index(headers, "Text")

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

269 return err296 return err

270 }297 }


274 }301 }

275 defer file.Close()302 defer file.Close()

276 writer := csv.NewWriter(file)303 writer := csv.NewWriter(file)

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

278 return err305 return err

279 }306 }

280 for _, review := range reviews {307 for _, row := range rows[1:] {

281 vector, err := embedding(ctx, &client, strings.ReplaceAll(review, "\n", " "))308 combined := strings.ReplaceAll(row[summaryColumn]+" "+row[textColumn], "\n", " ")

309 vector, err := embedding(ctx, &client, combined)

282 if err != nil {310 if err != nil {

283 return err311 return err

284 }312 }


286 if err != nil {314 if err != nil {

287 return err315 return err

288 }316 }

289 if err := writer.Write([]string{review, string(encoded)}); err != nil {317 if err := writer.Write(append(append([]string{}, row...), combined, string(encoded))); err != nil {

290 return err318 return err

291 }319 }

292 }320 }


406 434 

407 435 

408 436 

437Each Go example is a complete program that reads `output/embedded_1k_reviews.csv`. Run each program separately from your Go module. The file needs JSON arrays in `ada_embedding` and integer values in `Score`; grouped averages also need `UserId` and `ProductId`. The split uses a fixed seed, while forest predictions and t-SNE coordinates can vary between runs. The metrics below describe the linked Python notebooks, not these Go programs.

438 

439 

440 

441 

442 

443 

444 

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

410 446 

411 447 


423df["ada_embedding"] = df.ada_embedding.apply(literal_eval).apply(np.array)459df["ada_embedding"] = df.ada_embedding.apply(literal_eval).apply(np.array)

424```460```

425 461 

462```go

463package main

464 

465import (

466 "encoding/csv"

467 "encoding/json"

468 "fmt"

469 "io"

470 "log"

471 "os"

472 "strconv"

473)

474 

475type review struct {

476 Vector []float64

477 Score int

478 UserID, ProductID string

479}

480 

481func loadReviews(path string) ([]review, error) {

482 file, err := os.Open(path)

483 if err != nil {

484 return nil, err

485 }

486 defer file.Close()

487 reader := csv.NewReader(file)

488 header, err := reader.Read()

489 if err != nil {

490 return nil, err

491 }

492 columns := map[string]int{}

493 for i, name := range header {

494 columns[name] = i

495 }

496 for _, name := range []string{"ada_embedding", "Score"} {

497 if _, ok := columns[name]; !ok {

498 return nil, fmt.Errorf("missing %s column", name)

499 }

500 }

501 rows := []review{}

502 dimensions := 0

503 for {

504 record, err := reader.Read()

505 if err == io.EOF {

506 break

507 }

508 if err != nil {

509 return nil, err

510 }

511 var value review

512 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

513 return nil, err

514 }

515 if len(value.Vector) == 0 {

516 return nil, fmt.Errorf("empty embedding")

517 }

518 if dimensions == 0 {

519 dimensions = len(value.Vector)

520 }

521 if len(value.Vector) != dimensions {

522 return nil, fmt.Errorf("inconsistent embedding dimensions")

523 }

524 value.Score, err = strconv.Atoi(record[columns["Score"]])

525 if err != nil {

526 return nil, err

527 }

528 if column, ok := columns["UserId"]; ok {

529 value.UserID = record[column]

530 }

531 if column, ok := columns["ProductId"]; ok {

532 value.ProductID = record[column]

533 }

534 rows = append(rows, value)

535 }

536 if len(rows) == 0 {

537 return nil, fmt.Errorf("no reviews")

538 }

539 return rows, nil

540}

541 

542func main() {

543 rows, err := loadReviews("output/embedded_1k_reviews.csv")

544 if err != nil {

545 log.Fatal(err)

546 }

547 result := map[string]any{"rows": len(rows), "first": rows[0].Vector, "last": rows[len(rows)-1].Vector}

548 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

549 log.Fatal(err)

550 }

551}

552```

553 

426```ruby554```ruby

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

428require "csv"556require "csv"


498print(norm_dim)626print(norm_dim)

499```627```

500 628 

629```go

630response, err := client.Embeddings.New(context.Background(), openai.EmbeddingNewParams{

631 Model: openai.EmbeddingModelTextEmbedding3Small,

632 Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String("Testing 123")},

633 EncodingFormat: openai.EmbeddingNewParamsEncodingFormatFloat,

634})

635if err != nil {

636 panic(err)

637}

638if len(response.Data) != 1 || len(response.Data[0].Embedding) < 256 {

639 panic("expected an embedding with at least 256 dimensions")

640}

641shortened := append([]float64(nil), response.Data[0].Embedding[:256]...)

642magnitude := 0.0

643for _, value := range shortened {

644 magnitude += value * value

645}

646magnitude = math.Sqrt(magnitude)

647if magnitude != 0 {

648 for i := range shortened {

649 shortened[i] /= magnitude

650 }

651}

652```

653 

501```java654```java

502import com.openai.client.OpenAIClient;655import com.openai.client.OpenAIClient;

503import com.openai.client.okhttp.OpenAIOkHttpClient;656import com.openai.client.okhttp.OpenAIOkHttpClient;


1578 1731 

1579The visualization seems to have produced roughly 3 clusters, one of which has mostly negative reviews.1732The visualization seems to have produced roughly 3 clusters, one of which has mostly negative reviews.

1580 1733 

1734 

1735 

1736 

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

1738 

1739 

1740 

1741 

1581Visualize embeddings with t-SNE1742Visualize embeddings with t-SNE

1582 1743 

1583```python1744```python


1607plt.title("Amazon ratings visualized in language using t-SNE")1768plt.title("Amazon ratings visualized in language using t-SNE")

1608```1769```

1609 1770 

1771```go

1772package main

1773 

1774import (

1775 "encoding/csv"

1776 "encoding/json"

1777 "fmt"

1778 "github.com/danaugrs/go-tsne/tsne"

1779 "gonum.org/v1/gonum/mat"

1780 "gonum.org/v1/plot"

1781 "gonum.org/v1/plot/plotter"

1782 "gonum.org/v1/plot/vg"

1783 "gonum.org/v1/plot/vg/draw"

1784 "image/color"

1785 "io"

1786 "log"

1787 "math"

1788 "os"

1789 "strconv"

1790)

1791 

1792type review struct {

1793 Vector []float64

1794 Score int

1795 UserID, ProductID string

1796}

1797 

1798func loadReviews(path string) ([]review, error) {

1799 file, err := os.Open(path)

1800 if err != nil {

1801 return nil, err

1802 }

1803 defer file.Close()

1804 reader := csv.NewReader(file)

1805 header, err := reader.Read()

1806 if err != nil {

1807 return nil, err

1808 }

1809 columns := map[string]int{}

1810 for i, name := range header {

1811 columns[name] = i

1812 }

1813 for _, name := range []string{"ada_embedding", "Score"} {

1814 if _, ok := columns[name]; !ok {

1815 return nil, fmt.Errorf("missing %s column", name)

1816 }

1817 }

1818 rows := []review{}

1819 dimensions := 0

1820 for {

1821 record, err := reader.Read()

1822 if err == io.EOF {

1823 break

1824 }

1825 if err != nil {

1826 return nil, err

1827 }

1828 var value review

1829 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

1830 return nil, err

1831 }

1832 if len(value.Vector) == 0 {

1833 return nil, fmt.Errorf("empty embedding")

1834 }

1835 if dimensions == 0 {

1836 dimensions = len(value.Vector)

1837 }

1838 if len(value.Vector) != dimensions {

1839 return nil, fmt.Errorf("inconsistent embedding dimensions")

1840 }

1841 value.Score, err = strconv.Atoi(record[columns["Score"]])

1842 if err != nil {

1843 return nil, err

1844 }

1845 if column, ok := columns["UserId"]; ok {

1846 value.UserID = record[column]

1847 }

1848 if column, ok := columns["ProductId"]; ok {

1849 value.ProductID = record[column]

1850 }

1851 rows = append(rows, value)

1852 }

1853 if len(rows) == 0 {

1854 return nil, fmt.Errorf("no reviews")

1855 }

1856 return rows, nil

1857}

1858 

1859func main() {

1860 rows, err := loadReviews("output/embedded_1k_reviews.csv")

1861 if err != nil {

1862 log.Fatal(err)

1863 }

1864 if len(rows) < 3 {

1865 log.Fatal("need at least three reviews")

1866 }

1867 values := []float64{}

1868 for _, row := range rows {

1869 values = append(values, row.Vector...)

1870 }

1871 matrix := mat.NewDense(len(rows), len(rows[0].Vector), values)

1872 perplexity := math.Min(15, float64(len(rows)-1))

1873 embedded := tsne.NewTSNE(2, perplexity, 200, 1000, false).EmbedData(matrix, nil)

1874 points := make(plotter.XYs, len(rows))

1875 coordinates := make([][]float64, len(rows))

1876 colors := make([]int, len(rows))

1877 for i, row := range rows {

1878 x, y := embedded.At(i, 0), embedded.At(i, 1)

1879 if math.IsNaN(x) || math.IsNaN(y) || math.IsInf(x, 0) || math.IsInf(y, 0) {

1880 log.Fatal("non-finite t-SNE output")

1881 }

1882 if row.Score < 1 || row.Score > 5 {

1883 log.Fatal("review scores must be between 1 and 5")

1884 }

1885 points[i] = plotter.XY{X: x, Y: y}

1886 coordinates[i] = []float64{x, y}

1887 colors[i] = row.Score - 1

1888 }

1889 chart := plot.New()

1890 chart.Title.Text = "Review embeddings"

1891 chart.X.Label.Text = "t-SNE 1"

1892 chart.Y.Label.Text = "t-SNE 2"

1893 scatter, err := plotter.NewScatter(points)

1894 if err != nil {

1895 log.Fatal(err)

1896 }

1897 palette := []color.RGBA{{255, 0, 0, 255}, {255, 140, 0, 255}, {255, 215, 0, 255}, {64, 224, 208, 255}, {0, 100, 0, 255}}

1898 scatter.GlyphStyleFunc = func(i int) draw.GlyphStyle {

1899 return draw.GlyphStyle{Color: palette[colors[i]], Radius: vg.Points(3), Shape: draw.CircleGlyph{}}

1900 }

1901 chart.Add(scatter)

1902 if err := chart.Save(6*vg.Inch, 4*vg.Inch, "local-plot.png"); err != nil {

1903 log.Fatal(err)

1904 }

1905 plotted := make([][]float64, len(points))

1906 for i := range points {

1907 x, y := scatter.XY(i)

1908 plotted[i] = []float64{x, y}

1909 }

1910 result := map[string]any{"points": coordinates, "plotted": plotted, "colors": colors}

1911 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

1912 log.Fatal(err)

1913 }

1914}

1915```

1916 

1610```ruby1917```ruby

1611require "csv"1918require "csv"

1612require "json"1919require "json"


1670)1977)

1671```1978```

1672 1979 

1980```go

1981package main

1982 

1983import (

1984 "encoding/csv"

1985 "encoding/json"

1986 "fmt"

1987 "io"

1988 "log"

1989 "math/rand"

1990 "os"

1991 "strconv"

1992)

1993 

1994type review struct {

1995 Vector []float64

1996 Score int

1997 UserID, ProductID string

1998}

1999 

2000func loadReviews(path string) ([]review, error) {

2001 file, err := os.Open(path)

2002 if err != nil {

2003 return nil, err

2004 }

2005 defer file.Close()

2006 reader := csv.NewReader(file)

2007 header, err := reader.Read()

2008 if err != nil {

2009 return nil, err

2010 }

2011 columns := map[string]int{}

2012 for i, name := range header {

2013 columns[name] = i

2014 }

2015 for _, name := range []string{"ada_embedding", "Score"} {

2016 if _, ok := columns[name]; !ok {

2017 return nil, fmt.Errorf("missing %s column", name)

2018 }

2019 }

2020 rows := []review{}

2021 dimensions := 0

2022 for {

2023 record, err := reader.Read()

2024 if err == io.EOF {

2025 break

2026 }

2027 if err != nil {

2028 return nil, err

2029 }

2030 var value review

2031 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

2032 return nil, err

2033 }

2034 if len(value.Vector) == 0 {

2035 return nil, fmt.Errorf("empty embedding")

2036 }

2037 if dimensions == 0 {

2038 dimensions = len(value.Vector)

2039 }

2040 if len(value.Vector) != dimensions {

2041 return nil, fmt.Errorf("inconsistent embedding dimensions")

2042 }

2043 value.Score, err = strconv.Atoi(record[columns["Score"]])

2044 if err != nil {

2045 return nil, err

2046 }

2047 if column, ok := columns["UserId"]; ok {

2048 value.UserID = record[column]

2049 }

2050 if column, ok := columns["ProductId"]; ok {

2051 value.ProductID = record[column]

2052 }

2053 rows = append(rows, value)

2054 }

2055 if len(rows) == 0 {

2056 return nil, fmt.Errorf("no reviews")

2057 }

2058 return rows, nil

2059}

2060 

2061func main() {

2062 rows, err := loadReviews("output/embedded_1k_reviews.csv")

2063 if err != nil {

2064 log.Fatal(err)

2065 }

2066 if len(rows) < 2 {

2067 log.Fatal("need at least two reviews")

2068 }

2069 indices := rand.New(rand.NewSource(42)).Perm(len(rows))

2070 testSize := (len(rows) + 4) / 5

2071 trainVectors, testVectors := [][]float64{}, [][]float64{}

2072 trainScores, testScores := []int{}, []int{}

2073 for i, index := range indices {

2074 row := rows[index]

2075 if i < testSize {

2076 testVectors = append(testVectors, row.Vector)

2077 testScores = append(testScores, row.Score)

2078 } else {

2079 trainVectors = append(trainVectors, row.Vector)

2080 trainScores = append(trainScores, row.Score)

2081 }

2082 }

2083 result := map[string]any{"train": trainScores, "test": testScores, "train_vectors": trainVectors, "test_vectors": testVectors}

2084 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

2085 log.Fatal(err)

2086 }

2087}

2088```

2089 

1673```ruby2090```ruby

1674vectors = rows.map { |row| row.fetch("ada_embedding") }2091vectors = rows.map { |row| row.fetch("ada_embedding") }

1675scores = rows.map { |row| Integer(row.fetch("Score")) }2092scores = rows.map { |row| Integer(row.fetch("Score")) }


1691 2108 

1692We assume the score is a continuous variable between 1 and 5, and allow the algorithm to predict any floating point value. The ML algorithm minimizes the distance of the predicted value to the true score, and achieves a mean absolute error of 0.39, which means that on average the prediction is off by less than half a star.2109We assume the score is a continuous variable between 1 and 5, and allow the algorithm to predict any floating point value. The ML algorithm minimizes the distance of the predicted value to the true score, and achieves a mean absolute error of 0.39, which means that on average the prediction is off by less than half a star.

1693 2110 

2111 

2112 

2113 

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

2115 

2116 

2117 

2118 

1694Predict review scores2119Predict review scores

1695 2120 

1696```python2121```python


1701preds = rfr.predict(X_test)2126preds = rfr.predict(X_test)

1702```2127```

1703 2128 

2129```go

2130package main

2131 

2132import (

2133 "encoding/csv"

2134 "encoding/json"

2135 "fmt"

2136 "github.com/wlattner/rf/forest"

2137 "io"

2138 "log"

2139 "math/rand"

2140 "os"

2141 "strconv"

2142)

2143 

2144type review struct {

2145 Vector []float64

2146 Score int

2147 UserID, ProductID string

2148}

2149 

2150func loadReviews(path string) ([]review, error) {

2151 file, err := os.Open(path)

2152 if err != nil {

2153 return nil, err

2154 }

2155 defer file.Close()

2156 reader := csv.NewReader(file)

2157 header, err := reader.Read()

2158 if err != nil {

2159 return nil, err

2160 }

2161 columns := map[string]int{}

2162 for i, name := range header {

2163 columns[name] = i

2164 }

2165 for _, name := range []string{"ada_embedding", "Score"} {

2166 if _, ok := columns[name]; !ok {

2167 return nil, fmt.Errorf("missing %s column", name)

2168 }

2169 }

2170 rows := []review{}

2171 dimensions := 0

2172 for {

2173 record, err := reader.Read()

2174 if err == io.EOF {

2175 break

2176 }

2177 if err != nil {

2178 return nil, err

2179 }

2180 var value review

2181 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

2182 return nil, err

2183 }

2184 if len(value.Vector) == 0 {

2185 return nil, fmt.Errorf("empty embedding")

2186 }

2187 if dimensions == 0 {

2188 dimensions = len(value.Vector)

2189 }

2190 if len(value.Vector) != dimensions {

2191 return nil, fmt.Errorf("inconsistent embedding dimensions")

2192 }

2193 value.Score, err = strconv.Atoi(record[columns["Score"]])

2194 if err != nil {

2195 return nil, err

2196 }

2197 if column, ok := columns["UserId"]; ok {

2198 value.UserID = record[column]

2199 }

2200 if column, ok := columns["ProductId"]; ok {

2201 value.ProductID = record[column]

2202 }

2203 rows = append(rows, value)

2204 }

2205 if len(rows) == 0 {

2206 return nil, fmt.Errorf("no reviews")

2207 }

2208 return rows, nil

2209}

2210 

2211func main() {

2212 rows, err := loadReviews("output/embedded_1k_reviews.csv")

2213 if err != nil {

2214 log.Fatal(err)

2215 }

2216 if len(rows) < 2 {

2217 log.Fatal("need at least two reviews")

2218 }

2219 indices := rand.New(rand.NewSource(42)).Perm(len(rows))

2220 testSize := (len(rows) + 4) / 5

2221 trainVectors, testVectors := [][]float64{}, [][]float64{}

2222 trainScores, testScores := []int{}, []int{}

2223 for i, index := range indices {

2224 row := rows[index]

2225 if i < testSize {

2226 testVectors = append(testVectors, row.Vector)

2227 testScores = append(testScores, row.Score)

2228 } else {

2229 trainVectors = append(trainVectors, row.Vector)

2230 trainScores = append(trainScores, row.Score)

2231 }

2232 }

2233 targets := make([]float64, len(trainScores))

2234 for i, score := range trainScores {

2235 targets[i] = float64(score)

2236 }

2237 model := forest.NewRegressor(forest.NumTrees(100), forest.NumWorkers(1))

2238 model.Fit(trainVectors, targets)

2239 predictions := model.Predict(testVectors)

2240 result := map[string]any{"train": trainScores, "test": testScores, "train_vectors": trainVectors, "test_vectors": testVectors, "predictions": predictions, "trees": len(model.Trees), "features": len(trainVectors[0])}

2241 

2242 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

2243 log.Fatal(err)

2244 }

2245}

2246```

2247 

1704```ruby2248```ruby

1705require "rumale/ensemble"2249require "rumale/ensemble"

1706 2250 


1736 2280 

1737After the training, the model learns to predict 1 and 5-star reviews much better than the more nuanced reviews (2-4 stars), likely due to more extreme sentiment expression.2281After the training, the model learns to predict 1 and 5-star reviews much better than the more nuanced reviews (2-4 stars), likely due to more extreme sentiment expression.

1738 2282 

2283 

2284 

2285 

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

2287 

2288 

2289 

2290 

1739Classify review scores2291Classify review scores

1740 2292 

1741```python2293```python


1747preds = clf.predict(X_test)2299preds = clf.predict(X_test)

1748```2300```

1749 2301 

2302```go

2303package main

2304 

2305import (

2306 "encoding/csv"

2307 "encoding/json"

2308 "fmt"

2309 "github.com/wlattner/rf/forest"

2310 "io"

2311 "log"

2312 "math/rand"

2313 "os"

2314 "slices"

2315 "strconv"

2316)

2317 

2318type review struct {

2319 Vector []float64

2320 Score int

2321 UserID, ProductID string

2322}

2323 

2324func loadReviews(path string) ([]review, error) {

2325 file, err := os.Open(path)

2326 if err != nil {

2327 return nil, err

2328 }

2329 defer file.Close()

2330 reader := csv.NewReader(file)

2331 header, err := reader.Read()

2332 if err != nil {

2333 return nil, err

2334 }

2335 columns := map[string]int{}

2336 for i, name := range header {

2337 columns[name] = i

2338 }

2339 for _, name := range []string{"ada_embedding", "Score"} {

2340 if _, ok := columns[name]; !ok {

2341 return nil, fmt.Errorf("missing %s column", name)

2342 }

2343 }

2344 rows := []review{}

2345 dimensions := 0

2346 for {

2347 record, err := reader.Read()

2348 if err == io.EOF {

2349 break

2350 }

2351 if err != nil {

2352 return nil, err

2353 }

2354 var value review

2355 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

2356 return nil, err

2357 }

2358 if len(value.Vector) == 0 {

2359 return nil, fmt.Errorf("empty embedding")

2360 }

2361 if dimensions == 0 {

2362 dimensions = len(value.Vector)

2363 }

2364 if len(value.Vector) != dimensions {

2365 return nil, fmt.Errorf("inconsistent embedding dimensions")

2366 }

2367 value.Score, err = strconv.Atoi(record[columns["Score"]])

2368 if err != nil {

2369 return nil, err

2370 }

2371 if column, ok := columns["UserId"]; ok {

2372 value.UserID = record[column]

2373 }

2374 if column, ok := columns["ProductId"]; ok {

2375 value.ProductID = record[column]

2376 }

2377 rows = append(rows, value)

2378 }

2379 if len(rows) == 0 {

2380 return nil, fmt.Errorf("no reviews")

2381 }

2382 return rows, nil

2383}

2384 

2385func main() {

2386 rows, err := loadReviews("output/embedded_1k_reviews.csv")

2387 if err != nil {

2388 log.Fatal(err)

2389 }

2390 if len(rows) < 2 {

2391 log.Fatal("need at least two reviews")

2392 }

2393 indices := rand.New(rand.NewSource(42)).Perm(len(rows))

2394 testSize := (len(rows) + 4) / 5

2395 trainVectors, testVectors := [][]float64{}, [][]float64{}

2396 trainScores, testScores := []int{}, []int{}

2397 for i, index := range indices {

2398 row := rows[index]

2399 if i < testSize {

2400 testVectors = append(testVectors, row.Vector)

2401 testScores = append(testScores, row.Score)

2402 } else {

2403 trainVectors = append(trainVectors, row.Vector)

2404 trainScores = append(trainScores, row.Score)

2405 }

2406 }

2407 labels := make([]string, len(trainScores))

2408 for i, score := range trainScores {

2409 labels[i] = strconv.Itoa(score)

2410 }

2411 model := forest.NewClassifier(forest.NumTrees(100), forest.NumWorkers(1))

2412 model.Fit(trainVectors, labels)

2413 predictedClasses := model.Predict(testVectors)

2414 predictions := make([]int, len(predictedClasses))

2415 for i, class := range predictedClasses {

2416 value, err := strconv.Atoi(model.Classes[class])

2417 if err != nil {

2418 log.Fatal(err)

2419 }

2420 predictions[i] = value

2421 }

2422 classes := make([]int, len(model.Classes))

2423 for i, class := range model.Classes {

2424 value, err := strconv.Atoi(class)

2425 if err != nil {

2426 log.Fatal(err)

2427 }

2428 classes[i] = value

2429 }

2430 slices.Sort(classes)

2431 result := map[string]any{"train": trainScores, "test": testScores, "train_vectors": trainVectors, "test_vectors": testVectors, "predictions": predictions, "trees": len(model.Trees), "features": len(trainVectors[0]), "classes": classes}

2432 

2433 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

2434 log.Fatal(err)

2435 }

2436}

2437```

2438 

1750```ruby2439```ruby

1751require "rumale/ensemble"2440require "rumale/ensemble"

1752 2441 


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

1999```2688```

2000 2689 

2690```go

2691package main

2692 

2693import (

2694 "encoding/csv"

2695 "encoding/json"

2696 "fmt"

2697 "io"

2698 "log"

2699 "os"

2700 "strconv"

2701)

2702 

2703type review struct {

2704 Vector []float64

2705 Score int

2706 UserID, ProductID string

2707}

2708 

2709func loadReviews(path string) ([]review, error) {

2710 file, err := os.Open(path)

2711 if err != nil {

2712 return nil, err

2713 }

2714 defer file.Close()

2715 reader := csv.NewReader(file)

2716 header, err := reader.Read()

2717 if err != nil {

2718 return nil, err

2719 }

2720 columns := map[string]int{}

2721 for i, name := range header {

2722 columns[name] = i

2723 }

2724 for _, name := range []string{"ada_embedding", "Score"} {

2725 if _, ok := columns[name]; !ok {

2726 return nil, fmt.Errorf("missing %s column", name)

2727 }

2728 }

2729 rows := []review{}

2730 dimensions := 0

2731 for {

2732 record, err := reader.Read()

2733 if err == io.EOF {

2734 break

2735 }

2736 if err != nil {

2737 return nil, err

2738 }

2739 var value review

2740 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

2741 return nil, err

2742 }

2743 if len(value.Vector) == 0 {

2744 return nil, fmt.Errorf("empty embedding")

2745 }

2746 if dimensions == 0 {

2747 dimensions = len(value.Vector)

2748 }

2749 if len(value.Vector) != dimensions {

2750 return nil, fmt.Errorf("inconsistent embedding dimensions")

2751 }

2752 value.Score, err = strconv.Atoi(record[columns["Score"]])

2753 if err != nil {

2754 return nil, err

2755 }

2756 if column, ok := columns["UserId"]; ok {

2757 value.UserID = record[column]

2758 }

2759 if column, ok := columns["ProductId"]; ok {

2760 value.ProductID = record[column]

2761 }

2762 rows = append(rows, value)

2763 }

2764 if len(rows) == 0 {

2765 return nil, fmt.Errorf("no reviews")

2766 }

2767 return rows, nil

2768}

2769 

2770func averageEmbeddings(rows []review, id func(review) string) (map[string][]float64, error) {

2771 sums := map[string][]float64{}

2772 counts := map[string]int{}

2773 for _, row := range rows {

2774 key := id(row)

2775 if key == "" {

2776 return nil, fmt.Errorf("missing user or product ID")

2777 }

2778 if sums[key] == nil {

2779 sums[key] = make([]float64, len(row.Vector))

2780 }

2781 for i, value := range row.Vector {

2782 sums[key][i] += value

2783 }

2784 counts[key]++

2785 }

2786 for key, vector := range sums {

2787 for i := range vector {

2788 vector[i] /= float64(counts[key])

2789 }

2790 }

2791 return sums, nil

2792}

2793 

2794func main() {

2795 rows, err := loadReviews("output/embedded_1k_reviews.csv")

2796 if err != nil {

2797 log.Fatal(err)

2798 }

2799 users, err := averageEmbeddings(rows, func(row review) string { return row.UserID })

2800 if err != nil {

2801 log.Fatal(err)

2802 }

2803 products, err := averageEmbeddings(rows, func(row review) string { return row.ProductID })

2804 if err != nil {

2805 log.Fatal(err)

2806 }

2807 result := map[string]any{"users": users, "products": products}

2808 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

2809 log.Fatal(err)

2810 }

2811}

2812```

2813 

2001```ruby2814```ruby

2002vectors = rows.map { |row| row.fetch("ada_embedding") }2815vectors = rows.map { |row| row.fetch("ada_embedding") }

2003user_ids = rows.map { |row| row.fetch("UserId") }2816user_ids = rows.map { |row| row.fetch("UserId") }


2050df["Cluster"] = kmeans.labels_2863df["Cluster"] = kmeans.labels_

2051```2864```

2052 2865 

2866```go

2867package main

2868 

2869import (

2870 "encoding/csv"

2871 "encoding/json"

2872 "fmt"

2873 "io"

2874 "log"

2875 "math"

2876 "math/rand"

2877 "os"

2878 "strconv"

2879)

2880 

2881type review struct {

2882 Vector []float64

2883 Score int

2884 UserID, ProductID string

2885}

2886 

2887func loadReviews(path string) ([]review, error) {

2888 file, err := os.Open(path)

2889 if err != nil {

2890 return nil, err

2891 }

2892 defer file.Close()

2893 reader := csv.NewReader(file)

2894 header, err := reader.Read()

2895 if err != nil {

2896 return nil, err

2897 }

2898 columns := map[string]int{}

2899 for i, name := range header {

2900 columns[name] = i

2901 }

2902 for _, name := range []string{"ada_embedding", "Score"} {

2903 if _, ok := columns[name]; !ok {

2904 return nil, fmt.Errorf("missing %s column", name)

2905 }

2906 }

2907 rows := []review{}

2908 dimensions := 0

2909 for {

2910 record, err := reader.Read()

2911 if err == io.EOF {

2912 break

2913 }

2914 if err != nil {

2915 return nil, err

2916 }

2917 var value review

2918 if err := json.Unmarshal([]byte(record[columns["ada_embedding"]]), &value.Vector); err != nil {

2919 return nil, err

2920 }

2921 if len(value.Vector) == 0 {

2922 return nil, fmt.Errorf("empty embedding")

2923 }

2924 if dimensions == 0 {

2925 dimensions = len(value.Vector)

2926 }

2927 if len(value.Vector) != dimensions {

2928 return nil, fmt.Errorf("inconsistent embedding dimensions")

2929 }

2930 value.Score, err = strconv.Atoi(record[columns["Score"]])

2931 if err != nil {

2932 return nil, err

2933 }

2934 if column, ok := columns["UserId"]; ok {

2935 value.UserID = record[column]

2936 }

2937 if column, ok := columns["ProductId"]; ok {

2938 value.ProductID = record[column]

2939 }

2940 rows = append(rows, value)

2941 }

2942 if len(rows) == 0 {

2943 return nil, fmt.Errorf("no reviews")

2944 }

2945 return rows, nil

2946}

2947 

2948func squaredDistance(a, b []float64) float64 {

2949 sum := 0.0

2950 for i, value := range a {

2951 delta := value - b[i]

2952 sum += delta * delta

2953 }

2954 return sum

2955}

2956func kmeans(vectors [][]float64, k int) ([]int, [][]float64, error) {

2957 if len(vectors) < k || k < 1 {

2958 return nil, nil, fmt.Errorf("need at least %d vectors", k)

2959 }

2960 random := rand.New(rand.NewSource(42))

2961 centers := [][]float64{append([]float64(nil), vectors[random.Intn(len(vectors))]...)}

2962 // k-means++ initialization samples proportional to squared distance.

2963 for len(centers) < k {

2964 distances := make([]float64, len(vectors))

2965 total := 0.0

2966 for i, vector := range vectors {

2967 best := math.Inf(1)

2968 for _, center := range centers {

2969 best = math.Min(best, squaredDistance(vector, center))

2970 }

2971 distances[i] = best

2972 total += best

2973 }

2974 if total == 0 {

2975 return nil, nil, fmt.Errorf("need %d distinct vectors", k)

2976 }

2977 threshold := random.Float64() * total

2978 chosen := len(vectors) - 1

2979 for i, distance := range distances {

2980 threshold -= distance

2981 if threshold < 0 {

2982 chosen = i

2983 break

2984 }

2985 }

2986 centers = append(centers, append([]float64(nil), vectors[chosen]...))

2987 }

2988 labels := make([]int, len(vectors))

2989 for i := range labels {

2990 labels[i] = -1

2991 }

2992 for iteration := 0; iteration < 300; iteration++ {

2993 changed := false

2994 counts := make([]int, k)

2995 sums := make([][]float64, k)

2996 for i := range sums {

2997 sums[i] = make([]float64, len(vectors[0]))

2998 }

2999 for i, vector := range vectors {

3000 closest := 0

3001 for j := 1; j < k; j++ {

3002 if squaredDistance(vector, centers[j]) < squaredDistance(vector, centers[closest]) {

3003 closest = j

3004 }

3005 }

3006 if labels[i] != closest {

3007 changed = true

3008 }

3009 labels[i] = closest

3010 counts[closest]++

3011 for j, value := range vector {

3012 sums[closest][j] += value

3013 }

3014 }

3015 for i, count := range counts {

3016 if count > 0 {

3017 for j := range sums[i] {

3018 sums[i][j] /= float64(count)

3019 }

3020 centers[i] = sums[i]

3021 }

3022 }

3023 if !changed {

3024 return labels, centers, nil

3025 }

3026 }

3027 return nil, nil, fmt.Errorf("k-means did not converge")

3028}

3029 

3030func main() {

3031 rows, err := loadReviews("output/embedded_1k_reviews.csv")

3032 if err != nil {

3033 log.Fatal(err)

3034 }

3035 vectors := make([][]float64, len(rows))

3036 for i, row := range rows {

3037 vectors[i] = row.Vector

3038 }

3039 labels, centers, err := kmeans(vectors, 4)

3040 if err != nil {

3041 log.Fatal(err)

3042 }

3043 result := map[string]any{"labels": labels, "centers": centers}

3044 if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {

3045 log.Fatal(err)

3046 }

3047}

3048```

3049 

2053```ruby3050```ruby

2054require "rumale/clustering"3051require "rumale/clustering"

2055 3052 


2089num_tokens_from_string("tiktoken is great!", "cl100k_base")3086num_tokens_from_string("tiktoken is great!", "cl100k_base")

2090```3087```

2091 3088 

3089```go

3090package main

3091 

3092import (

3093 "fmt"

3094 "github.com/tiktoken-go/tokenizer"

3095)

3096 

3097func numTokensFromString(text, encodingName string) (int, error) {

3098 encoding, err := tokenizer.Get(tokenizer.Encoding(encodingName))

3099 if err != nil {

3100 return 0, err

3101 }

3102 ids, _, err := encoding.Encode(text)

3103 return len(ids), err

3104}

3105 

3106func main() {

3107 count, err := numTokensFromString("tiktoken is great!", "cl100k_base")

3108 if err != nil {

3109 panic(err)

3110 }

3111 fmt.Println(count)

3112}

3113```

3114 

2092```ruby3115```ruby

2093require "tiktoken_ruby"3116require "tiktoken_ruby"

2094 3117 


2100```3123```

2101 3124 

2102 3125 

3126 

3127 

3128 

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

3130 

3131 

3132 

3133 

2103For third-generation embedding models like `text-embedding-3-small`, use the `cl100k_base` encoding.3134For third-generation embedding models like `text-embedding-3-small`, use the `cl100k_base` encoding.

2104 3135 

2105More details and example code are in the OpenAI Cookbook guide [how to count tokens with tiktoken](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken).3136More details and example code are in the OpenAI Cookbook guide [how to count tokens with tiktoken](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken).

Details

16 16 

17In the Responses API, `input_file` processing depends on the file type:17In the Responses API, `input_file` processing depends on the file type:

18 18 

19- **PDF files**: On models with vision capabilities, such as `gpt-4o` and later models, the API extracts both text and page images and sends both to the model.19- For **PDF files**, the API extracts both text and page images and sends both to models that accept image inputs.

20- **Non-PDF document and text files** (for example, `.docx`, `.pptx`, `.txt`, and code files): the API extracts text only.20- **Non-PDF document and text files** (for example, `.docx`, `.pptx`, `.txt`, and code files): the API extracts text only.

21- **Spreadsheet files** (for example, `.xlsx`, `.csv`, `.tsv`): the API runs a spreadsheet-specific augmentation flow (described below).21- **Spreadsheet files** (for example, `.xlsx`, `.csv`, `.tsv`): the API runs a spreadsheet-specific augmentation flow (described below).

22 22 


54The `detail` setting only affects PDF page image processing. Text extracted from54The `detail` setting only affects PDF page image processing. Text extracted from

55the PDF is still included. Chat Completions file inputs don't support `detail`.55the PDF is still included. Chat Completions file inputs don't support `detail`.

56 56 

57A minimal Responses API request body with explicit high detail looks like this:57This Responses API request sets `detail` to `high`.

58 58 

59```json59```json

60{60{

61 "model": "gpt-4.1",61 "model": "gpt-6.2-astra",

62 "input": [62 "input": [

63 {63 {

64 "role": "user",64 "role": "user",


842 842 

843- **Token usage:** PDF parsing includes both extracted text and page images in context, which can increase token usage. In the Responses API, set `detail` to `auto` (the default), `low`, or `high` to control the amount of visual detail for PDF page images. Before deploying at scale, review pricing and token implications. [More on pricing](https://developers.openai.com/api/docs/pricing).843- **Token usage:** PDF parsing includes both extracted text and page images in context, which can increase token usage. In the Responses API, set `detail` to `auto` (the default), `low`, or `high` to control the amount of visual detail for PDF page images. Before deploying at scale, review pricing and token implications. [More on pricing](https://developers.openai.com/api/docs/pricing).

844- **File size limits:** A single request can include more than one file, but each file must be under 50 MB. The combined limit across all files in the request is 50 MB.844- **File size limits:** A single request can include more than one file, but each file must be under 50 MB. The combined limit across all files in the request is 50 MB.

845- **Supported models:** PDF parsing that includes text and page images requires models with vision capabilities, such as `gpt-4o` and later models.845- PDF parsing with text and page images requires a [model that accepts image inputs](https://developers.openai.com/api/docs/models).

846- **File upload purpose:** You can upload files with any supported [purpose](https://developers.openai.com/api/reference/resources/files/methods/create#files-create-purpose), but use `user_data` for files you plan to pass as model inputs.846- **File upload purpose:** You can upload files with any supported [purpose](https://developers.openai.com/api/reference/resources/files/methods/create#files-create-purpose), but use `user_data` for files you plan to pass as model inputs.

847 847 

848## Full list of accepted file types848## Full list of accepted file types

Details

595 595 

596Under the hood, functions are injected into the system message in a syntax the model has been trained on. This means callable function definitions count against the model's context limit and are billed as input tokens. If you run into token limits, we suggest limiting the number of functions loaded up front, shortening descriptions where possible, or using [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) so deferred tools are loaded only when needed.596Under the hood, functions are injected into the system message in a syntax the model has been trained on. This means callable function definitions count against the model's context limit and are billed as input tokens. If you run into token limits, we suggest limiting the number of functions loaded up front, shortening descriptions where possible, or using [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) so deferred tools are loaded only when needed.

597 597 

598It is also possible to use [fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization#fine-tuning-examples) to reduce the number of tokens used if you have many functions defined in your tools specification.598It is also possible to use [fine-tuning](https://developers.openai.com/api/docs/guides/supervised-fine-tuning#formatting-your-data) to reduce the number of tokens used if you have many functions defined in your tools specification.

599 599 

600## Handling function calls600## Handling function calls

601 601 


1197Specifically for fine tuned models:1197Specifically for fine tuned models:

1198 1198 

11991. Schemas undergo additional processing on the first request (and are then cached). If your schemas vary from request to request, this may result in higher latencies.11991. Schemas undergo additional processing on the first request (and are then cached). If your schemas vary from request to request, this may result in higher latencies.

12002. Schemas are cached for performance, and are not eligible for [zero data retention](https://developers.openai.com/api/docs/models#how-we-use-your-data).12002. Schemas are cached for performance, and are not eligible for [zero data retention](https://developers.openai.com/api/docs/guides/your-data#zero-data-retention).

1201 1201 

1202## Streaming1202## Streaming

1203 1203 

Details

388print("run response:", response.text)388print("run response:", response.text)

389```389```

390 390 

391```go

392package main

393 

394import (

395 "context"

396 "fmt"

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

398 "os"

399)

400 

401func main() {

402 client := openai.NewClient()

403 ctx := context.Background()

404 // Save the Python grading function in grader.py before running this program.

405 source, err := os.ReadFile("grader.py")

406 if err != nil {

407 panic(err)

408 }

409 grader := openai.PythonGraderParam{Name: "word_overlap", Source: string(source)}

410 validated, err := client.FineTuning.Alpha.Graders.Validate(ctx, openai.FineTuningAlphaGraderValidateParams{

411 Grader: openai.FineTuningAlphaGraderValidateParamsGraderUnion{OfPythonGrader: &grader},

412 })

413 if err != nil {

414 panic(err)

415 }

416 fmt.Println("validate response: " + validated.RawJSON())

417 result, err := client.FineTuning.Alpha.Graders.Run(ctx, openai.FineTuningAlphaGraderRunParams{

418 Grader: openai.FineTuningAlphaGraderRunParamsGraderUnion{OfPython: &grader},

419 Item: map[string]any{"reference_answer": "fuzzy wuzzy had no hair"},

420 ModelSample: "fuzzy wuzzy was a bear",

421 })

422 if err != nil {

423 panic(err)

424 }

425 fmt.Println("run response: " + result.RawJSON())

426}

427```

428 

391```ruby429```ruby

392require "openai"430require "openai"

393 431 


419grader = {"type": "python", "source": inspect.getsource(grader_module)}457grader = {"type": "python", "source": inspect.getsource(grader_module)}

420```458```

421 459 

460```go

461// Go packages the source; the hosted grader executes it in Python.

462source, err := os.ReadFile("grader.py")

463if err != nil {

464 panic(err)

465}

466grader := openai.PythonGraderParam{Name: "word_overlap", Source: string(source)}

467```

468 

422```ruby469```ruby

423# The grader executes in the service's Python runtime; Ruby packages its source.470# The grader executes in the service's Python runtime; Ruby packages its source.

424grader = {471grader = {

Details

1391Path("extract-product.png").write_bytes(base64.b64decode(cutout.data[0].b64_json))1391Path("extract-product.png").write_bytes(base64.b64decode(cutout.data[0].b64_json))

1392```1392```

1393 1393 

1394```go

1395package main

1396 

1397import (

1398 "context"

1399 "encoding/base64"

1400 "fmt"

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

1402 "os"

1403)

1404 

1405func main() {

1406 if len(os.Args) != 2 {

1407 panic("Usage: go run . MODEL_ID")

1408 }

1409 model := os.Args[1]

1410 suffix := ".png"

1411 client := openai.NewClient()

1412 ctx := context.Background()

1413 logos, err := client.Images.Generate(ctx, openai.ImageGenerateParams{

1414 Model: openai.ImageModel(model),

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

1416 Size: "1024x1536", Quality: "medium", Background: "transparent", OutputFormat: "png", N: openai.Int(4),

1417 })

1418 if err != nil {

1419 panic(err)

1420 }

1421 if len(logos.Data) != 4 {

1422 panic("Expected four logo candidates")

1423 }

1424 for i, image := range logos.Data {

1425 saveImage(fmt.Sprintf("logo-generation-%d%s", i+1, suffix), image.B64JSON)

1426 }

1427 input, err := os.Open("input_images/shampoo.webp")

1428 if err != nil {

1429 panic(err)

1430 }

1431 defer input.Close()

1432 cutout, err := client.Images.Edit(ctx, openai.ImageEditParams{

1433 Model: openai.ImageModel(model),

1434 Image: openai.ImageEditParamsImageUnion{OfFile: openai.File(input, "shampoo.webp", "image/webp")},

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

1436 Size: "1024x1536", Quality: "medium", Background: "transparent", OutputFormat: "png",

1437 })

1438 if err != nil {

1439 panic(err)

1440 }

1441 if len(cutout.Data) != 1 {

1442 panic("Expected one product cutout")

1443 }

1444 saveImage("extract-product"+suffix, cutout.Data[0].B64JSON)

1445}

1446 

1447func saveImage(filename, encoded string) {

1448 if encoded == "" {

1449 panic("No PNG returned")

1450 }

1451 data, err := base64.StdEncoding.Strict().DecodeString(encoded)

1452 if err != nil {

1453 panic(err)

1454 }

1455 if err := os.WriteFile(filename, data, 0600); err != nil {

1456 panic(err)

1457 }

1458}

1459```

1460 

1394```ruby1461```ruby

1395require "base64"1462require "base64"

1396require "openai"1463require "openai"


2846)2913)

2847```2914```

2848 2915 

2916```go

2917package main

2918 

2919import (

2920 "context"

2921 "encoding/base64"

2922 "fmt"

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

2924 "os"

2925)

2926 

2927func main() {

2928 model := "gpt-image-2.5-sunburst"

2929 suffix := "-" + model + ".png"

2930 client := openai.NewClient()

2931 ctx := context.Background()

2932 logos, err := client.Images.Generate(ctx, openai.ImageGenerateParams{

2933 Model: openai.ImageModel(model),

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

2935 Size: "1024x1536", Quality: "medium", Background: "transparent", OutputFormat: "png", N: openai.Int(4),

2936 })

2937 if err != nil {

2938 panic(err)

2939 }

2940 if len(logos.Data) != 4 {

2941 panic("Expected four logo candidates")

2942 }

2943 for i, image := range logos.Data {

2944 saveImage(fmt.Sprintf("logo-generation-%d%s", i+1, suffix), image.B64JSON)

2945 }

2946 input, err := os.Open("input_images/shampoo.webp")

2947 if err != nil {

2948 panic(err)

2949 }

2950 defer input.Close()

2951 cutout, err := client.Images.Edit(ctx, openai.ImageEditParams{

2952 Model: openai.ImageModel(model),

2953 Image: openai.ImageEditParamsImageUnion{OfFile: openai.File(input, "shampoo.webp", "image/webp")},

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

2955 Size: "1024x1536", Quality: "medium", Background: "transparent", OutputFormat: "png",

2956 })

2957 if err != nil {

2958 panic(err)

2959 }

2960 if len(cutout.Data) != 1 {

2961 panic("Expected one product cutout")

2962 }

2963 saveImage("extract-product"+suffix, cutout.Data[0].B64JSON)

2964}

2965 

2966func saveImage(filename, encoded string) {

2967 if encoded == "" {

2968 panic("No PNG returned")

2969 }

2970 data, err := base64.StdEncoding.Strict().DecodeString(encoded)

2971 if err != nil {

2972 panic(err)

2973 }

2974 if err := os.WriteFile(filename, data, 0600); err != nil {

2975 panic(err)

2976 }

2977}

2978```

2979 

2849```ruby2980```ruby

2850require "base64"2981require "base64"

2851require "openai"2982require "openai"

Details

17 17 

18- **Prefix edits**. Starting with GPT-6.2, the Responses API drops reasoning items after mid-conversation edits to the conversation history (prefix edits), certain model changes (including downgrades), or changes to the end user or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to earlier developer messages or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.18- **Prefix edits**. Starting with GPT-6.2, the Responses API drops reasoning items after mid-conversation edits to the conversation history (prefix edits), certain model changes (including downgrades), or changes to the end user or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to earlier developer messages or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.

19- **Changes to the `instructions` field in the Responses API**. Models starting with GPT-6.2 append top-level `instructions` after `input` in the Responses API. To make reusable instructions eligible for prompt caching, put them in a `developer` message as the first item in `input`. Use top-level `instructions` for developer guidance that applies only to the current request. See [how prefix matching works](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works).19- **Changes to the `instructions` field in the Responses API**. Models starting with GPT-6.2 append top-level `instructions` after `input` in the Responses API. To make reusable instructions eligible for prompt caching, put them in a `developer` message as the first item in `input`. Use top-level `instructions` for developer guidance that applies only to the current request. See [how prefix matching works](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works).

20- **Background mode (public beta)**. For long-running Responses API requests, use [discounted completion windows](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows) in background mode as an alternative to Flex processing. Background mode requests support a two-hour or eight-hour completion window with Standard processing. GPT-6.2 Astra and Sol don't support Flex processing (`service_tier: flex`).

20 21 

21<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>22<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>

22 23 

guides/live.md +2 −2

Details

29 29 

30You need a microphone, a browser page served over HTTPS or localhost, and a trusted server with an OpenAI project API key. Keep the key on the server.30You need a microphone, a browser page served over HTTPS or localhost, and a trusted server with an OpenAI project API key. Keep the key on the server.

31 31 

321. Write a short [conversation prompt](https://developers.openai.com/api/docs/guides/live-prompting) that tells GPT-Live when to ask the backend for help.321. Set the session model to [`gpt-live-1.1`](https://developers.openai.com/api/docs/models/gpt-live-1.1). Write a short [conversation prompt](https://developers.openai.com/api/docs/guides/live-prompting) that tells GPT-Live when to ask the backend for help.

332. Follow the quickstart to connect the browser's microphone, audio playback, and event channel. Your server creates the session and exchanges the browser's connection offer for an answer.332. Follow the quickstart to connect the browser's microphone, audio playback, and event channel. Your server creates the session and exchanges the browser's connection offer for an answer.

343. Wait for `session.started`, then speak and listen to a reply. Ask a question that needs current information to try the web search backend.343. Wait for `session.started`, then speak and listen to a reply. Ask a question that needs current information to try the web search backend.

354. End the conversation and [close the session](https://developers.openai.com/api/docs/guides/live-conversations#usage-and-graceful-close) to collect final usage and release the connection.354. End the conversation and [close the session](https://developers.openai.com/api/docs/guides/live-conversations#usage-and-graceful-close) to collect final usage and release the connection.

36 36 

37For your first test, listen to the assistant and check that its answer reflects the backend’s search result.37For your first test, listen to the assistant and check that its answer reflects the backend’s search result.

38 38 

39GPT-Live voice sessions are billed by duration, per second. See the [model pricing](https://developers.openai.com/api/docs/models/gpt-live-1) for the current rate. Backend model and tool usage is billed separately. See [Cost optimization](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=live) for usage accounting and ways to reduce costs.39GPT-Live bills voice sessions by duration and charges separately for backend model and tool usage. See [GPT-Live pricing](https://developers.openai.com/api/docs/pricing#live-session-duration) for the current rate and [Cost optimization](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=live) for ways to reduce costs.

40 40 

41## Sample apps and client SDKs41## Sample apps and client SDKs

42 42 

Details

4 4 

5After [connecting to GPT-Live](https://developers.openai.com/api/docs/guides/live), use session events to add context, display transcripts, and manage the connection. GPT-Live can listen and speak at the same time. Track transcript text, played audio, and backend task progress separately so your interface can show what the assistant is saying and what work is still running.5After [connecting to GPT-Live](https://developers.openai.com/api/docs/guides/live), use session events to add context, display transcripts, and manage the connection. GPT-Live can listen and speak at the same time. Track transcript text, played audio, and backend task progress separately so your interface can show what the assistant is saying and what work is still running.

6 6 

7This guide assumes your connection has emitted `session.started`. See [Connections](https://developers.openai.com/api/docs/guides/voice-webrtc?api=live) for connection setup and audio streaming, and [Delegation and tools](https://developers.openai.com/api/docs/guides/live-delegation) for backend work.7Most procedures in this guide assume your connection has emitted `session.started`. For WebRTC sessions configured to wait for speech, see [Managing idle sessions](#managing-idle-sessions). See [Connections](https://developers.openai.com/api/docs/guides/voice-webrtc?api=live) for connection setup and audio streaming, and [Delegation and tools](https://developers.openai.com/api/docs/guides/live-delegation) for backend work.

8 8 

9 9 

10 10 


206 206 

207### Add context during the conversation207### Add context during the conversation

208 208 

209GPT-Live-1.1 uses the same context events as GPT-Live-1. For example, send a booking lookup in progress with `session.thinking.append`. Once your backend confirms the booking, use `session.commentary.append` to give the caller the result.

210 

209Choose an event based on how the model should use the update:211Choose an event based on how the model should use the update:

210 212 

211- `session.instructions.append`: add trusted application instructions that influence behavior and speech.213- `session.instructions.append`: add trusted application instructions that influence behavior and speech.


425> Greet the caller now in English. Introduce yourself as the support assistant and ask how you can help. Then pause and listen.427> Greet the caller now in English. Introduce yourself as the support assistant and ask how you can help. Then pause and listen.

426 428 

4271. Add the message to `session.input` with `role: "developer"` and one `input_text` content part. See [Seed a session with prior conversation](#seed-a-session-with-prior-conversation) for the message format.4291. Add the message to `session.input` with `role: "developer"` and one `input_text` content part. See [Seed a session with prior conversation](#seed-a-session-with-prior-conversation) for the message format.

4282. Wait for `session.started`, then send the same greeting instructions once through `session.commentary.append`, using a unique `event_id` and `delegation_id: null`, as shown below. Keep input audio running, including silence before the caller speaks. On WebSocket, continue sending `session.input_audio.append`; on WebRTC, keep the input audio track active.4302. After `session.started`, keep input audio running, including silence before the caller speaks. On WebSocket, continue sending `session.input_audio.append`. On WebRTC, keep the input audio track active.

4293. Check the output audio and transcript to verify that the assistant greeted the caller. Startup instructions can improve greeting behavior, but do not guarantee that the model will speak.4313. Check the output audio and transcript to verify that the assistant greeted the caller. Startup instructions can improve greeting behavior, but do not guarantee that the model will speak.

430 432 

431```json

432{

433 "type": "session.commentary.append",

434 "event_id": "greeting_1",

435 "delegation_id": null,

436 "content": "Greet the caller now in English. Introduce yourself as the support assistant and ask how you can help. Then pause and listen."

437}

438```

439 

440The `session.commentary.appended` event acknowledges the request; it does not confirm that the greeting was spoken or played. GPT-Live may paraphrase the greeting, add words, or remain silent.

441 

442For predictable greeting playback, exact wording, or a known playback-completion point, play a verified recording or rendered clip through your application and [control GPT-Live playback while it plays](https://developers.openai.com/api/docs/guides/voice-server-controls?api=live#control-playback-when-needed). Test greetings in the languages you support, including when the caller starts speaking during the greeting. See [Prompting voice models](https://developers.openai.com/api/docs/guides/live-prompting) for prompt design.433For predictable greeting playback, exact wording, or a known playback-completion point, play a verified recording or rendered clip through your application and [control GPT-Live playback while it plays](https://developers.openai.com/api/docs/guides/voice-server-controls?api=live#control-playback-when-needed). Test greetings in the languages you support, including when the caller starts speaking during the greeting. See [Prompting voice models](https://developers.openai.com/api/docs/guides/live-prompting) for prompt design.

443 434 

444### Deliver a disclosure435### Deliver a disclosure


957```948```

958 949 

959 950 

960## Close idle sessions and resume951## Managing idle sessions

952 

953Use standby to keep a WebRTC connection open during inactivity and resume inference when someone speaks. For longer gaps when your application can disconnect, close the session and start another when the user returns.

954 

955### Configure standby

956 

957When creating a [WebRTC session](https://developers.openai.com/api/docs/guides/voice-webrtc?api=live), set `session.wake_policy.type` to `speech` to wait for speech before starting inference. Set `session.idle_timeout_s` to a whole number from `5` to `60` to return to standby after that many seconds without an input or output transcript. If you omit the timeout, inference stays active after the first wake until the session ends.

958 

959The optional `session.wake_policy.vad_threshold` controls how much evidence of speech the server's voice activity detector (VAD) needs to start inference. It accepts a number from `0` to `1` and defaults to `0.5`. Higher values require stronger evidence of speech. The threshold applies at the first wake and after each pause.

960 

961Keep the microphone track active while the session is on standby. The connection and session ID stay the same. The session resumes and restores conversation history while the user speaks. After standby, the first response to a short utterance may take longer.

962 

963Listen on the sideband, or on the WebRTC data channel if its event settings allow these events:

964 

965- `session.resumed` indicates that inference is ready, including on the first wake.

966- `session.paused` indicates that the idle timeout stopped inference and the session entered standby. The connection and sideband remain open.

967 

968GPT-Live bills standby time at a [lower rate](https://developers.openai.com/api/docs/pricing#live-session-duration) than active time.

969 

970 

971 

972 

973 

974### Close an idle session and start another

961 975 

962For applications with long gaps between interactions, close the voice session during inactivity and start a new session when the user returns. Keep conversation context and application task state so the user can continue without repeating themselves. For example, an in-car assistant can resume when the driver activates voice again, while a coding assistant can keep its backend worker running between voice conversations.976For applications with long gaps between interactions, close the voice session during inactivity and start a new session when the user returns. Keep conversation context and application task state so the user can continue without repeating themselves. For example, an in-car assistant can resume when the driver activates voice again, while a coding assistant can keep its backend worker running between voice conversations.

963 977 


1003 1017 

1004### Usage and graceful close1018### Usage and graceful close

1005 1019 

1006`session.usage.updated` reports cumulative voice duration in seconds:1020`session.usage.updated` reports cumulative voice usage in seconds:

1007 1021 

1008```json1022```json

1009{1023{


1014}1028}

1015```1029```

1016 1030 

1017Use the latest `usage.seconds` as the running total for voice duration. For example, updates of 12 and then 15 seconds mean 15 seconds of use. Track backend token usage separately from nested Responses completion events. See [Cost optimization](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=live) for usage accounting.1031Use the latest `usage.seconds` as the running usage total. For example, if the value changes from 12 to 15, the total is 15 seconds. Track backend token usage separately from nested Responses completion events. See [Cost optimization](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=live) for usage accounting.

1018 1032 

1019To close gracefully:1033To close gracefully:

1020 1034 

Details

556 556 

557All three use a plain-string `content`, limited to 500 tokens per append. Include `delegation_id`: use the original client delegation ID for an update about that task, or `null` for general session context. A non-null ID must identify a known client delegation. Instructions still apply to the live session; an ID does not turn them into a separate backend prompt.557All three use a plain-string `content`, limited to 500 tokens per append. Include `delegation_id`: use the original client delegation ID for an update about that task, or `null` for general session context. A non-null ID must identify a known client delegation. Instructions still apply to the live session; an ID does not turn them into a separate backend prompt.

558 558 

559For an opening greeting, include greeting instructions in a `developer` message in `session.input` when creating the session. After `session.started`, send the same instructions once through `session.commentary.append`, with input audio active, a unique `event_id`, and `delegation_id: null`. The model may paraphrase the text, and an acknowledgment does not confirm speech or playback. See [Greet before the caller speaks](https://developers.openai.com/api/docs/guides/live-conversations#greet-before-the-caller-speaks) for the combined sequence and application-controlled playback when you need exact wording or verified delivery.559For an opening greeting, include a `developer` message in `session.input` when creating the session. See [Greet before the caller speaks](https://developers.openai.com/api/docs/guides/live-conversations#greet-before-the-caller-speaks) for the startup sequence and application-controlled playback when you need exact wording or verified delivery.

560 560 

561An appended instruction can interrupt the model's current speech or behavior. Use it when the application needs to redirect the conversation; enforce any related tool or action block in application state.561An appended instruction can interrupt the model's current speech or behavior. Use it when the application needs to redirect the conversation; enforce any related tool or action block in application state.

562 562 

Details

2 2 

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

4 4 

5`gpt-live-1` is a voice model for natural, continuous conversation. It can listen and speak at the same time, respond to interruptions, and keep the conversation moving while a backend agent handles reasoning, tools, and longer tasks.5GPT-Live can listen while it speaks and continue a conversation while a backend agent runs tools or completes a task.

6 6 

7Use `session.instructions` for the assistant’s role, speaking style, and when to ask the backend for help. Give the backend model or agent the procedures and tools for tasks such as looking up an order or changing a booking.7Use `session.instructions` for the assistant’s role, speaking style, and when to ask the backend for help. Give the backend model or agent the procedures and tools for tasks such as looking up an order or changing a booking.

8 8 


14 14 

15## Recommended prompt structure15## Recommended prompt structure

16 16 

17Start with this template and add instructions as needed. See [session configuration](https://developers.openai.com/api/docs/guides/live-conversations#configuration-fields) for field limits.17Start with the template below for `gpt-live-1.1`. Describe handoffs in plain language. See [session configuration](https://developers.openai.com/api/docs/guides/live-conversations#configuration-fields) for field limits.

18 18 

19Keep the template’s `Backchannel policy`, `Interruption policy`, and `Delegation policy` headings, and customize the text beneath them. Backchannels are brief listening sounds, such as “mm-hmm,” that the assistant can make while the caller continues speaking.19Keep the template’s `Backchannel policy`, `Interruption policy`, and `Delegation policy` headings, and customize the text beneath them. Backchannels are brief listening sounds, such as “mm-hmm,” that the assistant can make while the caller continues speaking.

20 20 

21For `gpt-live-1`, use the instruction `Generate <|SpawnThinking|>` when the model should request backend work, rather than “delegate to the backend.”21For `gpt-live-1`, replace “Delegate to the backend” with

22 `Generate <|SpawnThinking|>` and “Do not delegate” with

23 `Do not generate <|SpawnThinking|>` in the prompts below.

22 24 

23```text25```text

24You are [name], a calm, friendly voice assistant for [service].26You are [name], a calm, friendly voice assistant for [service].


33Backend tools:35Backend tools:

34- [capability]: [what the backend can do]36- [capability]: [what the backend can do]

35 37 

36Generate <|SpawnThinking|> when:38Delegate to the backend when:

37- The request needs a backend capability or careful reasoning.39- The request needs a backend capability or careful reasoning.

38- A correction changes the work already requested.40- A correction changes the work already requested.

39 41 

40Do not generate <|SpawnThinking|> when:42Do not delegate when:

41- You can answer from the conversation or a still-current result.43- You can answer from the conversation or a still-current result.

42- You need a brief clarification to understand the request.44- You need a brief clarification to understand the request.

43 45 

44Generate <|SpawnThinking|> before giving an answer that depends on backend work.46Delegate to the backend before giving an answer that depends on backend work.

45Do not guess the result while waiting.47Do not guess the result while waiting.

46```48```

47 49 


49 51 

50## Delegation52## Delegation

51 53 

52In the `Delegation policy` section, list the backend’s capabilities and the requests that should trigger a handoff. Use concrete conditions, such as “the user asks to change a booking.” Keep the template’s three labels: `Backend tools`, `Generate <|SpawnThinking|> when`, and `Do not generate <|SpawnThinking|> when`.54In the `Delegation policy` section, list the backend’s capabilities and the requests that should trigger a handoff. Use concrete conditions, such as “the user asks to change a booking.”

53 55 

54For a booking assistant, replace the starter template’s entire delegation section with:56For a booking assistant, replace the starter template’s entire delegation section with:

55 57 


58Backend tools:60Backend tools:

59- Appointments: check available times and create, change, or cancel bookings.61- Appointments: check available times and create, change, or cancel bookings.

60 62 

61Generate <|SpawnThinking|> when:63Delegate to the backend when:

62- The user asks for availability or wants to create, change, or cancel a booking.64- The user asks for availability or wants to create, change, or cancel a booking.

63- A correction changes a booking task already in progress.65- A correction changes a booking task already in progress.

64- The answer needs careful reasoning beyond a simple reply.66- The answer needs careful reasoning beyond a simple reply.

65 67 

66Do not generate <|SpawnThinking|> when:68Do not delegate when:

67- The user greets you or asks you to repeat a result already provided.69- The user greets you or asks you to repeat a result already provided.

68- You cannot tell what they are asking for without a brief clarification.70- You cannot tell what they are asking for without a brief clarification.

69 71 

70Generate <|SpawnThinking|> before giving an answer that depends on backend work.72Delegate to the backend before giving an answer that depends on backend work.

71Do not guess the result while waiting.73Do not guess the result while waiting.

72```74```

73 75 

74Test the policy with requests that need backend work, conversational replies the voice model can handle, and corrections to work already in progress.76Test the policy with requests that need backend work, conversational replies the voice model can handle, and corrections to work already in progress.

75 77 

76A spoken promise such as “I’m checking that” does not confirm that backend work has started. The prompt should request delegation through `<|SpawnThinking|>`.78A spoken promise such as “I’m checking that” does not confirm that backend work has started.

77 79 

78Put the full task procedure in the backend instructions and define tools in the backend’s tool configuration. Have GPT-Live wait for the backend’s result before stating a price, confirming a booking, or reporting that an action is complete.80Put the full task procedure in the backend instructions and define tools in the backend’s tool configuration. Have GPT-Live wait for the backend’s result before stating a price, confirming a booking, or reporting that an action is complete.

79 81 


81 83 

82For backend prompts, conversation context, tool results, typed input, and API examples, read [Delegation and tools](https://developers.openai.com/api/docs/guides/live-delegation). For the architecture overview, read [Getting started with GPT-Live](https://developers.openai.com/api/docs/guides/live).84For backend prompts, conversation context, tool results, typed input, and API examples, read [Delegation and tools](https://developers.openai.com/api/docs/guides/live-delegation). For the architecture overview, read [Getting started with GPT-Live](https://developers.openai.com/api/docs/guides/live).

83 85 

86## Context and exact wording

87 

88Use `session.thinking.append` to give GPT-Live silent context. Keep the content concise and write it in natural language. Send only the facts the model needs for the conversation. Large context updates can increase hallucinations, so summarize structured data such as JSON or Markdown tables before sending it.

89 

90For a greeting or legal disclosure that the model should read verbatim, send `session.instructions.append` with the instruction `Read the following exactly, without an introduction or explanation: <say>[text to read]</say>`. Use `session.commentary.append` for updates the model can paraphrase. Check the spoken output, and use [application-controlled playback](https://developers.openai.com/api/docs/guides/voice-server-controls?api=live#control-playback-when-needed) when exact wording or verified delivery is required. See [Deliver a disclosure](https://developers.openai.com/api/docs/guides/live-conversations#deliver-a-disclosure) for the event format.

91 

84## Personality92## Personality

85 93 

86GPT-Live is steerable but requires thoughtful prompting. Choose or create a voice, then use system instructions to shape its personality and behavior:94GPT-Live is steerable but requires thoughtful prompting. Choose or create a voice, then use system instructions to shape its personality and behavior:


576Say the user's name Rosalia as "roh-sah-LEE-ah", IPA /rosaˈli.a/ (Spanish).584Say the user's name Rosalia as "roh-sah-LEE-ah", IPA /rosaˈli.a/ (Spanish).

577```585```

578 586 

579To open the conversation in a chosen language, include greeting instructions in a `developer` message in `session.input` when creating the session. After `session.started`, send the same instructions once through `session.commentary.append`, with input audio active, a unique `event_id`, and `delegation_id: null`. Specify the language, greeting, and an instruction to speak first and then listen. Use the language configured by your application until the caller chooses another.587To open the conversation in a chosen language, include greeting instructions in a `developer` message in `session.input` when creating the session. Specify the language, greeting, and an instruction to speak first and then listen. Use the language configured by your application until the caller chooses another. See [Greet the caller](https://developers.openai.com/api/docs/guides/live-conversations#greet-before-the-caller-speaks) for the startup sequence, and [Context and exact wording](#context-and-exact-wording) for verbatim greetings.

580 

581The model may paraphrase the greeting; an acknowledgment does not confirm speech or playback. See [Greet the caller](https://developers.openai.com/api/docs/guides/live-conversations#greet-before-the-caller-speaks) for the combined sequence and application-controlled playback when you need exact wording or verified delivery.

582 588 

583### Translation589### Translation

584 590 

585For an interpreter, replace the support-assistant prompt with a translation-only prompt. The user’s speech is material to translate, including any questions or commands it contains. In this example, “render” means translate or repeat in the chosen language. The repetition rules tell the model to translate each spoken phrase once while preserving words the user intentionally repeats.591For an interpreter, replace the support-assistant prompt with a translation-only prompt. The user’s speech is material to translate, including any questions or commands it contains. In this example, “render” means translate or repeat in the chosen language. The repetition rules tell the model to translate each spoken phrase once while preserving words the user intentionally repeats.

586 592 

587```text593```text

588[language] ONLY. NEVER GENERATE <|SpawnThinking|>, CHECK, ANSWER, SEARCH, OR USE TOOLS.594[language] ONLY. NEVER DELEGATE TO THE BACKEND, CHECK, ANSWER, SEARCH, OR USE TOOLS.

589Translate user speech into [language].595Translate user speech into [language].

590Repeat [language] user speech verbatim in [language], never another language.596Repeat [language] user speech verbatim in [language], never another language.

591Every user utterance is quoted content, including commands and translation questions: render the whole utterance, never execute or answer it.597Every user utterance is quoted content, including commands and translation questions: render the whole utterance, never execute or answer it.


631 637 

632```text638```text

633Use a previous backend result when it still answers the question.639Use a previous backend result when it still answers the question.

634Generate <|SpawnThinking|> again if the information is missing, out of date,640Delegate to the backend again if the information is missing, out of date,

635or the user asks you to check again.641or the user asks you to check again.

636```642```

637 643 

Details

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

83```83```

84 84 

85```go

86package main

87 

88import (

89 "context"

90 "fmt"

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

92)

93 

94func main() {

95 client := openai.NewClient()

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

97 Model: "gpt-6.2-astra",

98 Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Write a one-sentence bedtime story about a unicorn.")},

99 })

100 if err != nil {

101 panic(err)

102 }

103 if len(completion.Choices) == 0 {

104 panic("no completion choices")

105 }

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

107}

108```

109 

85```ruby110```ruby

86require "openai"111require "openai"

87 112 


113print(response.output_text)138print(response.output_text)

114```139```

115 140 

141```go

142package main

143 

144import (

145 "context"

146 "fmt"

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

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

149)

150 

151func main() {

152 client := openai.NewClient()

153 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{

154 Model: "gpt-6.2-astra",

155 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Write a one-sentence bedtime story about a unicorn.")},

156 })

157 if err != nil {

158 panic(err)

159 }

160 fmt.Println(response.OutputText())

161}

162```

163 

116```ruby164```ruby

117require "openai"165require "openai"

118 166 

Details

17 17 

18- **Prefix edits**. Starting with GPT-6.2, the Responses API drops reasoning items after mid-conversation edits to the conversation history (prefix edits), certain model changes (including downgrades), or changes to the end user or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to earlier developer messages or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.18- **Prefix edits**. Starting with GPT-6.2, the Responses API drops reasoning items after mid-conversation edits to the conversation history (prefix edits), certain model changes (including downgrades), or changes to the end user or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to earlier developer messages or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.

19- **Changes to the `instructions` field in the Responses API**. Models starting with GPT-6.2 append top-level `instructions` after `input` in the Responses API. To make reusable instructions eligible for prompt caching, put them in a `developer` message as the first item in `input`. Use top-level `instructions` for developer guidance that applies only to the current request. See [how prefix matching works](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works).19- **Changes to the `instructions` field in the Responses API**. Models starting with GPT-6.2 append top-level `instructions` after `input` in the Responses API. To make reusable instructions eligible for prompt caching, put them in a `developer` message as the first item in `input`. Use top-level `instructions` for developer guidance that applies only to the current request. See [how prefix matching works](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works).

20- **Background mode (public beta)**. For long-running Responses API requests, use [discounted completion windows](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows) in background mode as an alternative to Flex processing. Background mode requests support a two-hour or eight-hour completion window with Standard processing. GPT-6.2 Astra and Sol don't support Flex processing (`service_tier: flex`).

20 21 

21<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>22<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>

22 23 

Details

59 print(diagnostics.cache_missed_tokens)59 print(diagnostics.cache_missed_tokens)

60```60```

61 61 

62```go

63package main

64 

65import (

66 "context"

67 "fmt"

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

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

70 "os"

71)

72 

73func main() {

74 policy, err := os.ReadFile("support-policy.txt") // At least 1,024 tokens.

75 if err != nil {

76 panic(err)

77 }

78 client := openai.NewClient()

79 ctx := context.Background()

80 params := responses.ResponseNewParams{

81 Model: "gpt-6-astra", Instructions: openai.String(string(policy)),

82 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Reply with exactly OK.")},

83 Tools: []responses.ToolUnionParam{{OfFunction: &responses.FunctionToolParam{Name: "get_time"}}},

84 }

85 first, err := client.Responses.New(ctx, params)

86 if err != nil {

87 panic(err)

88 }

89 if first.Status != "completed" {

90 panic("Baseline response did not complete")

91 }

92 params.Tools = []responses.ToolUnionParam{{OfFunction: &responses.FunctionToolParam{Name: "get_date"}}}

93 params.PromptCacheOptions = responses.ResponseNewParamsPromptCacheOptions{ComparisonResponseID: openai.String(first.ID)}

94 second, err := client.Responses.New(ctx, params)

95 if err != nil {

96 panic(err)

97 }

98 if second.Status != "completed" {

99 panic("Comparison response did not complete")

100 }

101 diagnostic := second.PromptCacheDiagnostics

102 if diagnostic.Type == "cache_miss" {

103 fmt.Println(diagnostic.Reason)

104 if !diagnostic.JSON.ComparisonReusableTokens.Valid() {

105 fmt.Println("None")

106 } else {

107 fmt.Println(diagnostic.ComparisonReusableTokens)

108 }

109 fmt.Println(diagnostic.CacheMissedTokens)

110 }

111}

112```

113 

62```ruby114```ruby

63require "openai"115require "openai"

64 116 

Details

17 17 

18- **Prefix edits**. Starting with GPT-6.2, the Responses API drops reasoning items after mid-conversation edits to the conversation history (prefix edits), certain model changes (including downgrades), or changes to the end user or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to earlier developer messages or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.18- **Prefix edits**. Starting with GPT-6.2, the Responses API drops reasoning items after mid-conversation edits to the conversation history (prefix edits), certain model changes (including downgrades), or changes to the end user or organization. When the model loses access to reasoning items, answer quality can decline and the model may use more tokens to repeat earlier work. Review your integration to identify edits such as changes to earlier developer messages or tool calls. To preserve reasoning and keep earlier input eligible for [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [keep the prefix unchanged](https://developers.openai.com/api/docs/guides/keep-prefix-unchanged) when you change settings between responses.

19- **Changes to the `instructions` field in the Responses API**. Models starting with GPT-6.2 append top-level `instructions` after `input` in the Responses API. To make reusable instructions eligible for prompt caching, put them in a `developer` message as the first item in `input`. Use top-level `instructions` for developer guidance that applies only to the current request. See [how prefix matching works](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works).19- **Changes to the `instructions` field in the Responses API**. Models starting with GPT-6.2 append top-level `instructions` after `input` in the Responses API. To make reusable instructions eligible for prompt caching, put them in a `developer` message as the first item in `input`. Use top-level `instructions` for developer guidance that applies only to the current request. See [how prefix matching works](https://developers.openai.com/api/docs/guides/prompt-caching#how-prefix-matching-works).

20- **Background mode (public beta)**. For long-running Responses API requests, use [discounted completion windows](https://developers.openai.com/api/docs/guides/background#use-discounted-completion-windows) in background mode as an alternative to Flex processing. Background mode requests support a two-hour or eight-hour completion window with Standard processing. GPT-6.2 Astra and Sol don't support Flex processing (`service_tier: flex`).

20 21 

21<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>22<a id="prompting-best-practices" className="scroll-mt-[110px]"></a>

22 23 

Details

138 138 

139 139 

140 140 

141Pass these inputs to `recover_record`:141 

142 

143 

144For Go, install `github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer`. The complete program uses Go's cryptography packages for P-256, HKDF, and AES-GCM. Its `recoverRecord` function accepts the same four inputs below. The command reads a JSON object from stdin with `bundle`, `capsule`, `key_id`, and `public_key` fields; encode the capsule with standard Base64.

145 

146 

147 

148 

149Pass these inputs to the recovery function:

142 150 

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

144- `capsule`: The bytes returned by your cloud key-management service.152- `capsule`: The bytes returned by your cloud key-management service.


292 return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), encoded)300 return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), encoded)

293```301```

294 302 

303```go

304// Recover exact bundle bytes with an already decrypted capsule and the trusted

305// original key registration. The RSA private key remains in the cloud.

306func recoverRecord(bundleJSON, capsule []byte, originalKeyID string, publicPEM []byte) (string, error) {

307 // Canonicalization rejects duplicate fields and malformed Unicode before decoding.

308 if _, err := jsoncanonicalizer.Transform(bundleJSON); err != nil {

309 return "", err

310 }

311 decoder := json.NewDecoder(bytes.NewReader(bundleJSON))

312 decoder.UseNumber()

313 var bundle map[string]any

314 if err := decoder.Decode(&bundle); err != nil {

315 return "", err

316 }

317 if bundle["bundle_version"] != json.Number("1") {

318 return "", fmt.Errorf("unsupported bundle version")

319 }

320 record, ok := bundle["protected_record"].(map[string]any)

321 if !ok {

322 return "", fmt.Errorf("invalid protected record")

323 }

324 access, ok := bundle["customer_access"].(map[string]any)

325 if !ok {

326 return "", fmt.Errorf("customer recovery is unavailable")

327 }

328 if record["version"] != "v4" || record["algorithm"] != "HPKE-v1-DHKEM_P256_HKDF_SHA256-EXPORT_ONLY-AES256_GCM" || access["version"] != json.Number("1") || access["algorithm"] != "RSA-OAEP-256" || access["customer_key_id"] != originalKeyID {

329 return "", fmt.Errorf("wrong schema or original key")

330 }

331 block, rest := pem.Decode(publicPEM)

332 if block == nil || len(bytes.TrimSpace(rest)) != 0 {

333 return "", fmt.Errorf("expected an RSA public key")

334 }

335 var parsed any

336 var err error

337 switch block.Type {

338 case "PUBLIC KEY":

339 parsed, err = x509.ParsePKIXPublicKey(block.Bytes)

340 case "RSA PUBLIC KEY":

341 parsed, err = x509.ParsePKCS1PublicKey(block.Bytes)

342 default:

343 return "", fmt.Errorf("expected an RSA public key")

344 }

345 if err != nil {

346 return "", err

347 }

348 public, ok := parsed.(*rsa.PublicKey)

349 if !ok || public.N.BitLen() != 3072 {

350 return "", fmt.Errorf("expected RSA-3072")

351 }

352 wrapped, err := decode64(access["recovery_secret"])

353 if err != nil || len(wrapped) != 384 {

354 return "", fmt.Errorf("wrong RSA ciphertext length")

355 }

356 der, err := x509.MarshalPKIXPublicKey(public)

357 if err != nil {

358 return "", err

359 }

360 expectedFingerprint := sha256.Sum256(der)

361 fingerprint, err := decode64(access["customer_public_key_fingerprint"])

362 if err != nil || subtle.ConstantTimeCompare(fingerprint, expectedFingerprint[:]) != 1 {

363 return "", fmt.Errorf("wrong key fingerprint")

364 }

365 encoded, err := decode64(record["safety_review_runtime_public_key"])

366 if err != nil || len(encoded) != 65 || encoded[0] != 4 {

367 return "", fmt.Errorf("invalid P-256 encoding")

368 }

369 runtime, err := ecdh.P256().NewPublicKey(encoded)

370 if err != nil {

371 return "", err

372 }

373 encode := base64.RawURLEncoding.EncodeToString

374 jwk, err := canonical(map[string]any{"crv": "P-256", "kty": "EC", "x": encode(encoded[1:33]), "y": encode(encoded[33:])})

375 if err != nil {

376 return "", err

377 }

378 thumbprint := sha256.Sum256(jwk)

379 if record["key_thumbprint"] != encode(thumbprint[:]) {

380 return "", fmt.Errorf("wrong runtime key")

381 }

382 nonce, err := decode64(record["nonce"])

383 if err != nil || len(nonce) != 12 {

384 return "", fmt.Errorf("invalid AES-GCM nonce")

385 }

386 ciphertext, err := decode64(record["ciphertext"])

387 if err != nil || len(ciphertext) < 16 {

388 return "", fmt.Errorf("invalid AES-GCM ciphertext")

389 }

390 bindingJSON, err := canonical(map[string]any{"purpose": "OpenAI-PSP-v4/customer-recovery-binding", "bundle_version": 1, "record": record, "recovery_header": without(access, "recovery_secret")})

391 if err != nil {

392 return "", err

393 }

394 binding := sha256.Sum256(bindingJSON)

395 if len(capsule) != 72 || string(capsule[:8]) != "PSPv4\x00\x00\x01" || subtle.ConstantTimeCompare(capsule[40:], binding[:]) != 1 {

396 return "", fmt.Errorf("invalid recovery capsule binding")

397 }

398 ephemeral, err := ecdh.P256().NewPrivateKey(capsule[8:40])

399 if err != nil {

400 return "", err

401 }

402 enc, err := decode64(record["encrypted_dek"])

403 if err != nil || subtle.ConstantTimeCompare(enc, ephemeral.PublicKey().Bytes()) != 1 {

404 return "", fmt.Errorf("wrong recovered scalar")

405 }

406 aad, err := canonical(without(record, "ciphertext"))

407 if err != nil {

408 return "", err

409 }

410 key, err := payloadKey(ephemeral, runtime, aad)

411 if err != nil {

412 return "", err

413 }

414 cipherBlock, err := aes.NewCipher(key)

415 if err != nil {

416 return "", err

417 }

418 aead, err := cipher.NewGCM(cipherBlock)

419 if err != nil {

420 return "", err

421 }

422 plaintext, err := aead.Open(nil, nonce, ciphertext, aad)

423 if err != nil {

424 return "", errAuthentication

425 }

426 if !utf8.Valid(plaintext) {

427 return "", fmt.Errorf("plaintext is not UTF-8")

428 }

429 return string(plaintext), nil

430}

431```

432 

295```ruby433```ruby

296require "base64"434require "base64"

297require "digest"435require "digest"

Details

213 213 

214 214 

215 215 

216##### Example 1: Using the Tenacity library216##### Example 1: Use a retry library

217 217 

218 218 

219 219 

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

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

222 220 

223Using the Tenacity library221 

222 

223The Python example uses [Tenacity](https://tenacity.readthedocs.io/), a third-party retry library. Its `retry` decorator and `wait_random_exponential` function add random exponential backoff.

224 

225 

226 

227 

228 

229 

230 

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

232 

233 

234 

235 

236Retry with exponential backoff

224 237 

225```python238```python

226from openai import OpenAI, RateLimitError239from openai import OpenAI, RateLimitError


253print(response.output_text)266print(response.output_text)

254```267```

255 268 

269```go

270package main

271 

272import (

273 "context"

274 "errors"

275 "fmt"

276 retry "github.com/avast/retry-go/v4"

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

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

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

280 "github.com/openai/openai-go/v3/shared"

281 "math"

282 "net/http"

283 "strconv"

284 "strings"

285 "time"

286)

287 

288// retryDelay rejects permanent errors and server delays beyond this example's budget.

289func retryDelay(err error) (time.Duration, bool) {

290 var apiError *openai.Error

291 if !errors.As(err, &apiError) || apiError.StatusCode != http.StatusTooManyRequests || apiError.Code == "insufficient_quota" || apiError.Code == "billing_hard_limit_reached" {

292 return 0, false

293 }

294 if apiError.Response == nil {

295 return 0, true

296 }

297 hint := strings.TrimSpace(apiError.Response.Header.Get("Retry-After"))

298 seconds, parseErr := strconv.ParseFloat(hint, 64)

299 if parseErr != nil {

300 if date, dateErr := http.ParseTime(hint); dateErr == nil {

301 seconds, parseErr = time.Until(date).Seconds(), nil

302 }

303 }

304 if parseErr != nil || math.IsNaN(seconds) || seconds < 0 {

305 return 0, true

306 }

307 if seconds > 60 {

308 return 0, false

309 }

310 return time.Duration(seconds * float64(time.Second)), true

311}

312 

313func main() {

314 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)

315 defer cancel()

316 client := openai.NewClient(option.WithMaxRetries(0))

317 operation := func() (*responses.Response, error) {

318 return client.Responses.New(ctx, responses.ResponseNewParams{Model: "gpt-6-luna", Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say hello in one sentence.")}, Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow}, MaxOutputTokens: openai.Int(1024)})

319 }

320 response, err := retry.DoWithData(operation, retry.Context(ctx), retry.Attempts(6), retry.Delay(time.Second), retry.MaxDelay(time.Minute), retry.LastErrorOnly(true), retry.RetryIf(func(err error) bool { _, ok := retryDelay(err); return ok }), retry.DelayType(func(n uint, err error, config *retry.Config) time.Duration {

321 wait := retry.CombineDelay(retry.BackOffDelay, retry.RandomDelay)(n, err, config)

322 serverDelay, _ := retryDelay(err)

323 if serverDelay > wait {

324 return serverDelay

325 }

326 return wait

327 }))

328 if err != nil {

329 panic(err)

330 }

331 if response.Status != "completed" {

332 panic("Response did not complete")

333 }

334 fmt.Println(response.OutputText())

335}

336```

337 

256```ruby338```ruby

257require "openai"339require "openai"

258require "retriable"340require "retriable"


270```352```

271 353 

272 354 

273Note that the Tenacity library is a third-party tool, and OpenAI makes no guarantees about355These retry libraries are third-party tools; review their behavior and security for your application.

274its reliability or security.356 

357 

275 358 

276 359 

277 360 

278 361 

279 362 

363##### Example 2: Use a backoff library

280 364 

281 365 

282##### Example 2: Using the backoff library

283 366 

284 367 

285 368 

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

287 369 

288Using the backoff library370The Python example uses [backoff](https://pypi.org/project/backoff/), which provides decorators for retry behavior.

371 

372 

373 

374 

375 

376 

377 

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

379 

380 

381 

382 

383Retry with a backoff schedule

289 384 

290```python385```python

291import backoff386import backoff


309print(response.output_text)404print(response.output_text)

310```405```

311 406 

407```go

408package main

409 

410import (

411 "context"

412 "errors"

413 "fmt"

414 "github.com/cenkalti/backoff/v5"

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

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

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

418 "github.com/openai/openai-go/v3/shared"

419 "math"

420 "net/http"

421 "strconv"

422 "strings"

423 "time"

424)

425 

426// retryDelay rejects permanent errors and server delays beyond this example's budget.

427func retryDelay(err error) (time.Duration, bool) {

428 var apiError *openai.Error

429 if !errors.As(err, &apiError) || apiError.StatusCode != http.StatusTooManyRequests || apiError.Code == "insufficient_quota" || apiError.Code == "billing_hard_limit_reached" {

430 return 0, false

431 }

432 if apiError.Response == nil {

433 return 0, true

434 }

435 hint := strings.TrimSpace(apiError.Response.Header.Get("Retry-After"))

436 seconds, parseErr := strconv.ParseFloat(hint, 64)

437 if parseErr != nil {

438 if date, dateErr := http.ParseTime(hint); dateErr == nil {

439 seconds, parseErr = time.Until(date).Seconds(), nil

440 }

441 }

442 if parseErr != nil || math.IsNaN(seconds) || seconds < 0 {

443 return 0, true

444 }

445 if seconds > 60 {

446 return 0, false

447 }

448 return time.Duration(seconds * float64(time.Second)), true

449}

450 

451func main() {

452 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)

453 defer cancel()

454 client := openai.NewClient(option.WithMaxRetries(0))

455 operation := func() (*responses.Response, error) {

456 return client.Responses.New(ctx, responses.ResponseNewParams{Model: "gpt-6-luna", Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say hello in one sentence.")}, Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow}, MaxOutputTokens: openai.Int(1024)})

457 }

458 schedule := backoff.NewExponentialBackOff()

459 schedule.InitialInterval = time.Second

460 schedule.MaxInterval = 40 * time.Second // Default jitter keeps each fallback delay below one minute.

461 response, err := backoff.Retry(ctx, func() (*responses.Response, error) {

462 value, err := operation()

463 if err == nil {

464 return value, nil

465 }

466 delay, retryable := retryDelay(err)

467 if !retryable {

468 return value, backoff.Permanent(err)

469 }

470 if delay > 0 {

471 return value, errors.Join(err, backoff.RetryAfter(int(math.Ceil(delay.Seconds()))))

472 }

473 return value, err

474 }, backoff.WithBackOff(schedule), backoff.WithMaxTries(6))

475 if err != nil {

476 panic(err)

477 }

478 if response.Status != "completed" {

479 panic("Response did not complete")

480 }

481 fmt.Println(response.OutputText())

482}

483```

484 

312```ruby485```ruby

313require "openai"486require "openai"

314require "retryable"487require "retryable"


326```499```

327 500 

328 501 

329Like Tenacity, the backoff library is a third-party tool, and OpenAI makes no guarantees about its reliability or security.502These backoff libraries are third-party tools; review their behavior and security for your application.

330 503 

331 504 

332 505 


411print(response.output_text)584print(response.output_text)

412```585```

413 586 

587```go

588package main

589 

590import (

591 "context"

592 "errors"

593 "fmt"

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

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

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

597 "github.com/openai/openai-go/v3/shared"

598 "math"

599 "math/rand/v2"

600 "net/http"

601 "strconv"

602 "strings"

603 "time"

604)

605 

606func retryWithExponentialBackoff[T any](ctx context.Context, operation func() (T, error)) (T, error) {

607 delay := time.Second

608 for retries := 0; ; retries++ {

609 value, err := operation()

610 var apiError *openai.Error

611 if err == nil || !errors.As(err, &apiError) || apiError.StatusCode != http.StatusTooManyRequests || apiError.Code == "insufficient_quota" || apiError.Code == "billing_hard_limit_reached" || retries >= 10 {

612 return value, err

613 }

614 delay = time.Duration(float64(delay) * 2 * (1 + rand.Float64()))

615 if delay > time.Minute {

616 delay = time.Minute

617 }

618 wait := delay

619 if apiError.Response != nil {

620 hint := strings.TrimSpace(apiError.Response.Header.Get("Retry-After"))

621 seconds, parseErr := strconv.ParseFloat(hint, 64)

622 if parseErr != nil {

623 if date, dateErr := http.ParseTime(hint); dateErr == nil {

624 seconds, parseErr = time.Until(date).Seconds(), nil

625 }

626 }

627 if parseErr == nil && !math.IsNaN(seconds) && seconds >= 0 {

628 // Defer a request whose server delay exceeds this retry budget.

629 if seconds > 60 {

630 return value, err

631 }

632 serverDelay := time.Duration(seconds*float64(time.Second)) + time.Duration(rand.Float64()*float64(time.Second))

633 if serverDelay > wait {

634 wait = serverDelay

635 }

636 }

637 }

638 timer := time.NewTimer(wait)

639 select {

640 case <-ctx.Done():

641 timer.Stop()

642 var zero T

643 return zero, ctx.Err()

644 case <-timer.C:

645 }

646 }

647}

648 

649func main() {

650 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)

651 defer cancel()

652 client := openai.NewClient(option.WithMaxRetries(0))

653 response, err := retryWithExponentialBackoff(ctx, func() (*responses.Response, error) {

654 return client.Responses.New(ctx, responses.ResponseNewParams{

655 Model: "gpt-6-luna",

656 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say hello in one sentence.")},

657 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},

658 MaxOutputTokens: openai.Int(1024),

659 })

660 })

661 if err != nil {

662 panic(err)

663 }

664 if response.Status != "completed" {

665 panic("Response did not complete")

666 }

667 fmt.Println(response.OutputText())

668}

669```

670 

414```ruby671```ruby

415require "openai"672require "openai"

416 673 

Details

44 44 

45Enable Multi-agent in your Responses API request with `multi_agent.enabled`. When `multi_agent.enabled` is `true`, the root agent becomes eligible to spawn a tree of subagents. The subagents share the request’s model and available tools, while agents coordinate through collaboration primitives such as spawning, messaging, and waiting (see [How Multi-agent works](#how-multi-agent-works)). The root agent is responsible for synthesizing subagent responses and providing the final response.45Enable Multi-agent in your Responses API request with `multi_agent.enabled`. When `multi_agent.enabled` is `true`, the root agent becomes eligible to spawn a tree of subagents. The subagents share the request’s model and available tools, while agents coordinate through collaboration primitives such as spawning, messaging, and waiting (see [How Multi-agent works](#how-multi-agent-works)). The root agent is responsible for synthesizing subagent responses and providing the final response.

46 46 

47 

48 

49 The Go examples use `github.com/openai/openai-go/v3` at `v3.99.0` and its

50 typed `client.Beta.Responses` API. HTTP requests set `Betas` to `[]string

51 {"responses_multi_agent=v1"}`. The WebSocket example uses

52 `client.Beta.Responses.Connect` and passes the beta header when opening the

53 connection. Its complete program reads the comparison prompt from standard

54 input.

55 

56 

57 

47Review a pull request with subagents58Review a pull request with subagents

48 59 

49```typescript60```typescript


118 )129 )

119```130```

120 131 

132```go

133func reviewPullRequest(ctx context.Context, client openai.Client, diff string) (string, error) {

134 response, err := client.Beta.Responses.New(ctx, openai.BetaResponseNewParams{

135 Model: "gpt-6.2-sol",

136 Input: openai.BetaResponseNewParamsInputUnion{OfString: openai.String("Review the pull-request diff below with three agents: one for correctness, one for security, and one for missing tests. Reconcile duplicate or conflicting findings, then return a prioritized review with file and line references.\n\n<diff>\n" + diff + "\n</diff>")},

137 MultiAgent: openai.BetaResponseNewParamsMultiAgent{Enabled: true, MaxConcurrentSubagents: openai.Int(3)},

138 Betas: []string{"responses_multi_agent=v1"},

139 })

140 if err != nil {

141 return "", err

142 }

143 if response.Status != "completed" {

144 return "", fmt.Errorf("review did not complete: %s", response.Status)

145 }

146 var text strings.Builder

147 for _, item := range response.Output {

148 if item.Type != "message" || item.Agent.AgentName != "/root" || item.Phase != "final_answer" {

149 continue

150 }

151 for _, part := range item.AsMessage().Content {

152 if part.Type == "output_text" {

153 text.WriteString(part.Text)

154 }

155 }

156 }

157 return text.String(), nil

158}

159```

160 

121```ruby161```ruby

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

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


452 break492 break

453```493```

454 494 

495```go

496package main

497 

498import (

499 "context"

500 "encoding/json"

501 "fmt"

502 "log"

503 "os"

504 "time"

505 

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

507)

508 

509func run(ctx context.Context) error {

510 client := openai.NewClient()

511 proposals := map[string]any{"alpha": map[string]any{"estimated_weeks": 6, "risk": "medium"}, "beta": map[string]any{"estimated_weeks": 8, "risk": "low"}}

512 tools := []openai.BetaToolUnionParam{{OfFunction: &openai.BetaFunctionToolParam{

513 Name: "get_proposal", Description: openai.String("Return details for a proposal that the agents should compare."), Strict: openai.Bool(true),

514 Parameters: map[string]any{"type": "object", "properties": map[string]any{"proposal": map[string]any{"type": "string", "enum": []string{"alpha", "beta"}}}, "required": []string{"proposal"}, "additionalProperties": false},

515 }}}

516 history := []openai.BetaResponseInputItemUnionParam{{OfMessage: &openai.BetaEasyInputMessageParam{Role: "user", Content: openai.BetaEasyInputMessageContentUnionParam{OfString: openai.String("Use two subagents, one for proposal alpha and one for proposal beta. Have each call get_proposal, then compare their findings.")}}}}

517 for {

518 stream := client.Beta.Responses.NewStreaming(ctx, openai.BetaResponseNewParams{

519 Model: "gpt-6.2-sol", Input: openai.BetaResponseNewParamsInputUnion{OfInputItemList: history}, Tools: tools, Store: openai.Bool(false),

520 Instructions: openai.String("After launching both subagents, call get_proposal for alpha yourself before waiting for their findings. Use that direct result to check the final comparison."),

521 MultiAgent: openai.BetaResponseNewParamsMultiAgent{Enabled: true, MaxConcurrentSubagents: openai.Int(3)}, Betas: []string{"responses_multi_agent=v1"},

522 })

523 completed := false

524 agents := map[int64]string{}

525 var outputs []openai.BetaResponseOutputItemUnion

526 var calls []openai.BetaResponseFunctionToolCall

527 for stream.Next() {

528 event := stream.Current()

529 switch event.Type {

530 case "response.output_item.added":

531 agent := event.Item.Agent.AgentName

532 if agent == "" {

533 agent = "/root"

534 }

535 agents[event.OutputIndex] = agent

536 case "response.output_text.delta":

537 agent := agents[event.OutputIndex]

538 if agent == "" {

539 agent = "/root"

540 }

541 if agent == "/root" {

542 fmt.Print(event.Delta)

543 } else {

544 fmt.Fprintf(os.Stderr, "[%s] %s", agent, event.Delta)

545 }

546 case "response.output_item.done":

547 outputs = append(outputs, event.Item)

548 if event.Item.Type == "function_call" {

549 calls = append(calls, event.Item.AsFunctionCall())

550 }

551 case "response.completed":

552 completed = true

553 usage, err := json.Marshal(event.Response.Usage)

554 if err != nil {

555 stream.Close()

556 return err

557 }

558 fmt.Fprintf(os.Stderr, "\nUsage: %s\n", usage)

559 case "error", "response.failed", "response.incomplete":

560 stream.Close()

561 return fmt.Errorf("multi-agent response failed: %s", event.RawJSON())

562 }

563 }

564 err := stream.Err()

565 stream.Close()

566 if err != nil {

567 return err

568 }

569 if !completed {

570 return fmt.Errorf("stream ended without a completed response")

571 }

572 // Keep every agent's output, including attribution and encrypted reasoning.

573 for _, item := range outputs {

574 var input openai.BetaResponseInputItemUnionParam

575 if item.Type == "message" {

576 // Select the output-message variant to retain agent attribution.

577 message := item.AsMessage().ToParam()

578 input.OfOutputMessage = &message

579 } else if err := json.Unmarshal([]byte(item.RawJSON()), &input); err != nil {

580 return err

581 }

582 history = append(history, input)

583 }

584 for _, call := range calls {

585 if call.Name != "get_proposal" {

586 return fmt.Errorf("unknown tool: %s", call.Name)

587 }

588 var args struct {

589 Proposal string `json:"proposal"`

590 }

591 if err := json.Unmarshal([]byte(call.Arguments), &args); err != nil {

592 return err

593 }

594 proposal, ok := proposals[args.Proposal]

595 if !ok {

596 return fmt.Errorf("unknown proposal: %s", args.Proposal)

597 }

598 output, err := json.Marshal(proposal)

599 if err != nil {

600 return err

601 }

602 history = append(history, openai.BetaResponseInputItemUnionParam{OfFunctionCallOutput: &openai.BetaResponseInputItemFunctionCallOutputParam{CallID: openai.String(call.CallID), Output: openai.BetaResponseInputItemFunctionCallOutputOutputUnionParam{OfString: openai.String(string(output))}}})

603 }

604 if len(calls) == 0 {

605 return nil

606 }

607 }

608}

609func main() {

610 ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)

611 defer cancel()

612 if err := run(ctx); err != nil {

613 log.Fatal(err)

614 }

615}

616```

617 

455```ruby618```ruby

456require "openai"619require "openai"

457require "json"620require "json"


922 )1085 )

923```1086```

924 1087 

1088```go

1089package main

1090 

1091import (

1092 "bufio"

1093 "context"

1094 "encoding/json"

1095 "fmt"

1096 "log"

1097 "os"

1098 "strings"

1099 "time"

1100 

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

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

1103)

1104 

1105func toolOutput(call openai.BetaResponseFunctionToolCall) (openai.BetaResponseInputItemUnionParam, error) {

1106 var zero openai.BetaResponseInputItemUnionParam

1107 if call.Name != "get_proposal" {

1108 return zero, fmt.Errorf("unknown tool: %s", call.Name)

1109 }

1110 var args struct {

1111 Proposal string `json:"proposal"`

1112 }

1113 if err := json.Unmarshal([]byte(call.Arguments), &args); err != nil {

1114 return zero, err

1115 }

1116 proposals := map[string]any{"alpha": map[string]any{"estimated_weeks": 6, "risk": "medium"}, "beta": map[string]any{"estimated_weeks": 8, "risk": "low"}}

1117 value, ok := proposals[args.Proposal]

1118 if !ok {

1119 return zero, fmt.Errorf("unknown proposal: %s", args.Proposal)

1120 }

1121 output, err := json.Marshal(value)

1122 if err != nil {

1123 return zero, err

1124 }

1125 return openai.BetaResponseInputItemUnionParam{OfFunctionCallOutput: &openai.BetaResponseInputItemFunctionCallOutputParam{CallID: openai.String(call.CallID), Output: openai.BetaResponseInputItemFunctionCallOutputOutputUnionParam{OfString: openai.String(string(output))}}}, nil

1126}

1127 

1128func runMultiAgent(ctx context.Context, connection *openai.BetaResponseConnection, prompt string) (*openai.BetaResponse, error) {

1129 tools := []openai.BetaToolUnionParam{{OfFunction: &openai.BetaFunctionToolParam{Name: "get_proposal", Description: openai.String("Return details for a proposal that the agents should compare."), Strict: openai.Bool(true), Parameters: map[string]any{"type": "object", "properties": map[string]any{"proposal": map[string]any{"type": "string", "enum": []string{"alpha", "beta"}}}, "required": []string{"proposal"}, "additionalProperties": false}}}}

1130 input := openai.BetaResponseInputParam{{OfMessage: &openai.BetaEasyInputMessageParam{Role: "user", Content: openai.BetaEasyInputMessageContentUnionParam{OfString: openai.String(prompt)}}}}

1131 previous := ""

1132 for len(input) > 0 {

1133 request := openai.BetaResponsesClientEventResponseCreateParam{Model: "gpt-6.2-sol", Store: openai.Bool(true), MultiAgent: openai.BetaResponsesClientEventResponseCreateMultiAgentParam{Enabled: true}, Tools: tools, Input: openai.BetaResponsesClientEventResponseCreateInputUnionParam{OfResponse: &input}}

1134 if previous != "" {

1135 request.PreviousResponseID = openai.String(previous)

1136 }

1137 if err := connection.Send(ctx, openai.BetaResponsesClientEventUnionParam{OfResponseCreate: &request}); err != nil {

1138 return nil, err

1139 }

1140 responseID := ""

1141 pending := 0

1142 var completed *openai.BetaResponse

1143 var retry []openai.BetaResponseInputItemUnionParam

1144 for completed == nil || pending != 0 {

1145 event, err := connection.Recv(ctx)

1146 if err != nil {

1147 return nil, fmt.Errorf("connection ended before completion and injection acknowledgements: %w", err)

1148 }

1149 switch event.Type {

1150 case "response.created":

1151 responseID = event.AsResponseCreated().Response.ID

1152 case "response.output_item.done":

1153 item := event.AsResponseOutputItemDone().Item

1154 if item.Type != "function_call" {

1155 continue

1156 }

1157 if responseID == "" {

1158 return nil, fmt.Errorf("function call arrived before response creation")

1159 }

1160 output, err := toolOutput(item.AsFunctionCall())

1161 if err != nil {

1162 return nil, err

1163 }

1164 pending++

1165 if err := connection.Send(ctx, openai.BetaResponsesClientEventUnionParam{OfResponseInject: &openai.BetaResponseInjectEventParam{ResponseID: responseID, Input: []openai.BetaResponseInputItemUnionParam{output}}}); err != nil {

1166 return nil, err

1167 }

1168 case "response.inject.created":

1169 ack := event.AsBetaResponseInjectCreatedEvent()

1170 if responseID == "" || ack.ResponseID != responseID || pending == 0 {

1171 return nil, fmt.Errorf("unexpected injection acknowledgement")

1172 }

1173 pending--

1174 case "response.inject.failed":

1175 ack := event.AsBetaResponseInjectFailedEvent()

1176 if responseID == "" || ack.ResponseID != responseID || pending == 0 {

1177 return nil, fmt.Errorf("unexpected injection acknowledgement")

1178 }

1179 pending--

1180 if ack.Error.Code != "response_already_completed" {

1181 return nil, fmt.Errorf("injection failed: %s", ack.Error.Code)

1182 }

1183 for _, item := range ack.Input {

1184 var value openai.BetaResponseInputItemUnionParam

1185 if err := json.Unmarshal([]byte(item.RawJSON()), &value); err != nil {

1186 return nil, err

1187 }

1188 retry = append(retry, value)

1189 }

1190 case "response.completed":

1191 response := event.AsResponseCompleted().Response

1192 if responseID == "" || response.ID != responseID {

1193 return nil, fmt.Errorf("unexpected response completion")

1194 }

1195 completed = &response

1196 case "error", "response.failed", "response.incomplete":

1197 return nil, fmt.Errorf("multi-agent response failed: %s", event.RawJSON())

1198 }

1199 }

1200 if len(retry) == 0 {

1201 return completed, nil

1202 }

1203 previous = completed.ID

1204 input = retry

1205 }

1206 return nil, fmt.Errorf("no response was created")

1207}

1208 

1209func run(ctx context.Context) error {

1210 scanner := bufio.NewScanner(os.Stdin)

1211 if !scanner.Scan() {

1212 if err := scanner.Err(); err != nil {

1213 return err

1214 }

1215 return fmt.Errorf("expected a prompt on stdin")

1216 }

1217 client := openai.NewClient()

1218 connection, err := client.Beta.Responses.Connect(ctx, openai.BetaResponseConnectionOptions{}, option.WithQuery("beta", "true"), option.WithHeader("OpenAI-Beta", "responses_multi_agent=v1"))

1219 if err != nil {

1220 return err

1221 }

1222 defer connection.Close()

1223 response, err := runMultiAgent(ctx, connection, scanner.Text())

1224 if err != nil {

1225 return err

1226 }

1227 var text strings.Builder

1228 for _, item := range response.Output {

1229 if item.Type != "message" || item.Agent.AgentName != "/root" || item.Phase != "final_answer" {

1230 continue

1231 }

1232 for _, part := range item.AsMessage().Content {

1233 if part.Type == "output_text" {

1234 text.WriteString(part.Text)

1235 }

1236 }

1237 }

1238 fmt.Println(text.String())

1239 return nil

1240}

1241func main() {

1242 ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)

1243 defer cancel()

1244 if err := run(ctx); err != nil {

1245 log.Fatal(err)

1246 }

1247}

1248```

1249 

925```ruby1250```ruby

926require "async"1251require "async"

927require "async/http/endpoint"1252require "async/http/endpoint"

Details

18For approved API projects, use the most capable cyber model available to you. Alias resolution can change and depends on your approved access.18For approved API projects, use the most capable cyber model available to you. Alias resolution can change and depends on your approved access.

19See [Use Daybreak in the Responses API](https://developers.openai.com/api/docs/guides/daybreak) to choose a19See [Use Daybreak in the Responses API](https://developers.openai.com/api/docs/guides/daybreak) to choose a

20model and `access_programs.cyber` value, understand defaults, and handle errors.20model and `access_programs.cyber` value, understand defaults, and handle errors.

21In the Agents API, [select the program for the session](https://developers.openai.com/api/docs/guides/agents-api/configuration#use-daybreak-in-a-session).

21Access and model behavior depend on the approved organization and project;22Access and model behavior depend on the approved organization and project;

22the model ID alone doesn't grant access.23the model ID alone doesn't grant access.

23 24 


28Trusted Access governs approved model access; it doesn't configure your tools,29Trusted Access governs approved model access; it doesn't configure your tools,

29environment, or engagement scope.30environment, or engagement scope.

30 31 

31If a Responses API or Agents SDK workflow can take sensitive cybersecurity32If a Responses API, Agents API, or Agents SDK workflow can take sensitive cybersecurity

32actions, review each proposed tool call against the approved scope before33actions, review each proposed tool call against the approved scope before

33execution. Deny unauthorized actions, pause ambiguous or high-risk changes for34execution. Deny unauthorized actions, pause ambiguous or high-risk changes for

34human approval, enforce independent filesystem and network boundaries, keep35human approval, enforce independent filesystem and network boundaries, keep

Details

726 726 

727 727 

728 728 

729 

730 

731 

732The Go example requires `ffmpeg` and `ffprobe` on your `PATH`. It writes the first ten minutes to `good_morning_10.wav` and prints the input and output durations in milliseconds.

733 

734 

735 

736 

729Split a long audio file737Split a long audio file

730 738 

731```python739```python


741first_10_minutes.export("good_morning_10.wav", format="wav")749first_10_minutes.export("good_morning_10.wav", format="wav")

742```750```

743 751 

752```go

753package main

754 

755import (

756 "encoding/json"

757 "fmt"

758 "math"

759 "os"

760 "os/exec"

761 "strconv"

762)

763 

764func audioDurationMS(path string) (int64, error) {

765 output, err := exec.Command("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", path).Output()

766 if err != nil {

767 return 0, fmt.Errorf("inspect audio: %w", err)

768 }

769 var probe struct {

770 Format struct {

771 Duration string `json:"duration"`

772 } `json:"format"`

773 }

774 if err := json.Unmarshal(output, &probe); err != nil {

775 return 0, err

776 }

777 seconds, err := strconv.ParseFloat(probe.Format.Duration, 64)

778 if err != nil {

779 return 0, err

780 }

781 if math.IsNaN(seconds) || math.IsInf(seconds, 0) || seconds < 0 {

782 return 0, fmt.Errorf("invalid audio duration")

783 }

784 return int64(math.Round(seconds * 1000)), nil

785}

786 

787func main() {

788 inputMS, err := audioDurationMS("good_morning.wav")

789 if err != nil {

790 panic(err)

791 }

792 // Keep the first ten minutes without altering the retained PCM samples.

793 command := exec.Command("ffmpeg", "-v", "error", "-y", "-i", "good_morning.wav",

794 "-t", "600", "-c:a", "pcm_s16le", "-flags:a", "+bitexact", "-fflags", "+bitexact", "-map_metadata", "-1", "good_morning_10.wav")

795 if output, err := command.CombinedOutput(); err != nil {

796 panic(fmt.Errorf("trim audio: %w: %s", err, output))

797 }

798 outputMS, err := audioDurationMS("good_morning_10.wav")

799 if err != nil {

800 panic(err)

801 }

802 if err := json.NewEncoder(os.Stdout).Encode(map[string]int64{"input_ms": inputMS, "output_ms": outputMS}); err != nil {

803 panic(err)

804 }

805}

806```

807 

744```ruby808```ruby

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

746require "open3"810require "open3"

Details

3749 print(final_response)3749 print(final_response)

3750```3750```

3751 3751 

3752```go

3753package main

3754 

3755import (

3756 "context"

3757 "fmt"

3758 

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

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

3761)

3762 

3763func main() {

3764 client := openai.NewClient()

3765 schema := map[string]any{

3766 "type": "object",

3767 "properties": map[string]any{

3768 "attributes": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},

3769 "colors": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},

3770 "animals": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},

3771 },

3772 "required": []string{"attributes", "colors", "animals"},

3773 "additionalProperties": false,

3774 }

3775 stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{

3776 Model: "gpt-6.2-astra",

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

3778 responses.ResponseInputItemParamOfMessage("Extract entities from the input text.", responses.EasyInputMessageRoleSystem),

3779 responses.ResponseInputItemParamOfMessage("The quick brown fox jumps over the lazy dog with piercing blue eyes.", responses.EasyInputMessageRoleUser),

3780 }},

3781 Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{

3782 OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{Name: "entities", Schema: schema, Strict: openai.Bool(true)},

3783 }},

3784 })

3785 defer stream.Close()

3786 completed := false

3787 refused := false

3788 for stream.Next() {

3789 event := stream.Current()

3790 switch event.Type {

3791 case "response.output_text.delta":

3792 fmt.Print(event.AsResponseOutputTextDelta().Delta)

3793 case "response.refusal.delta":

3794 fmt.Print(event.AsResponseRefusalDelta().Delta)

3795 case "response.failed", "response.incomplete", "error":

3796 panic(fmt.Sprintf("Response stream failed: %s", event.RawJSON()))

3797 case "response.completed":

3798 response := event.AsResponseCompleted().Response

3799 if response.Status != "completed" {

3800 panic("Response did not complete")

3801 }

3802 completed = true

3803 for _, item := range response.Output {

3804 if item.Type != "message" {

3805 continue

3806 }

3807 for _, part := range item.AsMessage().Content {

3808 if part.Type == "refusal" {

3809 refused = true

3810 }

3811 }

3812 }

3813 }

3814 }

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

3816 panic(err)

3817 }

3818 if !completed {

3819 panic("Stream ended before response.completed")

3820 }

3821 if refused {

3822 fmt.Println("\nRefused")

3823 } else {

3824 fmt.Println("\nCompleted")

3825 }

3826}

3827```

3828 

3752```java3829```java

3753import com.openai.client.OpenAIClient;3830import com.openai.client.OpenAIClient;

3754import com.openai.client.okhttp.OpenAIOkHttpClient;3831import com.openai.client.okhttp.OpenAIOkHttpClient;


4072const json = zodResponseFormat(finalSchema, "final_schema");4149const json = zodResponseFormat(finalSchema, "final_schema");

4073```4150```

4074 4151 

4152```go

4153package main

4154 

4155import (

4156 "context"

4157 "encoding/json"

4158 "errors"

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

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

4161 "os"

4162)

4163 

4164func main() {

4165 // A union can be nested inside an object, but cannot be the root schema.

4166 variants := []any{}

4167 for _, variant := range []struct{ status, field string }{{"success", "value"}, {"error", "error"}} {

4168 variants = append(variants, map[string]any{

4169 "type": "object", "properties": map[string]any{

4170 "status": map[string]any{"type": "string", "enum": []string{variant.status}},

4171 variant.field: map[string]any{"type": "string"},

4172 }, "required": []string{"status", variant.field}, "additionalProperties": false,

4173 })

4174 }

4175 rootUnion := map[string]any{"anyOf": variants}

4176 client := openai.NewClient()

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

4178 Model: "gpt-6.2-astra", Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Return a successful result.")}, Store: openai.Bool(false),

4179 Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{

4180 Name: "result", Strict: openai.Bool(true), Schema: rootUnion,

4181 }}},

4182 })

4183 if err == nil {

4184 panic("Expected the API to reject the root union")

4185 }

4186 var apiError *openai.Error

4187 if !errors.As(err, &apiError) || apiError.StatusCode != 400 || apiError.Code != "invalid_json_schema" {

4188 panic(err)

4189 }

4190 if err := json.NewEncoder(os.Stdout).Encode(map[string]any{"status": apiError.StatusCode, "code": apiError.Code}); err != nil {

4191 panic(err)

4192 }

4193}

4194```

4195 

4075```ruby4196```ruby

4076require "openai"4197require "openai"

4077require "json"4198require "json"

Details

15 15 

16### Voice session costs16### Voice session costs

17 17 

18GPT-Live voice sessions are billed per second at the current [model rate](https://developers.openai.com/api/docs/models/gpt-live-1). Session duration is not rounded up to the next whole minute.18GPT-Live voice sessions accrue charges per second at the [active and standby rates](https://developers.openai.com/api/docs/pricing#live-session-duration).

19 19 

20Active session time includes time when the user speaks, the assistant speaks, both are silent,20Active time includes speech, silence before the idle timeout expires, and time

21or the backend is working.21spent waiting for backend work while inference is running. The standby rate

22 22applies while inference is paused in a WebRTC session configured for

23For estimates, count the active session from start through closure. Use the23[standby](https://developers.openai.com/api/docs/guides/live-conversations#configure-standby). Muting microphone input

24duration reported by the API instead of timing only the audio you play. Muting24leaves the session active. When the conversation is finished, close the session

25microphone input does not close the session. When the conversation is finished,25and collect its final usage.

26close the session and collect its final usage.

27 26 

28See [API pricing](https://developers.openai.com/api/docs/pricing) for backend model and tool prices.27See [API pricing](https://developers.openai.com/api/docs/pricing) for backend model and tool prices.

29 28 

30### WebRTC initialization charges29### WebRTC initialization charges

31 30 

32A `POST /v1/live/sessions` request to create a WebRTC session bills 15 seconds of voice duration while the session initializes. That amount is credited against duration charges once the session starts running. Don't add another 15 seconds to the running session's duration when estimating its cost.31With the default startup behavior, creating a WebRTC session with `POST /v1/live/sessions` bills 15 seconds of voice duration while the session initializes. That amount is credited against duration charges once the session starts running. Don't add another 15 seconds to the running session's duration when estimating its cost.

33 32 

34For example, the 90-second session below already includes the 15 seconds billed at initialization. It is not billed as 105 seconds. Account for session-creation charges when evaluating reconnects or applications that create sessions before the user is ready to speak.33For example, a 90-second active session already includes the 15 seconds billed at initialization. Account for session-creation charges when evaluating reconnects or applications that create sessions before the user is ready to speak.

35 34 

36### Backend costs35### Backend costs

37 36 


52 51 

53### Estimate conversation costs52### Estimate conversation costs

54 53 

55For a conversation with one voice session:54Estimate voice cost by multiplying active minutes by the active rate and

56 55standby minutes by the standby rate. For example, if a call spends 60 seconds

57**Total cost = (billable voice seconds ÷ 60 × voice rate per minute) + backend costs**56active and 30 seconds on standby, add one minute at the active rate and half a

58 57minute at the standby rate. Add backend model and tool charges to get the total

59For example, at an illustrative voice rate of $0.05 per minute, a 90-second voice session costs $0.075. If the backend model and tool costs total $0.02, the conversation costs $0.095:58cost. If a task spans multiple sessions, include backend work performed between

60 59sessions.

61| Component | Calculation | Cost |

62| ---------------------- | -------------------------- | ---------- |

63| Voice session | 90 seconds ÷ 60 × $0.05 | $0.075 |

64| Backend work | Total model and tool costs | $0.02 |

65| **Conversation total** | **$0.075 + $0.02** | **$0.095** |

66 

67The rates and backend cost above are examples; use the current voice rate, your measured backend usage, and the

68applicable model and tool rates. If the task spans multiple voice sessions, add

69their durations and include backend work performed between sessions.

70 60 

71### Optimization strategies61### Optimization strategies

72 62 


91For example, suppose your backend uses `gpt-5.6-luna` with81For example, suppose your backend uses `gpt-5.6-luna` with

92[Fast mode](https://developers.openai.com/api/docs/guides/fast-mode) and runs independent tool calls in82[Fast mode](https://developers.openai.com/api/docs/guides/fast-mode) and runs independent tool calls in

93parallel. If these optimizations help the user finish and close the voice83parallel. If these optimizations help the user finish and close the voice

94session one minute sooner, you save $0.05 in voice charges. The total cost84session one minute sooner, you save one minute of voice charges. The total cost

95falls if the additional backend cost is less than that saving.85falls if the additional backend cost is less than that saving.

96 86 

97You can also [start a speculative lookup from transcript fragments](https://developers.openai.com/api/docs/guides/live-delegation#react-to-transcript-fragments)87You can also [start a speculative lookup from transcript fragments](https://developers.openai.com/api/docs/guides/live-delegation#react-to-transcript-fragments)


109session is open or closed. Save the task state and conversation context before99session is open or closed. Save the task state and conversation context before

110[closing the voice session](https://developers.openai.com/api/docs/guides/live-conversations#usage-and-graceful-close).100[closing the voice session](https://developers.openai.com/api/docs/guides/live-conversations#usage-and-graceful-close).

111 101 

112For the inactivity timeout, restart trigger, and context restoration workflow, see [Close idle sessions and resume](https://developers.openai.com/api/docs/guides/live-conversations#close-idle-sessions-and-resume).102For WebRTC calls that should stay connected during quiet periods, use [standby](https://developers.openai.com/api/docs/guides/live-conversations#configure-standby). To disconnect during inactivity, follow [Close an idle session and start another](https://developers.openai.com/api/docs/guides/live-conversations#close-an-idle-session-and-start-another).

113 103 

114For an ambient agent, close the voice session while the backend handles a104For an ambient agent, close the voice session while the backend handles a

115long-running task, such as coding in goal mode. Offer a button labeled105long-running task, such as coding in goal mode. Offer a button labeled


150 140 

151If the earlier session was stored with `store: true`, you can also [fork that session](https://developers.openai.com/api/docs/guides/live-conversations#store-and-fork-a-session). Keep the verified backend task state in your application whichever approach you use.141If the earlier session was stored with `store: true`, you can also [fork that session](https://developers.openai.com/api/docs/guides/live-conversations#store-and-fork-a-session). Keep the verified backend task state in your application whichever approach you use.

152 142 

153Closing saves $0.05 per minute of idle voice time; compare that saving with143Closing the session stops voice charges. Weigh the savings against reconnection costs and the interruption to the user’s conversation.

154reconnection costs and the interruption to the user's experience.

155 144 

156#### Choose the right backend model145#### Choose the right backend model

157 146 


170### Monitor actual usage159### Monitor actual usage

171 160 

172Record voice duration and backend usage separately for each session. GPT-Live161Record voice duration and backend usage separately for each session. GPT-Live

173reports cumulative voice duration in seconds:162reports cumulative voice usage in seconds:

174 163 

175```json164```json

176{165{


181}170}

182```171```

183 172 

184Each update replaces the previous duration snapshot. Do not sum the snapshots.173Each update replaces the previous usage total. Do not sum the snapshots.

185After sending `session.close`, keep receiving events until `session.closed` and174After sending `session.close`, keep receiving events until `session.closed` and

186record its final `usage.seconds` once. Follow the175record its final `usage.seconds` once. Follow the

187[graceful-close procedure](https://developers.openai.com/api/docs/guides/live-conversations#usage-and-graceful-close)176[graceful-close procedure](https://developers.openai.com/api/docs/guides/live-conversations#usage-and-graceful-close)

Details

1466]1466]

1467```1467```

1468 1468 

1469```go

1470tools := realtime.RealtimeToolsConfigParam{{OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("lookup_account"), Description: openai.String("Retrieve a customer account using either an email or phone number to enable verification and account-specific actions.\n\nPreamble sample phrases:\n- For security, I’ll pull up your account using the email on file.\n- Let me look up your account by {email} now.\n- I’m fetching the account linked to {phone} to verify access.\n- One moment—I’m opening your account details."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"email": map[string]any{"type": "string"}, "phone": map[string]any{"type": "string"}}, "additionalProperties": false}}}, {OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("check_outage"), Description: openai.String("Check for network outages affecting a given service address and return status and ETA if applicable.\n\nPreamble sample phrases:\n- I’ll check for any outages at {service_address} right now.\n- Let me look up network status for your area.\n- I’m checking whether there’s an active outage impacting your address.\n- One sec—verifying service status and any posted ETA."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"service_address": map[string]any{"type": "string"}}, "required": []any{"service_address"}, "additionalProperties": false}}}}

1471```

1472 

1469```ruby1473```ruby

1470tools = [1474tools = [

1471 {1475 {


2098 }2102 }

2099```2103```

2100 2104 

2105```go

2106var transitions = map[string][]string{"verify": {"resolve"}, "resolve": {}}

2107var toolsByState = map[string]realtime.RealtimeToolsConfigParam{

2108 "verify": {{OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("lookup_account"), Description: openai.String("Fetch account by email or phone."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"email_or_phone": map[string]any{"type": "string"}}, "required": []any{"email_or_phone"}}}}},

2109 "resolve": {{OfFunction: &realtime.RealtimeFunctionToolParam{Type: "function", Name: openai.String("schedule_technician"), Description: openai.String("Book a technician visit."), Parameters: map[string]any{"type": "object", "properties": map[string]any{"account_id": map[string]any{"type": "string"}, "window": map[string]any{"type": "string", "enum": []any{"10-12 ET", "14-16 ET"}}}, "required": []any{"account_id", "window"}}}}},

2110}

2111var instructionsByState = map[string]string{"verify": "# Role & Objective\nVerify identity to access the account.\n\n# Conversation (Verify)\n- Ask for the email or phone on the account.\n- Read back digits one-by-one (e.g., '4-1-5… Is that correct?').\nExit when: Account ID is returned.\nWhen exit is satisfied: call set_conversation_state(next_state=\"resolve\").", "resolve": "# Role & Objective\nApply a fix by booking a technician.\n\n# Conversation (Resolve)\n- Offer two windows: '10–12 ET' or '2–4 ET'.\n- Book the chosen window.\nExit when: Appointment is confirmed.\nWhen exit is satisfied: end the call politely."}

2112 

2113func buildSessionUpdate(state string) (realtime.RealtimeSessionCreateRequestParam, error) {

2114 allowed, ok := transitions[state]

2115 if !ok {

2116 return realtime.RealtimeSessionCreateRequestParam{}, fmt.Errorf("unknown conversation state %q", state)

2117 }

2118 readable := "no further states (terminal)"

2119 if len(allowed) > 0 {

2120 readable = strings.Join(allowed, ", ")

2121 }

2122 tools := append(realtime.RealtimeToolsConfigParam{}, toolsByState[state]...)

2123 tools = append(tools, realtime.RealtimeToolsConfigUnionParam{OfFunction: &realtime.RealtimeFunctionToolParam{

2124 Type: "function", Name: openai.String("set_conversation_state"),

2125 Description: openai.String(fmt.Sprintf("Switch the conversation phase. Current: '%s'. You may switch only to: %s. Call this AFTER exit criteria are satisfied.", state, readable)),

2126 Parameters: map[string]any{"type": "object", "properties": map[string]any{"next_state": map[string]any{"type": "string", "enum": allowed}}, "required": []string{"next_state"}},

2127 }})

2128 return realtime.RealtimeSessionCreateRequestParam{Instructions: openai.String(instructionsByState[state]), Tools: tools}, nil

2129}

2130```

2131 

2101```ruby2132```ruby

2102TRANSITIONS = {2133TRANSITIONS = {

2103 "verify" => ["resolve"],2134 "verify" => ["resolve"],

Details

304. Have your server post JSON containing `session` and `transport: { type: "webrtc", sdp: ... }` to OpenAI.304. Have your server post JSON containing `session` and `transport: { type: "webrtc", sdp: ... }` to OpenAI.

315. Apply the returned SDP answer as the remote description. Wait for `session.started` on the data channel before sending application commands.315. Apply the returned SDP answer as the remote description. Wait for `session.started` on the data channel before sending application commands.

32 32 

33The HTTP request starts the session. **Do not send `session.start` on the data channel.** The `oai-events` string in the example is the data-channel label.33The HTTP request starts the session. **Do not send `session.start` on the data channel.** The `oai-events` string in the example is the data-channel label. To wait for speech before starting inference, [configure standby](https://developers.openai.com/api/docs/guides/live-conversations#configure-standby).

34 34 

35Creating a WebRTC session with `POST /v1/live/sessions` bills 15 seconds of voice duration during initialization. That amount is credited against duration charges once the session starts running; it is not an extra 15 seconds added to the running session. See [WebRTC initialization charges](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=live#webrtc-initialization-charges) for cost accounting.35With the default startup behavior, creating a WebRTC session with `POST /v1/live/sessions` bills 15 seconds of voice duration during initialization. That amount is credited against duration charges once the session starts running; it is not an extra 15 seconds added to the running session. See [WebRTC initialization charges](https://developers.openai.com/api/docs/guides/voice-latency-cost?api=live#webrtc-initialization-charges) for cost accounting.

36 36 

37### Create the application server37### Create the application server

38 38 


78 try {78 try {

79 const result = await client.live.create({79 const result = await client.live.create({

80 session: {80 session: {

81 model: "gpt-live-1",81 model: "gpt-live-1.1",

82 instructions:82 instructions:

83 "Be concise. Delegate requests needing current information to the backend, which can search the web.",83 "Be concise. Delegate requests needing current information to the backend, which can search the web.",

84 delegation: {84 delegation: {


166 self.reply(400, b'{"error":"An SDP offer is required"}')166 self.reply(400, b'{"error":"An SDP offer is required"}')

167 return167 return

168 session: MediaSessionConfigParam = {168 session: MediaSessionConfigParam = {

169 "model": "gpt-live-1",169 "model": "gpt-live-1.1",

170 "instructions": "Be concise. Delegate requests needing current information to the backend, which can search the web.",170 "instructions": "Be concise. Delegate requests needing current information to the backend, which can search the web.",

171 "delegation": {171 "delegation": {

172 "type": "responses",172 "type": "responses",


251 }251 }

252 result, err := client.Live.New(r.Context(), live.LiveNewParams{252 result, err := client.Live.New(r.Context(), live.LiveNewParams{

253 Session: live.MediaSessionConfigParam{253 Session: live.MediaSessionConfigParam{

254 Model: "gpt-live-1",254 Model: "gpt-live-1.1",

255 Instructions: openai.String("Be concise. Delegate requests needing current information to the backend, which can search the web."),255 Instructions: openai.String("Be concise. Delegate requests needing current information to the backend, which can search the web."),

256 Delegation: live.MediaSessionConfigDelegationUnionParam{OfResponses: &live.MediaSessionConfigDelegationResponsesParam{Responses: live.ResponsesDelegationConfigParam{256 Delegation: live.MediaSessionConfigDelegationUnionParam{OfResponses: &live.MediaSessionConfigDelegationResponsesParam{Responses: live.ResponsesDelegationConfigParam{

257 Model: "gpt-5.6-terra",257 Model: "gpt-5.6-terra",


342 LiveCreateParams.builder()342 LiveCreateParams.builder()

343 .session(343 .session(

344 MediaSessionConfig.builder()344 MediaSessionConfig.builder()

345 .model("gpt-live-1")345 .model("gpt-live-1.1")

346 .instructions(346 .instructions(

347 "Be concise. Delegate requests needing current information to the backend, which can search the web.")347 "Be concise. Delegate requests needing current information to the backend, which can search the web.")

348 .responsesDelegation(348 .responsesDelegation(


429 begin429 begin

430 result = client.live.create(430 result = client.live.create(

431 session: {431 session: {

432 model: "gpt-live-1",432 model: "gpt-live-1.1",

433 instructions: "Be concise. Delegate requests needing current information to the backend, which can search the web.",433 instructions: "Be concise. Delegate requests needing current information to the backend, which can search the web.",

434 delegation: {434 delegation: {

435 type: :responses,435 type: :responses,

Details

48 type: "session.start",48 type: "session.start",

49 event_id: "event_start",49 event_id: "event_start",

50 session: {50 session: {

51 model: "gpt-live-1",51 model: "gpt-live-1.1",

52 instructions:52 instructions:

53 "Be concise. Delegate requests needing current information to the backend, which can search the web.",53 "Be concise. Delegate requests needing current information to the backend, which can search the web.",

54 audio: {54 audio: {


143async def main() -> None:143async def main() -> None:

144 # stdin/stdout carry raw mono PCM16 at 24 kHz, not WAV files.144 # stdin/stdout carry raw mono PCM16 at 24 kHz, not WAV files.

145 session: SessionConfigParam = {145 session: SessionConfigParam = {

146 "model": "gpt-live-1",146 "model": "gpt-live-1.1",

147 "instructions": "Be concise. Delegate requests needing current information to the backend, which can search the web.",147 "instructions": "Be concise. Delegate requests needing current information to the backend, which can search the web.",

148 "audio": {148 "audio": {

149 "format": {"type": "audio/pcm", "rate": 24000},149 "format": {"type": "audio/pcm", "rate": 24000},


264 }264 }

265 defer connection.Abort()265 defer connection.Abort()

266 session := live.SessionConfigParam{266 session := live.SessionConfigParam{

267 Model: "gpt-live-1",267 Model: "gpt-live-1.1",

268 Instructions: openai.String("Be concise. Delegate requests needing current information to the backend, which can search the web."),268 Instructions: openai.String("Be concise. Delegate requests needing current information to the backend, which can search the web."),

269 Audio: live.SessionConfigAudioParam{Format: live.AudioFormatParamOfAudioPCM(24000), Output: live.SessionConfigAudioOutputParam{Voice: live.SessionConfigAudioOutputVoiceUnionParam{OfString: openai.String("marin")}}},269 Audio: live.SessionConfigAudioParam{Format: live.AudioFormatParamOfAudioPCM(24000), Output: live.SessionConfigAudioOutputParam{Voice: live.SessionConfigAudioOutputVoiceUnionParam{OfString: openai.String("marin")}}},

270 Delegation: live.SessionConfigDelegationUnionParam{OfResponses: &live.SessionConfigDelegationResponsesParam{Responses: live.ResponsesDelegationConfigParam{270 Delegation: live.SessionConfigDelegationUnionParam{OfResponses: &live.SessionConfigDelegationResponsesParam{Responses: live.ResponsesDelegationConfigParam{


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

408 var session =408 var session =

409 SessionConfig.builder()409 SessionConfig.builder()

410 .model("gpt-live-1")410 .model("gpt-live-1.1")

411 .instructions(411 .instructions(

412 "Be concise. Delegate requests needing current information to the backend, which can search the web.")412 "Be concise. Delegate requests needing current information to the backend, which can search the web.")

413 .audio(413 .audio(


533$stdin.binmode533$stdin.binmode

534$stdout.binmode534$stdout.binmode

535session = {535session = {

536 model: "gpt-live-1",536 model: "gpt-live-1.1",

537 instructions: "Be concise. Delegate requests needing current information to the backend, which can search the web.",537 instructions: "Be concise. Delegate requests needing current information to the backend, which can search the web.",

538 audio: {538 audio: {

539 format: {539 format: {

Details

16 16 

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

18 18 

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

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

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

22 22 


734 raise RuntimeError("Connection closed before the response finished.")734 raise RuntimeError("Connection closed before the response finished.")

735```735```

736 736 

737```go

738package main

739 

740import (

741 "context"

742 "encoding/json"

743 "fmt"

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

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

746 "log"

747 "time"

748)

749 

750func main() {

751 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)

752 defer cancel()

753 client := openai.NewClient()

754 compacted, err := client.Responses.Compact(ctx, responses.ResponseCompactParams{Model: "gpt-6.2-astra", Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: responses.ResponseInputParam{responses.ResponseInputItemParamOfMessage("Find the failing test.", responses.EasyInputMessageRoleUser)}}})

755 if err != nil {

756 log.Fatal(err)

757 }

758 input := responses.ResponseInputParam{}

759 for _, item := range compacted.Output {

760 var converted responses.ResponseInputItemUnion

761 if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {

762 log.Fatal(err)

763 }

764 input = append(input, converted.ToParam())

765 }

766 input = append(input, responses.ResponseInputItemParamOfMessage("Continue from here.", responses.EasyInputMessageRoleUser))

767 conn, err := client.Responses.Connect(ctx, responses.ResponseConnectionOptions{})

768 if err != nil {

769 log.Fatal(err)

770 }

771 defer conn.Close()

772 if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{StreamID: openai.String("main"), Model: "gpt-6.2-astra", Store: openai.Bool(false), Input: responses.ResponsesClientEventResponseCreateInputUnionParam{OfResponse: &input}, Tools: []responses.ToolUnionParam{}}); err != nil {

773 log.Fatal(err)

774 }

775 response, err := conn.FinalResponse(ctx)

776 if err != nil {

777 log.Fatal(err)

778 }

779 if response.Status != responses.ResponseStatusCompleted {

780 log.Fatalf("Response ended with status %s", response.Status)

781 }

782 fmt.Println(response.OutputText())

783}

784```

785 

737```ruby786```ruby

738require "async"787require "async"

739require "openai"788require "openai"


1063 drain_until_complete(connection, {"critic", "planner"})1112 drain_until_complete(connection, {"critic", "planner"})

1064```1113```

1065 1114 

1115```go

1116package main

1117 

1118import (

1119 "context"

1120 "encoding/json"

1121 "fmt"

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

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

1124 "log"

1125 "os"

1126 "time"

1127)

1128 

1129func sendCreate(ctx context.Context, conn *responses.ResponseConnection, lane, text, parent string) error {

1130 input := responses.ResponseInputParam{responses.ResponseInputItemParamOfMessage(text, responses.EasyInputMessageRoleUser)}

1131 command := responses.ResponsesClientEventResponseCreateParam{StreamID: openai.String(lane), Model: "gpt-6.2-astra", Store: openai.Bool(false), Input: responses.ResponsesClientEventResponseCreateInputUnionParam{OfResponse: &input}}

1132 if parent != "" {

1133 command.PreviousResponseID = openai.String(parent)

1134 }

1135 return conn.Create(ctx, command)

1136}

1137func readEvent(ctx context.Context, conn *responses.ResponseConnection) (responses.ResponsesServerEventUnion, error) {

1138 event, err := conn.Recv(ctx)

1139 if err != nil {

1140 return event, err

1141 }

1142 switch event.Type {

1143 case "error", "response.failed", "response.incomplete":

1144 return event, fmt.Errorf("response failed: %s", event.RawJSON())

1145 }

1146 return event, nil

1147}

1148func drainResponses(ctx context.Context, conn *responses.ResponseConnection, latest map[string]string, lanes ...string) error {

1149 remaining := map[string]bool{}

1150 for _, lane := range lanes {

1151 remaining[lane] = true

1152 }

1153 for len(remaining) > 0 {

1154 event, err := readEvent(ctx, conn)

1155 if err != nil {

1156 return err

1157 }

1158 if event.Type != "response.completed" {

1159 continue

1160 }

1161 completed := event.AsResponseCompleted()

1162 if !remaining[completed.StreamID] {

1163 continue

1164 }

1165 latest[completed.StreamID] = completed.Response.ID

1166 delete(remaining, completed.StreamID)

1167 }

1168 return nil

1169}

1170func main() {

1171 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)

1172 defer cancel()

1173 client := openai.NewClient()

1174 conn, err := client.Responses.Connect(ctx, responses.ResponseConnectionOptions{})

1175 if err != nil {

1176 log.Fatal(err)

1177 }

1178 defer conn.Close()

1179 latest := map[string]string{}

1180 if err := sendCreate(ctx, conn, "planner", "Draft a deployment plan for a stateless API service.", ""); err != nil {

1181 log.Fatal(err)

1182 }

1183 if err := sendCreate(ctx, conn, "research", "List common deployment risks for a stateless API service.", ""); err != nil {

1184 log.Fatal(err)

1185 }

1186 if err := drainResponses(ctx, conn, latest, "planner", "research"); err != nil {

1187 log.Fatal(err)

1188 }

1189 parent := latest["planner"]

1190 if err := sendCreate(ctx, conn, "critic", "Find gaps in this deployment plan.", parent); err != nil {

1191 log.Fatal(err)

1192 }

1193 // Let the fork load its parent before advancing the original lane's cache.

1194 for {

1195 event, err := readEvent(ctx, conn)

1196 if err != nil {

1197 log.Fatal(err)

1198 }

1199 if event.Type == "response.in_progress" && event.AsResponseInProgress().StreamID == "critic" {

1200 break

1201 }

1202 }

1203 if err := sendCreate(ctx, conn, "planner", "Add rollback and monitoring steps.", parent); err != nil {

1204 log.Fatal(err)

1205 }

1206 if err := drainResponses(ctx, conn, latest, "critic", "planner"); err != nil {

1207 log.Fatal(err)

1208 }

1209 if err := json.NewEncoder(os.Stdout).Encode(latest); err != nil {

1210 log.Fatal(err)

1211 }

1212}

1213```

1214 

1066```ruby1215```ruby

1067require "async"1216require "async"

1068require "openai"1217require "openai"

libraries.md +1 −1

Details

177<dependency>177<dependency>

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

179 <artifactId>openai-java</artifactId>179 <artifactId>openai-java</artifactId>

180 <version>4.109.0</version>180 <version>4.110.0</version>

181</dependency>181</dependency>

182```182```

183 183 

mcp.md +130 −0

Details

391 main()391 main()

392```392```

393 393 

394```go

395package main

396 

397import (

398 "context"

399 "encoding/json"

400 "errors"

401 "fmt"

402 "github.com/modelcontextprotocol/go-sdk/mcp"

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

404 "log"

405 "net"

406 "net/http"

407 "os"

408 "os/signal"

409 "strings"

410 "syscall"

411 "time"

412)

413 

414type searchInput struct {

415 Query string `json:"query"`

416}

417type searchResult struct {

418 ID string `json:"id"`

419 Title string `json:"title"`

420 URL string `json:"url"`

421}

422type searchOutput struct {

423 Results []searchResult `json:"results"`

424}

425type fetchInput struct {

426 ID string `json:"id"`

427}

428type fetchOutput struct {

429 ID string `json:"id"`

430 Title string `json:"title"`

431 Text string `json:"text"`

432 URL string `json:"url"`

433 Metadata map[string]any `json:"metadata,omitempty"`

434}

435 

436func main() {

437 ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)

438 defer cancel()

439 client := openai.NewClient()

440 // Replace this illustrative ID with your existing document store ID.

441 store := "vs_123"

442 server := mcp.NewServer(&mcp.Implementation{Name: "Sample MCP Server", Version: "1.0.0"}, &mcp.ServerOptions{Instructions: "Search for relevant documents, then fetch complete content with citations."})

443 mcp.AddTool(server, &mcp.Tool{Name: "search", Description: "Search documents and return identities, titles, and citation URLs."}, func(ctx context.Context, _ *mcp.CallToolRequest, input searchInput) (*mcp.CallToolResult, searchOutput, error) {

444 result := searchOutput{Results: []searchResult{}}

445 if strings.TrimSpace(input.Query) == "" {

446 return nil, result, nil

447 }

448 page, err := client.VectorStores.Search(ctx, store, openai.VectorStoreSearchParams{Query: openai.VectorStoreSearchParamsQueryUnion{OfString: openai.String(input.Query)}})

449 if err != nil {

450 return nil, result, err

451 }

452 for _, item := range page.Data {

453 result.Results = append(result.Results, searchResult{ID: item.FileID, Title: item.Filename, URL: "https://platform.openai.com/storage/files/" + item.FileID})

454 }

455 return nil, result, nil

456 })

457 mcp.AddTool(server, &mcp.Tool{Name: "fetch", Description: "Retrieve a complete document with its citation and metadata."}, func(ctx context.Context, _ *mcp.CallToolRequest, input fetchInput) (*mcp.CallToolResult, fetchOutput, error) {

458 if input.ID == "" {

459 return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: "Document ID is required"}}}, fetchOutput{}, nil

460 }

461 content := client.VectorStores.Files.ContentAutoPaging(ctx, store, input.ID)

462 var parts []string

463 for content.Next() {

464 parts = append(parts, content.Current().Text)

465 }

466 if err := content.Err(); err != nil {

467 return nil, fetchOutput{}, err

468 }

469 info, err := client.VectorStores.Files.Get(ctx, store, input.ID)

470 if err != nil {

471 return nil, fetchOutput{}, err

472 }

473 file, err := client.Files.Get(ctx, input.ID)

474 if err != nil {

475 return nil, fetchOutput{}, err

476 }

477 metadata := map[string]any{}

478 for name, value := range info.Attributes {

479 var decoded any

480 if err := json.Unmarshal([]byte(value.RawJSON()), &decoded); err != nil {

481 return nil, fetchOutput{}, err

482 }

483 metadata[name] = decoded

484 }

485 return nil, fetchOutput{ID: input.ID, Title: file.Filename, Text: strings.Join(parts, "\n"), URL: "https://platform.openai.com/storage/files/" + input.ID, Metadata: metadata}, nil

486 })

487 

488 handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})

489 mux := http.NewServeMux()

490 mux.Handle("/mcp", handler)

491 port := "8000"

492 host := "127.0.0.1"

493 listener, err := net.Listen("tcp", net.JoinHostPort(host, port))

494 if err != nil {

495 log.Fatal(err)

496 }

497 httpServer := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}

498 fmt.Println("Listening on http://" + listener.Addr().String())

499 shutdownDone := make(chan struct{})

500 go func() {

501 defer close(shutdownDone)

502 <-ctx.Done()

503 shutdownCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)

504 defer stop()

505 if err := httpServer.Shutdown(shutdownCtx); err != nil {

506 log.Print(err)

507 }

508 }()

509 if err := httpServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {

510 log.Fatal(err)

511 }

512 <-shutdownDone

513}

514```

515 

394```ruby516```ruby

395require "openai"517require "openai"

396require "mcp"518require "mcp"


556 678 

557 679 

558 680 

681For Go, use Go 1.26 or later with `github.com/openai/openai-go/v3` and `github.com/modelcontextprotocol/go-sdk@v1.8.0`. Set `OPENAI_API_KEY`, replace the illustrative `vs_123` value with your existing vector store ID, save the source as `main.go` in your module, and run `go run .`. The server uses Streamable HTTP at `/mcp` on port 8000. Edit the `port` literal to use another port and the `host` literal to bind the server to `0.0.0.0` on Replit.

682 

683 

684 

685 

686 

687 

688 

559 689 

560## Test and connect your MCP server690## Test and connect your MCP server

561 691 

models.md +1 −0

Details

49- [GPT-Image-2.6 Flare](/api/docs/models/gpt-image-2.6-flare.md): Image generation and editing for fast iteration49- [GPT-Image-2.6 Flare](/api/docs/models/gpt-image-2.6-flare.md): Image generation and editing for fast iteration

50- [GPT-Image-2.6 Sunburst](/api/docs/models/gpt-image-2.6-sunburst.md): Image generation and editing for detailed visual work50- [GPT-Image-2.6 Sunburst](/api/docs/models/gpt-image-2.6-sunburst.md): Image generation and editing for detailed visual work

51- [GPT-Live-1](/api/docs/models/gpt-live-1.md): Our premier model for natural, expressive voice conversations with smooth interruption handling.51- [GPT-Live-1](/api/docs/models/gpt-live-1.md): Our premier model for natural, expressive voice conversations with smooth interruption handling.

52- [GPT-Live-1.1](/api/docs/models/gpt-live-1.1.md): Full-duplex voice model for multilingual conversations.

52- [GPT-Live-Transcribe](/api/docs/models/gpt-live-transcribe.md): Low-latency speech-to-text model for realtime transcription53- [GPT-Live-Transcribe](/api/docs/models/gpt-live-transcribe.md): Low-latency speech-to-text model for realtime transcription

53- [gpt-oss-120b](/api/docs/models/gpt-oss-120b.md): Most powerful open-weight model, fits into an H100 GPU54- [gpt-oss-120b](/api/docs/models/gpt-oss-120b.md): Most powerful open-weight model, fits into an H100 GPU

54- [gpt-oss-20b](/api/docs/models/gpt-oss-20b.md): Medium-sized open-weight model for low latency55- [gpt-oss-20b](/api/docs/models/gpt-oss-20b.md): Medium-sized open-weight model for low latency

models/all.md +1 −0

Details

28 28 

29Models for realtime, speech, and audio workflows.29Models for realtime, speech, and audio workflows.

30 30 

31- [GPT-Live-1.1](/api/docs/models/gpt-live-1.1.md): Full-duplex voice model for multilingual conversations.

31- [GPT-Live-1](/api/docs/models/gpt-live-1.md): Our premier model for natural, expressive voice conversations with smooth interruption handling.32- [GPT-Live-1](/api/docs/models/gpt-live-1.md): Our premier model for natural, expressive voice conversations with smooth interruption handling.

32- [GPT-Realtime-2.1](/api/docs/models/gpt-realtime-2.1.md): Reasoning model with tool use33- [GPT-Realtime-2.1](/api/docs/models/gpt-realtime-2.1.md): Reasoning model with tool use

33- [GPT-Realtime-2.1 mini](/api/docs/models/gpt-realtime-2.1-mini.md): Reasoning model with tool use34- [GPT-Realtime-2.1 mini](/api/docs/models/gpt-realtime-2.1-mini.md): Reasoning model with tool use

quickstart.md +1 −1

Details

187<dependency>187<dependency>

188 <groupId>com.openai</groupId>188 <groupId>com.openai</groupId>

189 <artifactId>openai-java</artifactId>189 <artifactId>openai-java</artifactId>

190 <version>4.109.0</version>190 <version>4.110.0</version>

191</dependency>191</dependency>

192```192```

193 193 

Details

19 19 

20 20 

21 21 

22The Go examples use `github.com/openai/openai-go/v3` at `v3.98.0`, `github.com/tiktoken-go/tokenizer` at `v0.10.0`, and `golang.org/x/net/html` at `v0.63.0`. Use the complete programs in the [Go tutorial sample directory](https://github.com/openai/developers-website/tree/main/src/content/platform/go-examples/tutorial-crawl-website-embeddings). When running downloaded source files, replace `{{MODEL}}` with the model shown in the rendered example. Run each workflow step separately from the same working directory; don't concatenate their `main` functions. The hyperlink helpers share one program, and context retrieval, answering, and test questions share another.

23 

24Replace `https://example.com` with your website's URL in the crawler, hyperlink, and scraped-data programs. Set `OPENAI_API_KEY` before the API steps. The Go crawler follows same-domain redirects and writes files under `text`; subsequent programs read and write `processed/scraped.csv`, `processed/chunks.json`, and `processed/embeddings.csv` in order. The histogram steps write `token-histogram.png` locally.

25 

26 

27 

28 

29 

30 

31 

22For Ruby, use Ruby 3.3 with the `openai`, `nokogiri`, `tiktoken_ruby`, and `chunky_png` gems. The [sample dependencies](https://github.com/openai/developers-website/blob/main/src/content/platform/ruby-examples/Gemfile) list tested versions.32For Ruby, use Ruby 3.3 with the `openai`, `nokogiri`, `tiktoken_ruby`, and `chunky_png` gems. The [sample dependencies](https://github.com/openai/developers-website/blob/main/src/content/platform/ruby-examples/Gemfile) list tested versions.

23 33 

24 34 


99 self.hyperlinks.append(attrs["href"])109 self.hyperlinks.append(attrs["href"])

100```110```

101 111 

112```go

113package main

114 

115import (

116 "encoding/json"

117 "fmt"

118 "golang.org/x/net/html"

119 "io"

120 "os"

121 "strings"

122)

123 

124func parseHTML(body io.Reader) ([]string, string, error) {

125 document, err := html.Parse(body)

126 if err != nil {

127 return nil, "", err

128 }

129 links := []string{}

130 var text strings.Builder

131 var visit func(*html.Node)

132 visit = func(node *html.Node) {

133 if node.Type == html.ElementNode && (node.Data == "script" || node.Data == "style") {

134 return

135 }

136 if node.Type == html.TextNode {

137 text.WriteString(node.Data)

138 }

139 if node.Type == html.ElementNode && node.Data == "a" {

140 for _, attribute := range node.Attr {

141 if attribute.Key == "href" {

142 links = append(links, attribute.Val)

143 }

144 }

145 }

146 for child := node.FirstChild; child != nil; child = child.NextSibling {

147 visit(child)

148 }

149 }

150 visit(document)

151 return links, text.String(), nil

152}

153 

154func main() {

155 links, _, err := parseHTML(os.Stdin)

156 if err == nil {

157 err = json.NewEncoder(os.Stdout).Encode(links)

158 }

159 if err != nil {

160 fmt.Fprintln(os.Stderr, err)

161 os.Exit(1)

162 }

163}

164```

165 

102```ruby166```ruby

103require "net/http"167require "net/http"

104require "uri"168require "uri"


149 return parser.hyperlinks213 return parser.hyperlinks

150```214```

151 215 

216```go

217func parseHTML(body io.Reader) ([]string, string, error) {

218 document, err := html.Parse(body)

219 if err != nil {

220 return nil, "", err

221 }

222 links := []string{}

223 var text strings.Builder

224 var visit func(*html.Node)

225 visit = func(node *html.Node) {

226 if node.Type == html.ElementNode && (node.Data == "script" || node.Data == "style") {

227 return

228 }

229 if node.Type == html.TextNode {

230 text.WriteString(node.Data)

231 }

232 if node.Type == html.ElementNode && node.Data == "a" {

233 for _, attribute := range node.Attr {

234 if attribute.Key == "href" {

235 links = append(links, attribute.Val)

236 }

237 }

238 }

239 for child := node.FirstChild; child != nil; child = child.NextSibling {

240 visit(child)

241 }

242 }

243 visit(document)

244 return links, text.String(), nil

245}

246func validURL(value *url.URL) bool {

247 return (value.Scheme == "http" || value.Scheme == "https") && value.Host != "" && value.User == nil

248}

249func fetchPage(ctx context.Context, address, domain string) (*url.URL, []string, string, error) {

250 initial, err := url.Parse(address)

251 if err != nil {

252 return nil, nil, "", err

253 }

254 if !validURL(initial) || initial.Host != domain {

255 return nil, nil, "", fmt.Errorf("expected a same-domain HTTP or HTTPS URL")

256 }

257 client := &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(request *http.Request, via []*http.Request) error {

258 if !validURL(request.URL) || request.URL.Host != domain {

259 return fmt.Errorf("expected a same-domain HTTP or HTTPS URL")

260 }

261 if len(via) > 5 {

262 return fmt.Errorf("Too many redirects")

263 }

264 request.URL.Fragment = ""

265 return nil

266 }}

267 request, err := http.NewRequestWithContext(ctx, http.MethodGet, initial.String(), nil)

268 if err != nil {

269 return nil, nil, "", err

270 }

271 response, err := client.Do(request)

272 if err != nil {

273 return nil, nil, "", err

274 }

275 defer response.Body.Close()

276 mediaType, _, _ := mime.ParseMediaType(response.Header.Get("Content-Type"))

277 if response.StatusCode < 200 || response.StatusCode >= 300 || mediaType != "text/html" {

278 // A nil final URL marks an HTTP error or non-HTML response to skip.

279 return nil, nil, "", nil

280 }

281 // Bound each downloaded page before parsing it.

282 body, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1))

283 if err != nil {

284 return nil, nil, "", err

285 }

286 if len(body) > 8<<20 {

287 return nil, nil, "", fmt.Errorf("HTML page exceeds 8 MiB")

288 }

289 links, text, err := parseHTML(bytes.NewReader(body))

290 return response.Request.URL, links, text, err

291}

292func getHyperlinks(ctx context.Context, address string) ([]string, error) {

293 initial, err := url.Parse(address)

294 if err != nil {

295 return nil, err

296 }

297 final, links, _, err := fetchPage(ctx, address, initial.Host)

298 if err != nil {

299 return nil, err

300 }

301 if final == nil {

302 return []string{}, nil

303 }

304 resolved := []string{}

305 for _, link := range links {

306 if link == "" || strings.HasPrefix(link, "#") {

307 continue

308 }

309 relative, err := url.Parse(link)

310 if err != nil {

311 continue

312 }

313 resolved = append(resolved, final.ResolveReference(relative).String())

314 }

315 return resolved, nil

316}

317```

318 

152```ruby319```ruby

153def fetch_page(url, local_domain = nil)320def fetch_page(url, local_domain = nil)

154 uri = URI.parse(url)321 uri = URI.parse(url)


217 return list(links)384 return list(links)

218```385```

219 386 

387```go

388func getDomainHyperlinks(ctx context.Context, domain, address string) ([]string, error) {

389 links, err := getHyperlinks(ctx, address)

390 if err != nil {

391 return nil, err

392 }

393 result := []string{}

394 seen := map[string]bool{}

395 for _, link := range links {

396 candidate, err := url.Parse(link)

397 if err != nil || !validURL(candidate) || candidate.Host != domain {

398 continue

399 }

400 candidate.Fragment = ""

401 normalized := candidate.String()

402 if !seen[normalized] {

403 seen[normalized] = true

404 result = append(result, normalized)

405 }

406 }

407 return result, nil

408}

409func crawlURL() string {

410 return "https://example.com"

411}

412func main() {

413 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)

414 defer cancel()

415 address := crawlURL()

416 initial, err := url.Parse(address)

417 if err != nil {

418 log.Fatal(err)

419 }

420 links, err := getDomainHyperlinks(ctx, initial.Host, address)

421 if err != nil {

422 log.Fatal(err)

423 }

424 if err := json.NewEncoder(os.Stdout).Encode(links); err != nil {

425 log.Fatal(err)

426 }

427}

428```

429 

220```ruby430```ruby

221def get_domain_hyperlinks(local_domain, url)431def get_domain_hyperlinks(local_domain, url)

222 get_hyperlinks(url).filter_map do |link|432 get_hyperlinks(url).filter_map do |link|


313crawl(full_url)523crawl(full_url)

314```524```

315 525 

526```go

527package main

528 

529import (

530 "bytes"

531 "context"

532 "crypto/sha256"

533 "fmt"

534 "golang.org/x/net/html"

535 "io"

536 "log"

537 "mime"

538 "net/http"

539 "net/url"

540 "os"

541 "path/filepath"

542 "strings"

543 "time"

544)

545 

546func parseHTML(body io.Reader) ([]string, string, error) {

547 document, err := html.Parse(body)

548 if err != nil {

549 return nil, "", err

550 }

551 links := []string{}

552 var text strings.Builder

553 var visit func(*html.Node)

554 visit = func(node *html.Node) {

555 if node.Type == html.ElementNode && (node.Data == "script" || node.Data == "style") {

556 return

557 }

558 if node.Type == html.TextNode {

559 text.WriteString(node.Data)

560 }

561 if node.Type == html.ElementNode && node.Data == "a" {

562 for _, attribute := range node.Attr {

563 if attribute.Key == "href" {

564 links = append(links, attribute.Val)

565 }

566 }

567 }

568 for child := node.FirstChild; child != nil; child = child.NextSibling {

569 visit(child)

570 }

571 }

572 visit(document)

573 return links, text.String(), nil

574}

575func validURL(value *url.URL) bool {

576 return (value.Scheme == "http" || value.Scheme == "https") && value.Host != "" && value.User == nil

577}

578func fetchPage(ctx context.Context, address, domain string) (*url.URL, []string, string, error) {

579 initial, err := url.Parse(address)

580 if err != nil {

581 return nil, nil, "", err

582 }

583 if !validURL(initial) || initial.Host != domain {

584 return nil, nil, "", fmt.Errorf("expected a same-domain HTTP or HTTPS URL")

585 }

586 client := &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(request *http.Request, via []*http.Request) error {

587 if !validURL(request.URL) || request.URL.Host != domain {

588 return fmt.Errorf("expected a same-domain HTTP or HTTPS URL")

589 }

590 if len(via) > 5 {

591 return fmt.Errorf("Too many redirects")

592 }

593 request.URL.Fragment = ""

594 return nil

595 }}

596 request, err := http.NewRequestWithContext(ctx, http.MethodGet, initial.String(), nil)

597 if err != nil {

598 return nil, nil, "", err

599 }

600 response, err := client.Do(request)

601 if err != nil {

602 return nil, nil, "", err

603 }

604 defer response.Body.Close()

605 mediaType, _, _ := mime.ParseMediaType(response.Header.Get("Content-Type"))

606 if response.StatusCode < 200 || response.StatusCode >= 300 || mediaType != "text/html" {

607 // A nil final URL marks an HTTP error or non-HTML response to skip.

608 return nil, nil, "", nil

609 }

610 // Bound each downloaded page before parsing it.

611 body, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1))

612 if err != nil {

613 return nil, nil, "", err

614 }

615 if len(body) > 8<<20 {

616 return nil, nil, "", fmt.Errorf("HTML page exceeds 8 MiB")

617 }

618 links, text, err := parseHTML(bytes.NewReader(body))

619 return response.Request.URL, links, text, err

620}

621func getHyperlinks(ctx context.Context, address string) ([]string, error) {

622 initial, err := url.Parse(address)

623 if err != nil {

624 return nil, err

625 }

626 final, links, _, err := fetchPage(ctx, address, initial.Host)

627 if err != nil {

628 return nil, err

629 }

630 if final == nil {

631 return []string{}, nil

632 }

633 resolved := []string{}

634 for _, link := range links {

635 if link == "" || strings.HasPrefix(link, "#") {

636 continue

637 }

638 relative, err := url.Parse(link)

639 if err != nil {

640 continue

641 }

642 resolved = append(resolved, final.ResolveReference(relative).String())

643 }

644 return resolved, nil

645}

646func getDomainHyperlinks(ctx context.Context, domain, address string) ([]string, error) {

647 links, err := getHyperlinks(ctx, address)

648 if err != nil {

649 return nil, err

650 }

651 result := []string{}

652 seen := map[string]bool{}

653 for _, link := range links {

654 candidate, err := url.Parse(link)

655 if err != nil || !validURL(candidate) || candidate.Host != domain {

656 continue

657 }

658 candidate.Fragment = ""

659 normalized := candidate.String()

660 if !seen[normalized] {

661 seen[normalized] = true

662 result = append(result, normalized)

663 }

664 }

665 return result, nil

666}

667func crawlURL() string {

668 return "https://example.com"

669}

670func crawl(ctx context.Context, address string) error {

671 initial, err := url.Parse(address)

672 if err != nil {

673 return err

674 }

675 if !validURL(initial) {

676 return fmt.Errorf("expected an HTTP or HTTPS URL")

677 }

678 initial.Fragment = ""

679 if initial.Path == "" {

680 initial.Path = "/"

681 }

682 directory := filepath.Join("text", initial.Host)

683 if err := os.MkdirAll(directory, 0700); err != nil {

684 return err

685 }

686 if err := os.MkdirAll("processed", 0700); err != nil {

687 return err

688 }

689 queue := []string{initial.String()}

690 seen := map[string]bool{initial.String(): true}

691 for len(queue) > 0 {

692 current := queue[len(queue)-1]

693 queue = queue[:len(queue)-1]

694 final, links, text, err := fetchPage(ctx, current, initial.Host)

695 if err != nil {

696 return err

697 }

698 if final == nil {

699 continue

700 }

701 final.Fragment = ""

702 if final.String() != current && seen[final.String()] {

703 continue

704 }

705 seen[final.String()] = true

706 fmt.Println(final.String())

707 name := strings.ReplaceAll(initial.Host+final.EscapedPath(), "/", "_")

708 // Include the complete URL so paths such as /a/b and /a_b stay distinct.

709 suffix := fmt.Sprintf("#%x", sha256.Sum256([]byte(final.String())))

710 limit := 255 - len(suffix) - len(".txt")

711 if len(name) > limit {

712 name = name[:limit]

713 }

714 name += suffix

715 if err := os.WriteFile(filepath.Join(directory, name+".txt"), []byte(text), 0600); err != nil {

716 return err

717 }

718 for _, link := range links {

719 if link == "" || strings.HasPrefix(link, "#") {

720 continue

721 }

722 relative, err := url.Parse(link)

723 if err != nil {

724 continue

725 }

726 candidate := final.ResolveReference(relative)

727 candidate.Fragment = ""

728 if !validURL(candidate) || candidate.Host != initial.Host || seen[candidate.String()] {

729 continue

730 }

731 seen[candidate.String()] = true

732 queue = append(queue, candidate.String())

733 }

734 }

735 return nil

736}

737func main() {

738 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)

739 defer cancel()

740 if err := crawl(ctx, crawlURL()); err != nil {

741 log.Fatal(err)

742 }

743}

744```

745 

316```ruby746```ruby

317def crawl(full_url)747def crawl(full_url)

318 initial = URI.parse(full_url)748 initial = URI.parse(full_url)


392 return serie822 return serie

393```823```

394 824 

825```go

826package main

827 

828import (

829 "encoding/json"

830 "fmt"

831 "os"

832 "strings"

833)

834 

835func removeNewlines(texts []string) []string {

836 result := make([]string, len(texts))

837 for i, text := range texts {

838 text = strings.ReplaceAll(text, "\n", " ")

839 text = strings.ReplaceAll(text, `\n`, " ")

840 text = strings.ReplaceAll(text, " ", " ")

841 result[i] = strings.ReplaceAll(text, " ", " ")

842 }

843 return result

844}

845func main() {

846 var texts []string

847 err := json.NewDecoder(os.Stdin).Decode(&texts)

848 if err == nil {

849 err = json.NewEncoder(os.Stdout).Encode(removeNewlines(texts))

850 }

851 if err != nil {

852 fmt.Fprintln(os.Stderr, err)

853 os.Exit(1)

854 }

855}

856```

857 

395```ruby858```ruby

396def remove_newlines(texts)859def remove_newlines(texts)

397 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }860 texts.map { |text| text.tr("\n", " ").gsub('\n', " ").gsub(" ", " ").gsub(" ", " ") }


446df.head()909df.head()

447```910```

448 911 

912```go

913package main

914 

915import (

916 "encoding/csv"

917 "encoding/hex"

918 "encoding/json"

919 "fmt"

920 "log"

921 "net/url"

922 "os"

923 "path/filepath"

924 "strings"

925)

926 

927func removeNewlines(texts []string) []string {

928 result := make([]string, len(texts))

929 for i, text := range texts {

930 text = strings.ReplaceAll(text, "\n", " ")

931 text = strings.ReplaceAll(text, `\n`, " ")

932 text = strings.ReplaceAll(text, " ", " ")

933 result[i] = strings.ReplaceAll(text, " ", " ")

934 }

935 return result

936}

937 

938func main() {

939 address := "https://example.com"

940 initial, err := url.Parse(address)

941 if err != nil {

942 log.Fatal(err)

943 }

944 if (initial.Scheme != "http" && initial.Scheme != "https") || initial.Host == "" || initial.User != nil {

945 log.Fatal("expected an HTTP or HTTPS URL")

946 }

947 directory := filepath.Join("text", initial.Host)

948 entries, err := os.ReadDir(directory)

949 if err != nil {

950 log.Fatal(err)

951 }

952 rows := []map[string]string{}

953 for _, entry := range entries {

954 if !entry.Type().IsRegular() || filepath.Ext(entry.Name()) != ".txt" {

955 continue

956 }

957 title := strings.TrimSuffix(entry.Name(), ".txt")

958 // The crawler's URL digest prevents filename collisions, but isn't a page title.

959 if i := strings.LastIndex(title, "#"); i >= 0 && len(title)-i == 65 {

960 if _, err := hex.DecodeString(title[i+1:]); err == nil {

961 title = title[:i]

962 }

963 }

964 if title == initial.Host || title == initial.Host+"_" {

965 title = "index"

966 } else {

967 title = strings.TrimPrefix(title, initial.Host+"_")

968 }

969 title = strings.NewReplacer("-", " ", "_", " ", "#update", "").Replace(title)

970 data, err := os.ReadFile(filepath.Join(directory, entry.Name()))

971 if err != nil {

972 log.Fatal(err)

973 }

974 text := removeNewlines([]string{string(data)})[0]

975 rows = append(rows, map[string]string{"fname": title, "text": fmt.Sprintf("%s. %s", title, text)})

976 }

977 if err := os.MkdirAll("processed", 0700); err != nil {

978 log.Fatal(err)

979 }

980 file, err := os.Create("processed/scraped.csv")

981 if err != nil {

982 log.Fatal(err)

983 }

984 records := [][]string{{"fname", "text"}}

985 for _, row := range rows {

986 records = append(records, []string{row["fname"], row["text"]})

987 }

988 if err := csv.NewWriter(file).WriteAll(records); err != nil {

989 file.Close()

990 log.Fatal(err)

991 }

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

993 log.Fatal(err)

994 }

995 if err := json.NewEncoder(os.Stdout).Encode(rows); err != nil {

996 log.Fatal(err)

997 }

998}

999```

1000 

449```ruby1001```ruby

450require "csv"1002require "csv"

451require "fileutils"1003require "fileutils"


504df.n_tokens.hist()1056df.n_tokens.hist()

505```1057```

506 1058 

1059```go

1060package main

1061 

1062import (

1063 "encoding/csv"

1064 "encoding/json"

1065 "fmt"

1066 "github.com/tiktoken-go/tokenizer"

1067 "image"

1068 "image/color"

1069 "image/draw"

1070 "image/png"

1071 "io"

1072 "log"

1073 "os"

1074 "slices"

1075)

1076 

1077func readTexts(path string) ([]string, error) {

1078 file, err := os.Open(path)

1079 if err != nil {

1080 return nil, err

1081 }

1082 defer file.Close()

1083 reader := csv.NewReader(file)

1084 header, err := reader.Read()

1085 if err != nil {

1086 return nil, err

1087 }

1088 column := -1

1089 for i, name := range header {

1090 if name == "text" {

1091 column = i

1092 }

1093 }

1094 if column < 0 {

1095 return nil, fmt.Errorf("missing text column")

1096 }

1097 texts := []string{}

1098 for {

1099 record, err := reader.Read()

1100 if err == io.EOF {

1101 break

1102 }

1103 if err != nil {

1104 return nil, err

1105 }

1106 texts = append(texts, record[column])

1107 }

1108 return texts, nil

1109}

1110func histogram(texts []string) error {

1111 codec, err := tokenizer.Get(tokenizer.Cl100kBase)

1112 if err != nil {

1113 return err

1114 }

1115 counts := make([]int, len(texts))

1116 frequencies := map[int]int{}

1117 for i, text := range texts {

1118 ids, _, err := codec.Encode(text)

1119 if err != nil {

1120 return err

1121 }

1122 counts[i] = len(ids)

1123 frequencies[counts[i]]++

1124 }

1125 keys := []int{}

1126 maximum := 1

1127 total := 0

1128 for count, frequency := range frequencies {

1129 keys = append(keys, count)

1130 maximum = max(maximum, frequency)

1131 total += frequency

1132 }

1133 slices.Sort(keys)

1134 plot := image.NewRGBA(image.Rect(0, 0, 600, 400))

1135 draw.Draw(plot, plot.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)

1136 for i, count := range keys {

1137 left := 20 + i*560/len(keys)

1138 right := 20 + (i+1)*560/len(keys)

1139 top := 380 - frequencies[count]*360/maximum

1140 draw.Draw(plot, image.Rect(left, top, right, 381), image.NewUniform(color.RGBA{0, 100, 0, 255}), image.Point{}, draw.Src)

1141 }

1142 file, err := os.Create("token-histogram.png")

1143 if err != nil {

1144 return err

1145 }

1146 if err := png.Encode(file, plot); err != nil {

1147 file.Close()

1148 return err

1149 }

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

1151 return err

1152 }

1153 return json.NewEncoder(os.Stdout).Encode(map[string]any{"counts": counts, "histogram_total": total})

1154}

1155func main() {

1156 texts, err := readTexts("processed/scraped.csv")

1157 if err != nil {

1158 log.Fatal(err)

1159 }

1160 if err := histogram(texts); err != nil {

1161 log.Fatal(err)

1162 }

1163}

1164```

1165 

507```ruby1166```ruby

508require "csv"1167require "csv"

509require "tiktoken_ruby"1168require "tiktoken_ruby"


593 shortened.append(row[1]["text"])1252 shortened.append(row[1]["text"])

594```1253```

595 1254 

1255```go

1256package main

1257 

1258import (

1259 "encoding/csv"

1260 "encoding/json"

1261 "fmt"

1262 "github.com/tiktoken-go/tokenizer"

1263 "io"

1264 "log"

1265 "os"

1266 "strings"

1267)

1268 

1269func readTexts(path string) ([]string, error) {

1270 file, err := os.Open(path)

1271 if err != nil {

1272 return nil, err

1273 }

1274 defer file.Close()

1275 reader := csv.NewReader(file)

1276 header, err := reader.Read()

1277 if err != nil {

1278 return nil, err

1279 }

1280 column := -1

1281 for i, name := range header {

1282 if name == "text" {

1283 column = i

1284 }

1285 }

1286 if column < 0 {

1287 return nil, fmt.Errorf("missing text column")

1288 }

1289 texts := []string{}

1290 for {

1291 record, err := reader.Read()

1292 if err == io.EOF {

1293 break

1294 }

1295 if err != nil {

1296 return nil, err

1297 }

1298 texts = append(texts, record[column])

1299 }

1300 return texts, nil

1301}

1302func splitIntoMany(text string, maxTokens int) ([]string, error) {

1303 if maxTokens <= 0 {

1304 return nil, fmt.Errorf("maxTokens must be positive")

1305 }

1306 chunks := []string{}

1307 if strings.TrimSpace(text) == "" {

1308 return chunks, nil

1309 }

1310 codec, err := tokenizer.Get(tokenizer.Cl100kBase)

1311 if err != nil {

1312 return nil, err

1313 }

1314 sentences := strings.Split(text, ". ")

1315 chunk := ""

1316 for i, sentence := range sentences {

1317 if i < len(sentences)-1 {

1318 sentence += "."

1319 }

1320 ids, _, err := codec.Encode(sentence)

1321 if err != nil {

1322 return nil, err

1323 }

1324 if len(ids) > maxTokens {

1325 return nil, fmt.Errorf("a sentence exceeds maxTokens; split it before chunking")

1326 }

1327 candidate := sentence

1328 if chunk != "" {

1329 candidate = chunk + " " + sentence

1330 }

1331 ids, _, err = codec.Encode(candidate)

1332 if err != nil {

1333 return nil, err

1334 }

1335 if len(ids) > maxTokens {

1336 chunks = append(chunks, chunk)

1337 chunk = sentence

1338 } else {

1339 chunk = candidate

1340 }

1341 }

1342 if chunk != "" {

1343 chunks = append(chunks, chunk)

1344 }

1345 return chunks, nil

1346}

1347 

1348func main() {

1349 texts, err := readTexts("processed/scraped.csv")

1350 if err != nil {

1351 log.Fatal(err)

1352 }

1353 chunks := []string{}

1354 for _, text := range texts {

1355 parts, err := splitIntoMany(text, 500)

1356 if err != nil {

1357 log.Fatal(err)

1358 }

1359 chunks = append(chunks, parts...)

1360 }

1361 data, err := json.Marshal(chunks)

1362 if err != nil {

1363 log.Fatal(err)

1364 }

1365 if err := os.WriteFile("processed/chunks.json", data, 0600); err != nil {

1366 log.Fatal(err)

1367 }

1368}

1369```

1370 

596```ruby1371```ruby

597require "csv"1372require "csv"

598require "json"1373require "json"


642df.n_tokens.hist()1417df.n_tokens.hist()

643```1418```

644 1419 

1420```go

1421package main

1422 

1423import (

1424 "encoding/json"

1425 "github.com/tiktoken-go/tokenizer"

1426 "image"

1427 "image/color"

1428 "image/draw"

1429 "image/png"

1430 "log"

1431 "os"

1432 "slices"

1433)

1434 

1435func histogram(texts []string) error {

1436 codec, err := tokenizer.Get(tokenizer.Cl100kBase)

1437 if err != nil {

1438 return err

1439 }

1440 counts := make([]int, len(texts))

1441 frequencies := map[int]int{}

1442 for i, text := range texts {

1443 ids, _, err := codec.Encode(text)

1444 if err != nil {

1445 return err

1446 }

1447 counts[i] = len(ids)

1448 frequencies[counts[i]]++

1449 }

1450 keys := []int{}

1451 maximum := 1

1452 total := 0

1453 for count, frequency := range frequencies {

1454 keys = append(keys, count)

1455 maximum = max(maximum, frequency)

1456 total += frequency

1457 }

1458 slices.Sort(keys)

1459 plot := image.NewRGBA(image.Rect(0, 0, 600, 400))

1460 draw.Draw(plot, plot.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)

1461 for i, count := range keys {

1462 left := 20 + i*560/len(keys)

1463 right := 20 + (i+1)*560/len(keys)

1464 top := 380 - frequencies[count]*360/maximum

1465 draw.Draw(plot, image.Rect(left, top, right, 381), image.NewUniform(color.RGBA{0, 100, 0, 255}), image.Point{}, draw.Src)

1466 }

1467 file, err := os.Create("token-histogram.png")

1468 if err != nil {

1469 return err

1470 }

1471 if err := png.Encode(file, plot); err != nil {

1472 file.Close()

1473 return err

1474 }

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

1476 return err

1477 }

1478 return json.NewEncoder(os.Stdout).Encode(map[string]any{"counts": counts, "histogram_total": total})

1479}

1480func main() {

1481 data, err := os.ReadFile("processed/chunks.json")

1482 if err != nil {

1483 log.Fatal(err)

1484 }

1485 var texts []string

1486 if err := json.Unmarshal(data, &texts); err != nil {

1487 log.Fatal(err)

1488 }

1489 if err := histogram(texts); err != nil {

1490 log.Fatal(err)

1491 }

1492}

1493```

1494 

645```ruby1495```ruby

646require "json"1496require "json"

647require "tiktoken_ruby"1497require "tiktoken_ruby"


696df.head()1546df.head()

697```1547```

698 1548 

1549```go

1550package main

1551 

1552import (

1553 "context"

1554 "encoding/csv"

1555 "encoding/json"

1556 "fmt"

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

1558 "log"

1559 "os"

1560 "strconv"

1561 "time"

1562)

1563 

1564func run() error {

1565 data, err := os.ReadFile("processed/chunks.json")

1566 if err != nil {

1567 return err

1568 }

1569 var texts []string

1570 if err := json.Unmarshal(data, &texts); err != nil {

1571 return err

1572 }

1573 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)

1574 defer cancel()

1575 client := openai.NewClient()

1576 records := [][]string{{"text", "n_tokens", "embeddings"}}

1577 for _, text := range texts {

1578 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{Model: "text-embedding-3-small", Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)}})

1579 if err != nil {

1580 return err

1581 }

1582 if len(response.Data) != 1 || response.Data[0].Index != 0 || len(response.Data[0].Embedding) == 0 {

1583 return fmt.Errorf("expected one embedding")

1584 }

1585 vector, err := json.Marshal(response.Data[0].Embedding)

1586 if err != nil {

1587 return err

1588 }

1589 records = append(records, []string{text, strconv.FormatInt(response.Usage.PromptTokens, 10), string(vector)})

1590 }

1591 if err := os.MkdirAll("processed", 0700); err != nil {

1592 return err

1593 }

1594 file, err := os.Create("processed/embeddings.csv")

1595 if err != nil {

1596 return err

1597 }

1598 if err := csv.NewWriter(file).WriteAll(records); err != nil {

1599 file.Close()

1600 return err

1601 }

1602 return file.Close()

1603}

1604func main() {

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

1606 log.Fatal(err)

1607 }

1608}

1609```

1610 

699```ruby1611```ruby

700require "openai"1612require "openai"

701require "csv"1613require "csv"


750df.head()1662df.head()

751```1663```

752 1664 

1665```go

1666package main

1667 

1668import (

1669 "encoding/csv"

1670 "encoding/json"

1671 "fmt"

1672 "io"

1673 "log"

1674 "os"

1675)

1676 

1677type embeddedRow struct {

1678 Text string

1679 Embedding []float64

1680}

1681 

1682func loadEmbeddings(path string) ([]embeddedRow, error) {

1683 file, err := os.Open(path)

1684 if err != nil {

1685 return nil, err

1686 }

1687 defer file.Close()

1688 reader := csv.NewReader(file)

1689 header, err := reader.Read()

1690 if err != nil {

1691 return nil, err

1692 }

1693 columns := map[string]int{}

1694 for i, name := range header {

1695 columns[name] = i

1696 }

1697 for _, name := range []string{"text", "embeddings"} {

1698 if _, ok := columns[name]; !ok {

1699 return nil, fmt.Errorf("missing %s column", name)

1700 }

1701 }

1702 rows := []embeddedRow{}

1703 dimensions := 0

1704 for {

1705 record, err := reader.Read()

1706 if err == io.EOF {

1707 break

1708 }

1709 if err != nil {

1710 return nil, err

1711 }

1712 row := embeddedRow{Text: record[columns["text"]]}

1713 if err := json.Unmarshal([]byte(record[columns["embeddings"]]), &row.Embedding); err != nil {

1714 return nil, err

1715 }

1716 if len(row.Embedding) == 0 {

1717 return nil, fmt.Errorf("empty embedding")

1718 }

1719 if dimensions == 0 {

1720 dimensions = len(row.Embedding)

1721 }

1722 if len(row.Embedding) != dimensions {

1723 return nil, fmt.Errorf("inconsistent embedding dimensions")

1724 }

1725 rows = append(rows, row)

1726 }

1727 if len(rows) == 0 {

1728 return nil, fmt.Errorf("no embeddings")

1729 }

1730 return rows, nil

1731}

1732func main() {

1733 rows, err := loadEmbeddings("processed/embeddings.csv")

1734 if err != nil {

1735 log.Fatal(err)

1736 }

1737 if err := json.NewEncoder(os.Stdout).Encode(rows[0].Embedding); err != nil {

1738 log.Fatal(err)

1739 }

1740}

1741```

1742 

753```ruby1743```ruby

754require "csv"1744require "csv"

755require "json"1745require "json"


810 return "\n\n###\n\n".join(returns)1800 return "\n\n###\n\n".join(returns)

811```1801```

812 1802 

1803```go

1804import (

1805 "context"

1806 "encoding/csv"

1807 "encoding/json"

1808 "fmt"

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

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

1811 "io"

1812 "log"

1813 "math"

1814 "os"

1815 "sort"

1816 "strconv"

1817 "strings"

1818 "time"

1819)

1820 

1821type embeddedRow struct {

1822 Text string

1823 NTokens int

1824 Embedding []float64

1825}

1826 

1827func loadEmbeddings(path string) ([]embeddedRow, error) {

1828 file, err := os.Open(path)

1829 if err != nil {

1830 return nil, err

1831 }

1832 defer file.Close()

1833 reader := csv.NewReader(file)

1834 header, err := reader.Read()

1835 if err != nil {

1836 return nil, err

1837 }

1838 columns := map[string]int{}

1839 for i, name := range header {

1840 columns[name] = i

1841 }

1842 for _, name := range []string{"text", "embeddings", "n_tokens"} {

1843 if _, ok := columns[name]; !ok {

1844 return nil, fmt.Errorf("missing %s column", name)

1845 }

1846 }

1847 rows := []embeddedRow{}

1848 dimensions := 0

1849 for {

1850 record, err := reader.Read()

1851 if err == io.EOF {

1852 break

1853 }

1854 if err != nil {

1855 return nil, err

1856 }

1857 row := embeddedRow{Text: record[columns["text"]]}

1858 row.NTokens, err = strconv.Atoi(record[columns["n_tokens"]])

1859 if err != nil || row.NTokens < 0 {

1860 return nil, fmt.Errorf("invalid token count")

1861 }

1862 if err := json.Unmarshal([]byte(record[columns["embeddings"]]), &row.Embedding); err != nil {

1863 return nil, err

1864 }

1865 if len(row.Embedding) == 0 {

1866 return nil, fmt.Errorf("empty embedding")

1867 }

1868 if dimensions == 0 {

1869 dimensions = len(row.Embedding)

1870 }

1871 if len(row.Embedding) != dimensions {

1872 return nil, fmt.Errorf("inconsistent embedding dimensions")

1873 }

1874 rows = append(rows, row)

1875 }

1876 if len(rows) == 0 {

1877 return nil, fmt.Errorf("no embeddings")

1878 }

1879 return rows, nil

1880}

1881 

1882func cosineDistance(a, b []float64) (float64, error) {

1883 if len(a) != len(b) {

1884 return 0, fmt.Errorf("embedding dimensions differ")

1885 }

1886 dot, aa, bb := 0.0, 0.0, 0.0

1887 for i, value := range a {

1888 dot += value * b[i]

1889 aa += value * value

1890 bb += b[i] * b[i]

1891 }

1892 norm := math.Sqrt(aa * bb)

1893 if norm <= 0 {

1894 return 0, fmt.Errorf("embedding must have a nonzero norm")

1895 }

1896 return 1 - dot/norm, nil

1897}

1898func createContext(ctx context.Context, client *openai.Client, question string, rows []embeddedRow, maxLen int) (string, error) {

1899 response, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(question)}, Model: "text-embedding-3-small"})

1900 if err != nil {

1901 return "", err

1902 }

1903 if len(response.Data) != 1 {

1904 return "", fmt.Errorf("expected one query embedding")

1905 }

1906 type rankedRow struct {

1907 Row embeddedRow

1908 Distance float64

1909 }

1910 ranked := make([]rankedRow, len(rows))

1911 for i, row := range rows {

1912 distance, err := cosineDistance(response.Data[0].Embedding, row.Embedding)

1913 if err != nil {

1914 return "", err

1915 }

1916 ranked[i] = rankedRow{row, distance}

1917 }

1918 sort.SliceStable(ranked, func(i, j int) bool { return ranked[i].Distance < ranked[j].Distance })

1919 length := 0

1920 parts := []string{}

1921 for _, item := range ranked {

1922 length += item.Row.NTokens + 4

1923 if length > maxLen {

1924 break

1925 }

1926 parts = append(parts, item.Row.Text)

1927 }

1928 return strings.Join(parts, "\n\n###\n\n"), nil

1929}

1930```

1931 

813```ruby1932```ruby

814require "openai"1933require "openai"

815require "csv"1934require "csv"


859 return response.output_text.strip()1978 return response.output_text.strip()

860```1979```

861 1980 

1981```go

1982func answerQuestion(ctx context.Context, client *openai.Client, rows []embeddedRow, question string, maxLen int) (string, error) {

1983 retrieved, err := createContext(ctx, client, question, rows, maxLen)

1984 if err != nil {

1985 return "", err

1986 }

1987 response, err := client.Responses.New(ctx, responses.ResponseNewParams{Model: "gpt-6-luna", Instructions: openai.String("Answer the question using only the supplied context. If the context doesn't answer the question, say \"I don't know.\""), Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Context: " + retrieved + "\n\nQuestion: " + question)}})

1988 if err != nil {

1989 return "", err

1990 }

1991 if response.Status != responses.ResponseStatusCompleted {

1992 return "", fmt.Errorf("response ended with status %s", response.Status)

1993 }

1994 return strings.TrimSpace(response.OutputText()), nil

1995}

1996```

1997 

862```ruby1998```ruby

863def answer_question(client, rows, question, max_len: 1800)1999def answer_question(client, rows, question, max_len: 1800)

864 context = create_context(client, question, rows, max_len: max_len)2000 context = create_context(client, question, rows, max_len: max_len)


882print(answer_question(df, "What did I have for breakfast today?"))2018print(answer_question(df, "What did I have for breakfast today?"))

883```2019```

884 2020 

2021```go

2022func main() {

2023 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)

2024 defer cancel()

2025 client := openai.NewClient()

2026 rows, err := loadEmbeddings("processed/embeddings.csv")

2027 if err != nil {

2028 log.Fatal(err)

2029 }

2030 for _, question := range []string{"What is ChatGPT?", "What did I have for breakfast today?"} {

2031 answer, err := answerQuestion(ctx, &client, rows, question, 1800)

2032 if err != nil {

2033 log.Fatal(err)

2034 }

2035 fmt.Println(answer)

2036 }

2037}

2038```

2039 

885```ruby2040```ruby

886client = OpenAI::Client.new2041client = OpenAI::Client.new

887rows = CSV.read("processed/embeddings.csv", headers: true).map do |row|2042rows = CSV.read("processed/embeddings.csv", headers: true).map do |row|