SpyBara
Go Premium

Documentation 2026-11-20 23:59 UTC to 2026-11-21 23:57 UTC

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

26 <tbody>26 <tbody>

27 <tr>27 <tr>

28 <td>`Assistants`</td>28 <td>`Assistants`</td>

29 <td>`Prompts`</td>29 <td>Responses request configuration</td>

30 <td>30 <td>

31 Prompts hold configuration (model, tools, instructions) and are easier31 Keep the model, instructions, and tools in your application and pass

32 to version and update32 them in the request.

33 </td>33 </td>

34 </tr>34 </tr>

35 <tr>35 <tr>


55 </tbody>55 </tbody>

56</table>56</table>

57 57 

58## Migrate Ruby applications

59 

60The [Ruby SDK migration guide](https://developers.openai.com/api/docs/guides/ruby-sdk-migration) lists

61the retired Assistants and Threads bindings. Keep your model choice,

62instructions, and tool definitions in your application. Pass them as

63`model:`, `instructions:`, and `tools:` when you call

64`client.responses.create`.

65 

66Create a Conversation for each thread you migrate. Convert messages and tool

67results from your own stored history to Conversation items and keep them in

68their original order. Store the new Conversation ID with the original thread

69ID.

70 

71Create a Conversation with saved messages

72 

73```ruby

74require "openai"

75 

76client = OpenAI::Client.new

77conversation = client.conversations.create(

78 items: [

79 {

80 role: :user,

81 content: "What are the five Ds of dodgeball?"

82 }

83 ],

84 metadata: { user_id: "peter_le_fleur" }

85)

86puts(conversation.id)

87```

88 

89 

90Pass the returned ID as `conversation:` on later requests. For

91application-run function tools, send each result as a `function_call_output`

92item with the matching `call_id`.

93 

94Continue the Conversation with a Response

95 

96```ruby

97require "openai"

98 

99client = OpenAI::Client.new

100response = client.responses.create(

101 model: "gpt-6.2-astra",

102 input: [

103 {

104 role: :user,

105 content: "What are the five Ds of dodgeball?"

106 }

107 ],

108 conversation: "conv_abc123"

109)

110puts(response.output_text)

111```

112 

113 

58## From assistants to prompts114## From assistants to prompts

59 115 

60Assistants were persistent API objects that bundled model choice, instructions, and tool declarations—created and managed entirely through the API. Their replacement, prompts, can only be created in the dashboard, where you can version them as you develop your product.116Assistants were persistent API objects that bundled model choice, instructions, and tool declarations. Earlier migrations moved that configuration into reusable prompts created in the dashboard.

61 117 

62### Why this is helpful118### Why this is helpful

63 119 


482 538 

483Follow the migration steps below to move from the Assistants API to the Responses API, without losing any feature support.539Follow the migration steps below to move from the Assistants API to the Responses API, without losing any feature support.

484 540 

541For Ruby, follow [Migrate Ruby applications](#migrate-ruby-applications) to

542pass your application configuration directly in the request.

543 

485### 1. Create prompts from your assistants544### 1. Create prompts from your assistants

486 545 

4871. Identify the most important assistant objects in your application.5461. Identify the most important assistant objects in your application.


542conversation = openai.conversations.create(items=items)601conversation = openai.conversations.create(items=items)

543```602```

544 603 

545```ruby

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

547require "openai"

548 

549client = OpenAI::Client.new

550thread_id = "thread_123"

551messages = client.beta.threads.messages.list(thread_id, order: :asc)

552items = []

553messages.auto_paging_each do |message|

554 content = message.content.filter_map do |part|

555 case part

556 when OpenAI::Models::Beta::Threads::TextContentBlock

557 type = if message.role == OpenAI::Models::Beta::Threads::Message::Role::USER

558 :input_text

559 else

560 :output_text

561 end

562 {

563 type: type,

564 text: part.text.value

565 }

566 when OpenAI::Models::Beta::Threads::ImageURLContentBlock

567 {

568 type: :input_image,

569 image_url: part.image_url.url,

570 detail: part.image_url.detail

571 }

572 end

573 end

574 items << {

575 role: message.role,

576 content: content

577 }

578end

579conversation = client.conversations.create(

580 items: items

581)

582puts(conversation.id)

583```

584 

585 604 

586## Comparing full examples605## Comparing full examples

587 606 


632 return {"content": messages.data[0].content}651 return {"content": messages.data[0].content}

633```652```

634 653 

635```ruby

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

637require "openai"

638 

639client = OpenAI::Client.new

640assistant_id = "asst_123"

641threads_by_session = {}

642 

643handle_message = lambda do |session_id:, content:|

644 thread_id = threads_by_session[session_id]

645 unless thread_id

646 thread_id = client.beta.threads.create.id

647 threads_by_session[session_id] = thread_id

648 end

649 

650 client.beta.threads.messages.create(

651 thread_id,

652 role: :user,

653 content: content

654 )

655 run = client.beta.threads.runs.create(

656 thread_id,

657 assistant_id: assistant_id

658 )

659 while [:queued, :in_progress].include?(run.status)

660 sleep(1)

661 run = client.beta.threads.runs.retrieve(run.id, thread_id: thread_id)

662 end

663 

664 messages = client.beta.threads.messages.list(

665 thread_id,

666 order: :desc,

667 limit: 1

668 )

669 { content: messages.data&.first&.content }

670end

671 

672puts(

673 handle_message.call(

674 session_id: "example-session",

675 content: "What are the five Ds of dodgeball?"

676 )

677)

678```

679 

680 654 

681 655

682 656 


685 659

686Responses API660Responses API

687 661 

688```typescript

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

690import express from "express";

691import OpenAI from "openai";

692 

693const app = express();

694const client = new OpenAI();

695const conversationsBySession = new Map<string, Promise<string>>();

696 

697app.use(express.json());

698 

699app.post("/messages", async (request, response) => {

700 const { content, session_id: sessionId } = request.body ?? {};

701 if (

702 typeof content !== "string" ||

703 !content.trim() ||

704 typeof sessionId !== "string" ||

705 !sessionId.trim()

706 ) {

707 response.status(400).json({

708 error: "content and session_id must be non-empty strings.",

709 });

710 return;

711 }

712 

713 let conversationIdPromise = conversationsBySession.get(sessionId);

714 

715 if (!conversationIdPromise) {

716 conversationIdPromise = client.conversations

717 .create()

718 .then((conversation) => conversation.id)

719 .catch((error) => {

720 conversationsBySession.delete(sessionId);

721 throw error;

722 });

723 conversationsBySession.set(sessionId, conversationIdPromise);

724 }

725 const conversationId = await conversationIdPromise;

726 

727 const promptId = "pmpt_123";

728 

729 const result = await client.responses.create({

730 prompt: { id: promptId },

731 input: [{ role: "user", content }],

732 conversation: conversationId,

733 });

734 

735 response.json({ content: result.output_text });

736});

737 

738app.listen(Number(process.env.OPENAI_EXAMPLE_PORT ?? 8000), "127.0.0.1");

739```

740 

741```python662```python

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

743conversations_by_session: dict[str, str] = {}664conversations_by_session: dict[str, str] = {}


869}790}

870```791```

871 792 

793```typescript

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

795import express from "express";

796import OpenAI from "openai";

797 

798const app = express();

799const client = new OpenAI();

800const conversationsBySession = new Map<string, Promise<string>>();

801 

802app.use(express.json());

803 

804app.post("/messages", async (request, response) => {

805 const { content, session_id: sessionId } = request.body ?? {};

806 if (

807 typeof content !== "string" ||

808 !content.trim() ||

809 typeof sessionId !== "string" ||

810 !sessionId.trim()

811 ) {

812 response.status(400).json({

813 error: "content and session_id must be non-empty strings.",

814 });

815 return;

816 }

817 

818 let conversationIdPromise = conversationsBySession.get(sessionId);

819 

820 if (!conversationIdPromise) {

821 conversationIdPromise = client.conversations

822 .create()

823 .then((conversation) => conversation.id)

824 .catch((error) => {

825 conversationsBySession.delete(sessionId);

826 throw error;

827 });

828 conversationsBySession.set(sessionId, conversationIdPromise);

829 }

830 const conversationId = await conversationIdPromise;

831 

832 const promptId = "pmpt_123";

833 

834 const result = await client.responses.create({

835 prompt: { id: promptId },

836 input: [{ role: "user", content }],

837 conversation: conversationId,

838 });

839 

840 response.json({ content: result.output_text });

841});

842 

843app.listen(Number(process.env.OPENAI_EXAMPLE_PORT ?? 8000), "127.0.0.1");

844```

845 

846 

847 

848<details>

849 <summary>Earlier Ruby example using a reusable prompt</summary>

850 

851For new Ruby integrations, use the application-owned configuration in

852[Migrate Ruby applications](#migrate-ruby-applications).

853 

872```ruby854```ruby

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

874require "openai"856require "openai"


907 )889 )

908)890)

909```891```

892 

893</details>

Details

484}484}

485```485```

486 486 

487```csharp

488using System.Globalization;

489 

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

491```

492 

487```ruby493```ruby

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

489```495```

guides/batch.md +26 −0

Details

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

139```139```

140 140 

141```csharp

142using OpenAI.Files;

143#pragma warning disable OPENAI001

144 

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

146OpenAIFileClient client = new(key);

147 

148OpenAIFile file = await client.UploadFileAsync("batchinput.jsonl", FileUploadPurpose.Batch);

149Console.WriteLine(file.Id);

150```

151 

141```ruby152```ruby

142require "openai"153require "openai"

143require "pathname"154require "pathname"


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

615```626```

616 627 

628```csharp

629using OpenAI.Batch;

630#pragma warning disable OPENAI001

631 

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

633BatchClient client = new(key);

634 

635int count = 0;

636await foreach (BatchJob batch in client.GetBatchesAsync(new BatchCollectionOptions { PageSizeLimit = 10 }))

637{

638 Console.WriteLine(batch.Id);

639 if (++count == 10) break;

640}

641```

642 

617```ruby643```ruby

618require "openai"644require "openai"

619 645 

Details

516}516}

517```517```

518 518 

519```csharp

520using System.Text.RegularExpressions;

521 

522private sealed record Citation(string Raw, string Family, string[] SourceIds, string? Locator, int Start, int End);

523 

524private static List<Citation> ExtractCitations(string text, params string[] families)

525{

526 if (families.Length == 0) return [];

527 string familyPattern = string.Join("|", families.Select(Regex.Escape));

528 Regex tokens = new($"\uE200(?<family>{familyPattern})\uE202(?<body>.*?)\uE201", RegexOptions.Singleline);

529 List<Citation> citations = [];

530 foreach (Match match in tokens.Matches(text))

531 {

532 List<string> parts = match.Groups["body"].Value.Split('\uE202')

533 .Select(part => part.Trim()).Where(part => part.Length > 0).ToList();

534 if (parts.Count == 0) continue;

535 string? locator = null;

536 if (Regex.IsMatch(parts[^1], @"\AL[0-9]+(?:-L[0-9]+)?\z"))

537 {

538 locator = parts[^1];

539 parts.RemoveAt(parts.Count - 1);

540 }

541 if (parts.Count == 0 || parts.Any(part => !Regex.IsMatch(part, @"\A[A-Za-z0-9_-]+\z"))) continue;

542 citations.Add(new(match.Value, match.Groups["family"].Value, parts.ToArray(), locator,

543 match.Index, match.Index + match.Length));

544 }

545 return citations;

546}

547 

548private static string StripCitations(string text, IEnumerable<Citation> citations)

549{

550 foreach (Citation citation in citations.OrderByDescending(citation => citation.Start))

551 text = text.Remove(citation.Start, citation.End - citation.Start);

552 return text;

553}

554```

555 

519```ruby556```ruby

520CITATION_START = "\u{E200}"557CITATION_START = "\u{E200}"

521CITATION_DELIMITER = "\u{E202}"558CITATION_DELIMITER = "\u{E202}"

Details

742is the canonical next context window, so pass it into your next `/responses`742is the canonical next context window, so pass it into your next `/responses`

743call as-is.743call as-is.

744 744 

745In Ruby SDK 1.0, the `output` from `client.responses.compact` uses `ResponseItem`,

746and the `output` from `client.beta.responses.compact` uses `BetaResponseItem`.

747These unions include retained input messages, output items, and compaction

748records. Update typed collections to use the broader union. To preserve raw

749fields on unrecognized items, pass `compacted.deep_to_h.fetch(:output)` as

750`input` on the next request. See the [Ruby SDK migration

751guide](https://developers.openai.com/api/docs/guides/ruby-sdk-migration).

752 

745### User journey for standalone compaction753### User journey for standalone compaction

746 754 

7471. Use `/responses` normally, sending input items that include user messages,7551. Use `/responses` normally, sending input items that include user messages,

Details

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

474```474```

475 475 

476```csharp

477using OpenAI.Conversations;

478#pragma warning disable OPENAI001

479 

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

481ConversationClient conversations = new(key);

482 

483ConversationResource conversation = await conversations.CreateConversationAsync(new ConversationCreationOptions());

484```

485 

476```ruby486```ruby

477conversation = client.conversations.create487conversation = client.conversations.create

478```488```


540 .forEach(text -> System.out.println(text.text()));550 .forEach(text -> System.out.println(text.text()));

541```551```

542 552 

553```csharp

554using OpenAI.Responses;

555#pragma warning disable OPENAI001

556 

557ResponsesClient client = new(key);

558 

559ResponseResult response = await client.CreateResponseAsync(new CreateResponseOptions(

560 "gpt-6.2-astra",

561 [ResponseItem.CreateUserMessageItem("What are the five Ds of dodgeball?")])

562{

563 ConversationOptions = new ResponseConversationOptions(conversation.Id),

564});

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

566```

567 

543```ruby568```ruby

544response = client.responses.create(569response = client.responses.create(

545 model: "gpt-6.2-astra",570 model: "gpt-6.2-astra",

Details

48 48 

49## Choose a model for the workload49## Choose a model for the workload

50 50 

51Evaluate the [GPT-6 model family](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-6-astra)51Start with [`gpt-6.2-sol`](https://developers.openai.com/api/docs/models/gpt-6.2-sol) at medium reasoning effort for most API workflows.

52for your workload. Use [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra) for the52Evaluate [`gpt-6.2-astra`](https://developers.openai.com/api/docs/models/gpt-6.2-astra) for demanding engineering or analysis,

53highest capability, [`gpt-6.1-sol`](https://developers.openai.com/api/docs/models/gpt-6.1-sol) for complex53use [`gpt-6.1-terra`](https://developers.openai.com/api/docs/models/gpt-6.1-terra) for visual tasks such as interpreting charts and screenshots,

54coding and professional work at a lower cost than Astra, and54and use [`gpt-6-luna`](https://developers.openai.com/api/docs/models/gpt-6-luna) for small, repeatable tasks. Choose the model that performs well on representative

55[`gpt-6-luna`](https://developers.openai.com/api/docs/models/gpt-6-luna) for55tasks rather than routing every request to the most capable model. See

56efficient, repeatable work. Choose the model that performs well on representative56[model selection](https://developers.openai.com/api/docs/guides/model-selection) for more workload guidance.

57tasks rather than routing every request to the most capable model.

58 57 

59When migrating to GPT-6, preserve your current model's workload role and58When migrating to GPT-6, preserve your current model's workload role and

60effective reasoning effort where supported. Use the Responses API for reasoning59effective reasoning effort where supported. Use the Responses API for reasoning

61with tools. GPT-6 Astra and [GPT-6.1 Sol](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-6-astra#gpt-61-sol)60with tools. GPT-6.2 Astra, GPT-6.2 Sol, and GPT-6.1 Terra require Responses for

62require Responses for tool calling; GPT-6 Sol and GPT-6 Luna support function61tool calling. GPT-6 Luna supports function calling in Chat Completions only with

63calling in Chat Completions only with `reasoning_effort: "none"`.62`reasoning_effort: "none"`.

64When reasoning effort is not `none`, remove `temperature`, `top_p`, and63When reasoning effort is not `none`, remove `temperature`, `top_p`, and

65`top_logprobs`; also remove `logprobs` from Chat Completions requests and64`top_logprobs`; also remove `logprobs` from Chat Completions requests and

66`message.output_text.logprobs` from the Responses `include` array. Check65`message.output_text.logprobs` from the Responses `include` array. Check

67[data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency)66[data residency eligibility](https://developers.openai.com/api/docs/guides/data-residency#which-models-and-features-are-eligible-for-data-residency)

68before selecting a model or processing tier. See the67before selecting a model or processing tier. See the

69[model migration guidance](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-6-astra#migration-quickstart)68[model migration guidance](https://developers.openai.com/api/docs/guides/latest-model#migration-quickstart)

70for other compatibility checks. Run representative evals before changing prompts or adding new69for other compatibility checks. Run representative evals before changing prompts or adding new

71capabilities. Compare task success, latency, input, output, reasoning, and70capabilities. Compare task success, latency, input, output, reasoning, and

72cache-write tokens, and cost per successful task.71cache-write tokens, and cost per successful task.


76Use `reasoning.effort` to decide how much thinking the model should do before it75Use `reasoning.effort` to decide how much thinking the model should do before it

77answers.76answers.

78 77 

79GPT-6 Astra, GPT-6.1 Sol, GPT-6 Sol, and GPT-6 Luna support `low`, `medium`,78GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, and GPT-6 Luna support `low`,

80`high`, `xhigh`, and `max`. GPT-6 Sol and GPT-6 Luna also support `none`; GPT-679`medium`, `high`, `xhigh`, and `max`. GPT-6.1 Terra and GPT-6 Luna also support

81Astra and GPT-6.1 Sol do not. Lower effort is faster and uses fewer80`none`; GPT-6.2 Astra and GPT-6.2 Sol do not. Lower effort is faster and uses

82reasoning tokens. Higher effort gives the model more time for planning,81fewer reasoning tokens. Higher effort gives the model more time for planning,

83debugging, synthesis, and multi-step tradeoffs.82debugging, synthesis, and multi-step tradeoffs.

84 83 

85Use `low` when the job is mostly extraction, routing, classification, or a84Use `low` when the job is mostly extraction, routing, classification, or a

86routine rewrite. Use `medium` or `high` when the model needs to diagnose a85routine rewrite. Use `medium` or `high` when the model needs to diagnose a

87problem, compare options, write a plan, or reason through code. Use `xhigh` or86problem, compare options, write a plan, or reason through code. Use `xhigh` or

88`max` only when representative evals show that the quality gain justifies the87`max` only when representative evals show that the quality gain justifies the

89extra latency and cost. When migrating from `minimal`, or from `none` to GPT-688extra latency and cost. When migrating from `minimal`, or from `none` to GPT-6.2

90Astra or GPT-6.1 Sol, start with `low` and compare results. Otherwise, preserve89Astra or GPT-6.2 Sol, start with `low` and compare results. Otherwise, preserve

91your current effective effort and test changes against your quality, latency,90your current effective effort and test changes against your quality, latency,

92and cost targets.91and cost targets.

93 92 


1609 1608 

1610## Handle misalignment monitoring1609## Handle misalignment monitoring

1611 1610 

1612For GPT-6 Astra agent workflows, plan for [misalignment1611For agent workflows with models covered by [misalignment

1613monitoring](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring). If a request1612monitoring](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring), plan for

1613blocked requests. If a request

1614returns `403` with `misalignment_policy_violation`, stop dispatching actions for1614returns `403` with `misalignment_policy_violation`, stop dispatching actions for

1615that conversation and do not automatically retry the blocked workflow. Handle1615that conversation and do not automatically retry the blocked workflow. Handle

1616errors during streaming too, and review any actions that may already have run.1616errors during streaming too, and review any actions that may already have run.


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

1780```1780```

1781 1781 

1782```csharp

1783using OpenAI.Responses;

1784#pragma warning disable OPENAI001

1785 

1786CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem("Analyze this large log bundle and cluster the primary failure modes.")])

1787{

1788 BackgroundModeEnabled = true,

1789 StoredOutputEnabled = false

1790};

1791options.Tools.Add(ResponseTool.CreateCodeInterpreterTool(

1792 CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(["file_abc123"])));

1793ResponseResult response = await client.CreateResponseAsync(options);

1794while (response.Status is ResponseStatus.Queued or ResponseStatus.InProgress)

1795{

1796 await Task.Delay(TimeSpan.FromSeconds(2));

1797 response = await client.GetResponseAsync(response.Id);

1798}

1799if (response.Status != ResponseStatus.Completed)

1800 throw new InvalidOperationException($"Response ended with status {response.Status}");

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

1802```

1803 

1782```ruby1804```ruby

1783require "openai"1805require "openai"

1784 1806 


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

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

1851 1873 

1852For Go, run `go get github.com/openai/openai-go/v3@v3.104.0`.1874For Go, run `go get github.com/openai/openai-go/v3@v3.105.0`.

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

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

1855 1877 

Details

469}469}

470```470```

471 471 

472```csharp

473using System.ClientModel;

474using OpenAI.Responses;

475#pragma warning disable OPENAI001

476 

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

478ResponsesClient client = new(key);

479 

480try

481{

482 ResponseResult response = await client.CreateResponseAsync("gpt-6.2-astra", "Hello world");

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

484}

485catch (ClientResultException error) when (error.Status == 429)

486{

487 Console.WriteLine($"OpenAI API request exceeded rate limit: {error.Message}");

488}

489catch (ClientResultException error)

490{

491 Console.WriteLine($"OpenAI API returned an API error: {error.Message}");

492}

493catch (HttpRequestException error)

494{

495 Console.WriteLine($"Failed to connect to OpenAI API: {error.Message}");

496}

497```

498 

472```ruby499```ruby

473require "openai"500require "openai"

474 501 

guides/evals.md +11 −0

Details

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

570```570```

571 571 

572```csharp

573using OpenAI.Files;

574#pragma warning disable OPENAI001

575 

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

577OpenAIFileClient client = new(key);

578 

579OpenAIFile file = await client.UploadFileAsync("tickets.jsonl", new FileUploadPurpose("evals"));

580Console.WriteLine(file.Id);

581```

582 

572```ruby583```ruby

573require "openai"584require "openai"

574require "pathname"585require "pathname"

Details

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

91```91```

92 92 

93```csharp

94using OpenAI.Responses;

95#pragma warning disable OPENAI001

96 

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

98ResponsesClient client = new(key);

99 

100ResponseResult response = await client.CreateResponseAsync(new CreateResponseOptions(

101 "gpt-6.2-sol", [ResponseItem.CreateUserMessageItem("What does 'fit check for my napalm era' mean?")])

102{

103 ServiceTier = new ResponseServiceTier("fast"),

104});

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

106```

107 

93```ruby108```ruby

94require "openai"109require "openai"

95 110 

Details

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

419```419```

420 420 

421```csharp

422using System.Text.Json;

423using OpenAI.Responses;

424#pragma warning disable OPENAI001

425 

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

427ResponsesClient client = new(key);

428 

429BinaryData schema = BinaryData.FromString("""

430{"type":"object","properties":{"sign":{"type":"string","description":"An astrological sign like Taurus or Aquarius"}},"required":["sign"],"additionalProperties":false}

431""");

432List<ResponseItem> history = [ResponseItem.CreateUserMessageItem("What is my horoscope? I am an Aquarius.")];

433CreateResponseOptions options = new("gpt-6.2-astra", history);

434options.Tools.Add(ResponseTool.CreateFunctionTool("get_horoscope", schema,

435 strictModeEnabled: true, functionDescription: "Get today's horoscope for an astrological sign."));

436ResponseResult response = await client.CreateResponseAsync(options);

437options.InputItems.Clear();

438foreach (ResponseItem item in history.Concat(response.OutputItems))

439 options.InputItems.Add(item);

440foreach (FunctionCallResponseItem call in response.OutputItems.OfType<FunctionCallResponseItem>())

441{

442 if (call.FunctionName != "get_horoscope")

443 throw new InvalidOperationException($"Unknown function: {call.FunctionName}");

444 using JsonDocument arguments = JsonDocument.Parse(call.FunctionArguments);

445 string sign = arguments.RootElement.GetProperty("sign").GetString()!;

446 string horoscope = $"{sign}: Next Tuesday you will befriend a baby otter.";

447 options.InputItems.Add(ResponseItem.CreateFunctionCallOutputItem(call.CallId, horoscope));

448}

449options.Instructions = "Respond only with a horoscope generated by a tool.";

450response = await client.CreateResponseAsync(options);

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

452```

453 

421```ruby454```ruby

422require "json"455require "json"

423require "openai"456require "openai"


754System.out.println(ObjectMappers.jsonMapper().writeValueAsString(input));787System.out.println(ObjectMappers.jsonMapper().writeValueAsString(input));

755```788```

756 789 

790```csharp

791foreach (ResponseItem item in response.OutputItems) options.InputItems.Add(item);

792foreach (FunctionCallResponseItem call in response.OutputItems.OfType<FunctionCallResponseItem>())

793{

794 using JsonDocument args = JsonDocument.Parse(call.FunctionArguments);

795 string result = FunctionDispatcher.CallFunction(call.FunctionName, args.RootElement);

796 options.InputItems.Add(ResponseItem.CreateFunctionCallOutputItem(call.CallId, result));

797}

798```

799 

757```ruby800```ruby

758input.concat(response.output)801input.concat(response.output)

759 802 


991 .forEach(text -> System.out.println(text.text()));1034 .forEach(text -> System.out.println(text.text()));

992```1035```

993 1036 

1037```csharp

1038response = await responses.CreateResponseAsync(options);

1039```

1040 

994```ruby1041```ruby

995require "openai"1042require "openai"

996 1043 


1355}1402}

1356```1403```

1357 1404 

1405```csharp

1406using System.ClientModel.Primitives;

1407using OpenAI.Responses;

1408#pragma warning disable OPENAI001

1409 

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

1411string model = "gpt-6.2-astra";

1412ResponsesClient client = new(key);

1413 

1414BinaryData schema = BinaryData.FromString("""

1415 {"type":"object","properties":{"location":{"type":"string","description":"City and country e.g. Bogotá, Colombia"}},"required":["location"],"additionalProperties":false}

1416 """);

1417CreateResponseOptions options = new(model, [ResponseItem.CreateUserMessageItem("What's the weather like in Paris today?")]);

1418options.StreamingEnabled = true;

1419options.Tools.Add(ResponseTool.CreateFunctionTool("get_weather", schema, true, "Get current temperature for a given location."));

1420await foreach (StreamingResponseUpdate update in client.CreateResponseStreamingAsync(options))

1421{

1422 Console.WriteLine(ModelReaderWriter.Write(update));

1423}

1424```

1425 

1358```ruby1426```ruby

1359require "openai"1427require "openai"

1360 1428 


1573toolCalls.values().forEach(System.out::println);1641toolCalls.values().forEach(System.out::println);

1574```1642```

1575 1643 

1644```csharp

1645using System.ClientModel.Primitives;

1646using System.Text.Json.Nodes;

1647using OpenAI.Responses;

1648#pragma warning disable OPENAI001

1649 

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

1651string model = "gpt-6.2-astra";

1652ResponsesClient client = new(key);

1653 

1654BinaryData schema = BinaryData.FromString("""

1655 {"type":"object","properties":{"location":{"type":"string","description":"City and country e.g. Bogotá, Colombia"}},"required":["location"],"additionalProperties":false}

1656 """);

1657CreateResponseOptions options = new(model, [ResponseItem.CreateUserMessageItem("What's the weather like in Paris today?")]);

1658options.StreamingEnabled = true;

1659options.Tools.Add(ResponseTool.CreateFunctionTool("get_weather", schema, true, "Get current temperature for a given location."));

1660JsonObject calls = new();

1661await foreach (StreamingResponseUpdate update in client.CreateResponseStreamingAsync(options))

1662{

1663 if (update is StreamingResponseOutputItemAddedUpdate added && added.Item is FunctionCallResponseItem)

1664 {

1665 string index = added.OutputIndex.ToString(System.Globalization.CultureInfo.InvariantCulture);

1666 calls[index] = JsonNode.Parse(ModelReaderWriter.Write(added.Item).ToString());

1667 }

1668 else if (update is StreamingResponseFunctionCallArgumentsDeltaUpdate delta)

1669 {

1670 string index = delta.OutputIndex.ToString(System.Globalization.CultureInfo.InvariantCulture);

1671 JsonObject call = calls[index]!.AsObject();

1672 call["arguments"] = call["arguments"]!.GetValue<string>() + delta.Delta.ToString();

1673 }

1674}

1675Console.WriteLine(calls.ToJsonString());

1676```

1677 

1576```ruby1678```ruby

1577require "openai"1679require "openai"

1578 1680 


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

1731```1833```

1732 1834 

1835```csharp

1836using OpenAI.Responses;

1837#pragma warning disable OPENAI001

1838 

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

1840ResponsesClient client = new(key);

1841 

1842CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem("Use the code_exec tool to print hello world to the console.")]);

1843options.Tools.Add(new CustomTool("code_exec")

1844{

1845 ToolDescription = "Executes arbitrary Python code.",

1846});

1847ResponseResult response = await client.CreateResponseAsync(options);

1848foreach (CustomToolCallItem call in response.OutputItems.OfType<CustomToolCallItem>())

1849{

1850 Console.WriteLine($"{call.ToolName}: {call.Input}");

1851}

1852```

1853 

1733```ruby1854```ruby

1734require "openai"1855require "openai"

1735 1856 


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

1932```2053```

1933 2054 

2055```csharp

2056using OpenAI.Responses;

2057#pragma warning disable OPENAI001

2058 

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

2060ResponsesClient client = new(key);

2061 

2062string grammar = """

2063start: expr

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

2065| term

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

2067| factor

2068factor: INT

2069SP: " "

2070ADD: "+"

2071MUL: "*"

2072%import common.INT

2073""";

2074 

2075CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem("Use the math_exp tool to add four plus four.")]);

2076options.Tools.Add(new CustomTool("math_exp")

2077{

2078 ToolDescription = "Creates valid mathematical expressions",

2079 ToolFormat = new CustomToolGrammarFormat(grammar, CustomToolGrammarFormatSyntax.Lark),

2080});

2081ResponseResult response = await client.CreateResponseAsync(options);

2082foreach (CustomToolCallItem call in response.OutputItems.OfType<CustomToolCallItem>())

2083{

2084 Console.WriteLine($"{call.ToolName}: {call.Input}");

2085}

2086```

2087 

1934```ruby2088```ruby

1935require "openai"2089require "openai"

1936 2090 


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

2192```2346```

2193 2347 

2348```csharp

2349using OpenAI.Responses;

2350#pragma warning disable OPENAI001

2351 

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

2353ResponsesClient client = new(key);

2354 

2355string grammar = """

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

2357""";

2358 

2359CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem("Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.")]);

2360options.Tools.Add(new CustomTool("timestamp")

2361{

2362 ToolDescription = "Saves a timestamp in date + time in 24-hr format.",

2363 ToolFormat = new CustomToolGrammarFormat(grammar, CustomToolGrammarFormatSyntax.Regex),

2364});

2365ResponseResult response = await client.CreateResponseAsync(options);

2366foreach (CustomToolCallItem call in response.OutputItems.OfType<CustomToolCallItem>())

2367{

2368 Console.WriteLine($"{call.ToolName}: {call.Input}");

2369}

2370```

2371 

2194```ruby2372```ruby

2195require "openai"2373require "openai"

2196 2374 

Details

12 12 

13| Model | Model ID |13| Model | Model ID |

14| ------------- | --------------- |14| ------------- | --------------- |

15| GPT-6.2 Astra | `gpt-6.2-astra` |

16| GPT-6.2 Sol | `gpt-6.2-sol` |

15| GPT-6 Luna | `gpt-6-luna` |17| GPT-6 Luna | `gpt-6-luna` |

16| GPT-6.1 Sol | `gpt-6.1-sol` |18| GPT-6.1 Sol | `gpt-6.1-sol` |

17| GPT-6.1 Terra | `gpt-6.1-terra` |19| GPT-6.1 Terra | `gpt-6.1-terra` |


241 <tr>243 <tr>

242 <td>Reasoning summaries</td>244 <td>Reasoning summaries</td>

243 <td>Available</td>245 <td>Available</td>

244 <td>Not available</td>246 <td>Available</td>

245 </tr>247 </tr>

246 </tbody>248 </tbody>

247 <tbody>249 <tbody>

Details

1541}1541}

1542```1542```

1543 1543 

1544```csharp

1545using OpenAI.Responses;

1546#pragma warning disable OPENAI001

1547 

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

1549ResponsesClient client = new(key);

1550 

1551CreateResponseOptions options = new() { Model = "gpt-6.2-astra", StreamingEnabled = true };

1552options.InputItems.Add(ResponseItem.CreateUserMessageItem("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"));

1553options.Tools.Add(new ImageGenerationTool { Model = "gpt-image-2.5-sunburst", PartialImageCount = 2 });

1554bool completed = false;

1555await foreach (StreamingResponseUpdate update in client.CreateResponseStreamingAsync(options))

1556{

1557 if (update is StreamingResponseImageGenerationCallPartialImageUpdate partial)

1558 await File.WriteAllBytesAsync($"river-partial-{partial.PartialImageIndex}.png", partial.PartialImageBytes.ToArray());

1559 else if (update is StreamingResponseCompletedUpdate final)

1560 {

1561 ImageGenerationCallResponseItem image = final.Response.OutputItems.OfType<ImageGenerationCallResponseItem>().FirstOrDefault()

1562 ?? throw new InvalidOperationException("No generated image was returned.");

1563 await File.WriteAllBytesAsync("river-final.png", image.ImageResultBytes.ToArray());

1564 completed = true;

1565 }

1566}

1567if (!completed) throw new InvalidOperationException("Image generation did not complete.");

1568```

1569 

1544```ruby1570```ruby

1545require "base64"1571require "base64"

1546require "openai"1572require "openai"


1872System.out.println(file.id());1898System.out.println(file.id());

1873```1899```

1874 1900 

1901```csharp

1902using OpenAI.Files;

1903#pragma warning disable OPENAI001

1904 

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

1906OpenAIFileClient client = new(key);

1907 

1908OpenAIFile file = await client.UploadFileAsync("cat_and_otter.png", FileUploadPurpose.Vision);

1909Console.WriteLine(file.Id);

1910```

1911 

1875```ruby1912```ruby

1876require "openai"1913require "openai"

1877require "pathname"1914require "pathname"


2260 image.result().orElseThrow(() -> new IllegalStateException("No image returned"))));2297 image.result().orElseThrow(() -> new IllegalStateException("No image returned"))));

2261```2298```

2262 2299 

2300```csharp

2301using OpenAI.Files;

2302using OpenAI.Responses;

2303#pragma warning disable OPENAI001

2304 

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

2306ResponsesClient client = new(key);

2307OpenAIFileClient files = new(key);

2308 

2309OpenAIFile bathBomb = await files.UploadFileAsync("bath-bomb.png", FileUploadPurpose.Vision);

2310OpenAIFile incense = await files.UploadFileAsync("incense-kit.png", FileUploadPurpose.Vision);

2311CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem([

2312 ResponseContentPart.CreateInputTextPart("Generate a photorealistic image of a gift basket on a white background labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures."),

2313 ResponseContentPart.CreateInputImagePart(BinaryData.FromBytes(await File.ReadAllBytesAsync("body-lotion.png"), "image/png")),

2314 ResponseContentPart.CreateInputImagePart(BinaryData.FromBytes(await File.ReadAllBytesAsync("soap.png"), "image/png")),

2315 ResponseContentPart.CreateInputImagePart(bathBomb.Id),

2316 ResponseContentPart.CreateInputImagePart(incense.Id),

2317])]);

2318options.Tools.Add(new ImageGenerationTool { Model = "gpt-image-2.5-sunburst" });

2319ResponseResult response = await client.CreateResponseAsync(options);

2320ImageGenerationCallResponseItem image = response.OutputItems.OfType<ImageGenerationCallResponseItem>().First();

2321await File.WriteAllBytesAsync("gift-basket.png", image.ImageResultBytes.ToArray());

2322```

2323 

2263```ruby2324```ruby

2264require "base64"2325require "base64"

2265require "openai"2326require "openai"


2998Files.write(Path.of("lounge.png"), Base64.getDecoder().decode(imageResult));3059Files.write(Path.of("lounge.png"), Base64.getDecoder().decode(imageResult));

2999```3060```

3000 3061 

3062```csharp

3063using OpenAI.Files;

3064using OpenAI.Responses;

3065#pragma warning disable OPENAI001

3066 

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

3068ResponsesClient client = new(key);

3069OpenAIFileClient files = new(key);

3070 

3071OpenAIFile lounge = await files.UploadFileAsync("sunlit_lounge.png", FileUploadPurpose.Vision);

3072OpenAIFile mask = await files.UploadFileAsync("mask.png", FileUploadPurpose.Vision);

3073CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem([

3074 ResponseContentPart.CreateInputTextPart("generate an image of the same sunlit indoor lounge area with a pool but the pool should contain a flamingo"),

3075 ResponseContentPart.CreateInputImagePart(lounge.Id),

3076])]);

3077options.Tools.Add(new ImageGenerationTool

3078{

3079 Model = "gpt-image-2.5-sunburst",

3080 Quality = ImageGenerationToolQuality.High,

3081 InputImageMask = new ImageGenerationToolInputImageMask(mask.Id),

3082});

3083ResponseResult response = await client.CreateResponseAsync(options);

3084ImageGenerationCallResponseItem image = response.OutputItems.OfType<ImageGenerationCallResponseItem>().First();

3085await File.WriteAllBytesAsync("lounge.png", image.ImageResultBytes.ToArray());

3086```

3087 

3001```ruby3088```ruby

3002require "base64"3089require "base64"

3003require "openai"3090require "openai"


3181}3268}

3182```3269```

3183 3270 

3271```csharp

3272using OpenAI.Images;

3273#pragma warning disable OPENAI001

3274 

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

3276string model = "gpt-image-2.5-sunburst";

3277ImageClient client = new(model, key);

3278 

3279GeneratedImage image = await client.GenerateImageEditAsync(

3280 "sunlit_lounge.png",

3281 "A sunlit indoor lounge area with a pool containing a flamingo",

3282 "mask.png");

3283await File.WriteAllBytesAsync("composition.png", image.ImageBytes.ToArray());

3284```

3285 

3184```ruby3286```ruby

3185require "openai"3287require "openai"

3186require "pathname"3288require "pathname"

Details

3127}3127}

3128```3128```

3129 3129 

3130```csharp

3131using OpenAI.Images;

3132#pragma warning disable OPENAI001

3133 

3134string prompt = """

3135 

3136Create an original, non-infringing logo for a company called Field & Flour, a local bakery.

3137The logo should feel warm, simple, and timeless. Use clean, vector-like shapes, a strong silhouette, and balanced negative space.

3138Favor simplicity over detail so it reads clearly at small and large sizes. Flat design, minimal strokes, no gradients unless essential.

3139Fully transparent background. Deliver a single centered logo with generous padding, clean alpha edges, and no solid backdrop, scenery, checkerboard, or watermark.

3140 

3141""";

3142 GeneratedImageCollection logos = await client.GenerateImagesAsync(prompt, 4, new ImageGenerationOptions

3143 {

3144 Size = new GeneratedImageSize(1024, 1536),

3145 Quality = GeneratedImageQuality.MediumQuality,

3146 Background = GeneratedImageBackground.Transparent,

3147 OutputFileFormat = GeneratedImageFileFormat.Png

3148 });

3149 for (int index = 0; index < logos.Count; index++)

3150 await File.WriteAllBytesAsync($"logo-generation-{index + 1}-gpt-image-2.5-sunburst.png", logos[index].ImageBytes.ToArray());

3151 prompt = """

3152 

3153Extract the product from the input image and isolate it on a fully transparent background.

3154Output: centered product, crisp silhouette, no halos/fringing.

3155Preserve product geometry and label legibility exactly.

3156Add only light polishing. Do not add a solid backdrop, checkerboard, scenery, or shadow.

3157Do not restyle the product; remove the background and preserve clean alpha transparency.

3158 

3159""";

3160 GeneratedImage cutout = await client.GenerateImageEditAsync("input_images/shampoo.webp", prompt, new ImageEditOptions

3161 {

3162 Size = new GeneratedImageSize(1024, 1536),

3163 Quality = GeneratedImageQuality.MediumQuality,

3164 Background = GeneratedImageBackground.Transparent,

3165 OutputFileFormat = GeneratedImageFileFormat.Png

3166 });

3167 await File.WriteAllBytesAsync("extract-product-gpt-image-2.5-sunburst.png", cutout.ImageBytes.ToArray());

3168```

3169 

3130```ruby3170```ruby

3131require "base64"3171require "base64"

3132require "openai"3172require "openai"

Details

115 115 

116Register supported tools in `delegation.responses.tools`. Set `delegation.responses.tool_choice` to `"auto"` to let the backend choose a tool, `"required"` to require a tool call, or `"none"` to disable tool calls. You can also select a named function.116Register supported tools in `delegation.responses.tools`. Set `delegation.responses.tool_choice` to `"auto"` to let the backend choose a tool, `"required"` to require a tool call, or `"none"` to disable tool calls. You can also select a named function.

117 117 

118In Ruby SDK 1.0, typed delegation tool choices use `ToolChoice::Function` and `ToolChoice::Mcp`. See [Update Live delegation tool choices](https://developers.openai.com/api/docs/guides/ruby-sdk-migration#update-live-delegation-tool-choices) for the new names and MCP fields.

119 

118Set `delegation.responses.parallel_tool_calls` to `true` to allow multiple tool calls in a response, or `false` for sequential calls. Your application executes custom functions and checks their dependencies and required approvals. These settings apply after GPT-Live delegates; use the [live prompt](https://developers.openai.com/api/docs/guides/live-prompting#delegation) to guide when it should delegate.120Set `delegation.responses.parallel_tool_calls` to `true` to allow multiple tool calls in a response, or `false` for sequential calls. Your application executes custom functions and checks their dependencies and required approvals. These settings apply after GPT-Live delegates; use the [live prompt](https://developers.openai.com/api/docs/guides/live-prompting#delegation) to guide when it should delegate.

119 121 

120The Responses configuration requires a backend `model` at creation. In addition to the tools below, it exposes `max_output_tokens` (at least 16 when set), `service_tier`, and the `reasoning` and `text` settings supported by the selected backend model. See [Reduce backend latency](#reduce-backend-latency) for settings you can tune.122The Responses configuration requires a backend `model` at creation. In addition to the tools below, it exposes `max_output_tokens` (at least 16 when set), `service_tier`, and the `reasoning` and `text` settings supported by the selected backend model. See [Reduce backend latency](#reduce-backend-latency) for settings you can tune.

Details

123}123}

124```124```

125 125 

126```csharp

127using OpenAI.Chat;

128#pragma warning disable OPENAI001

129 

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

131ChatClient client = new("gpt-6.2-astra", key);

132 

133ChatCompletion completion = await client.CompleteChatAsync(

134 [new UserChatMessage("Write a one-sentence bedtime story about a unicorn.")]);

135Console.WriteLine(completion.Content[0].Text);

136```

137 

126```ruby138```ruby

127require "openai"139require "openai"

128 140 


188}200}

189```201```

190 202 

203```csharp

204using OpenAI.Responses;

205#pragma warning disable OPENAI001

206 

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

208ResponsesClient client = new(key);

209 

210ResponseResult response = await client.CreateResponseAsync(

211 "gpt-6.2-astra", "Write a one-sentence bedtime story about a unicorn.");

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

213```

214 

191```ruby215```ruby

192require "openai"216require "openai"

193 217 

Details

824}824}

825```825```

826 826 

827```csharp

828using System.ClientModel;

829using System.ClientModel.Primitives;

830using OpenAI.Responses;

831#pragma warning disable OPENAI001

832 

833ResponsesClientOptions clientOptions = new() { RetryPolicy = new ClientRetryPolicy(maxRetries: 0) };

834ResponsesClient client = new(new ApiKeyCredential(key), clientOptions);

835 

836CreateResponseOptions options = new("gpt-6-luna", [ResponseItem.CreateUserMessageItem("Say hello in one sentence.")])

837{

838 ReasoningOptions = new() { ReasoningEffortLevel = ResponseReasoningEffortLevel.Low },

839 MaxOutputTokenCount = 2048

840};

841ResponseResult response = await RetryWithBackoffAsync(() => client.CreateResponseAsync(options));

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

843 

844internal static async Task<ResponseResult> RetryWithBackoffAsync(Func<Task<ClientResult<ResponseResult>>> operation)

845{

846 double delaySeconds = 1;

847 const int maxRetries = 10;

848 for (int attempt = 0; ; attempt++)

849 {

850 try

851 {

852 return await operation();

853 }

854 catch (ClientResultException error) when (error.Status == 429 && attempt < maxRetries)

855 {

856 delaySeconds *= 2 * (1 + Random.Shared.NextDouble());

857 await Task.Delay(TimeSpan.FromSeconds(delaySeconds));

858 }

859 }

860}

861```

862 

827```ruby863```ruby

828require "openai"864require "openai"

829 865 

Details

1284}1284}

1285```1285```

1286 1286 

1287```csharp

1288using OpenAI.Realtime;

1289#pragma warning disable OPENAI002

1290 

1291RealtimeMessageItem item = RealtimeItem.CreateUserMessageItem([new RealtimeInputImageMessageContentPart(new Uri("data:image/png;base64," + Convert.ToBase64String(File.ReadAllBytes("image.png"))))]);

1292item.Id = Guid.NewGuid().ToString("N");

1293await session.SendCommandAsync(new RealtimeClientCommandConversationItemCreate(item), timeout.Token);

1294```

1295 

1287```ruby1296```ruby

1288encoded_image = Base64.strict_encode64(File.binread("image.png"))1297encoded_image = Base64.strict_encode64(File.binread("image.png"))

1289 1298 

Details

215}215}

216```216```

217 217 

218```csharp

219using OpenAI.Realtime;

220#pragma warning disable OPENAI002

221 

222RealtimeTranscriptionSessionInputAudioOptions input = new()

223{

224 AudioFormat = new RealtimePcmAudioFormat(),

225 AudioTranscriptionOptions = new() { Model = "gpt-live-transcribe" }

226};

227input.DisableTurnDetection();

228await session.SendCommandAsync(new RealtimeClientCommandSessionUpdate(new RealtimeTranscriptionSessionOptions

229{

230 AudioOptions = new() { InputAudioOptions = input }

231}), timeout.Token);

232byte[] audio = await File.ReadAllBytesAsync("speech.pcm", timeout.Token);

233for (int offset = 0; offset < audio.Length; offset += 9600)

234{

235 BinaryData chunk = BinaryData.FromBytes(audio.AsMemory(offset, Math.Min(9600, audio.Length - offset)));

236 await session.SendCommandAsync(new RealtimeClientCommandInputAudioBufferAppend(chunk), timeout.Token);

237}

238await session.SendCommandAsync(new RealtimeClientCommandInputAudioBufferCommit(), timeout.Token);

239string? itemId = null;

240await foreach (RealtimeServerUpdate update in session.ReceiveUpdatesAsync(timeout.Token))

241{

242 if (update is RealtimeServerUpdateError error)

243 throw new InvalidOperationException(error.Error.Message);

244 if (update is RealtimeServerUpdateInputAudioBufferCommitted committed)

245 itemId = committed.ItemId;

246 if (update is RealtimeServerUpdateConversationItemInputAudioTranscriptionDelta delta)

247 Console.Error.WriteLine($"Partial transcript ({delta.ItemId}): {delta.Delta}");

248 if (update is RealtimeServerUpdateConversationItemInputAudioTranscriptionFailed failed && failed.ItemId == itemId)

249 throw new InvalidOperationException(failed.Error.Message);

250 if (update is RealtimeServerUpdateConversationItemInputAudioTranscriptionCompleted transcript && transcript.ItemId == itemId)

251 {

252 Console.WriteLine($"Final transcript: {transcript.Transcript}");

253 return;

254 }

255}

256throw new InvalidOperationException("Session ended before the committed audio was transcribed.");

257```

258 

218```ruby259```ruby

219require "openai"260require "openai"

220require "base64"261require "base64"

Details

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

664```664```

665 665 

666```csharp

667using OpenAI.Responses;

668#pragma warning disable OPENAI001

669 

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

671ResponsesClient client = new(key);

672 

673List<ResponseItem> history = [ResponseItem.CreateUserMessageItem("Inspect this repository and identify the likely bug.")];

674ResponseResult first = await client.CreateResponseAsync(new CreateResponseOptions("gpt-6.1-sol", history)

675{

676 ReasoningOptions = new ResponseReasoningOptions { Context = ResponseReasoningContext.CurrentTurn },

677});

678 

679ResponseResult second = await client.CreateResponseAsync(new CreateResponseOptions(

680 "gpt-6.1-sol", [ResponseItem.CreateUserMessageItem("Now patch the bug and explain the change.")])

681{

682 PreviousResponseId = first.Id,

683 ReasoningOptions = new ResponseReasoningOptions { Context = ResponseReasoningContext.AllTurns },

684});

685Console.WriteLine(second.GetOutputText());

686```

687 

666```ruby688```ruby

667require "openai"689require "openai"

668 690 


907 .forEach(text -> System.out.println(text.text()));929 .forEach(text -> System.out.println(text.text()));

908```930```

909 931 

932```csharp

933using OpenAI.Responses;

934#pragma warning disable OPENAI001

935 

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

937ResponsesClient client = new(key);

938 

939List<ResponseItem> history = [ResponseItem.CreateUserMessageItem("Inspect this repository and identify the likely bug.")];

940ResponseResult first = await client.CreateResponseAsync(new CreateResponseOptions("gpt-6.1-sol", history)

941{

942 ReasoningOptions = new ResponseReasoningOptions { Context = ResponseReasoningContext.CurrentTurn },

943 StoredOutputEnabled = false,

944});

945 

946// Preserve every output item, including encrypted reasoning.

947history.AddRange(first.OutputItems);

948history.Add(ResponseItem.CreateUserMessageItem("Now patch the bug and explain the change."));

949ResponseResult second = await client.CreateResponseAsync(new CreateResponseOptions("gpt-6.1-sol", history)

950{

951 StoredOutputEnabled = false,

952 ReasoningOptions = new ResponseReasoningOptions { Context = ResponseReasoningContext.AllTurns },

953});

954Console.WriteLine(second.GetOutputText());

955```

956 

910```ruby957```ruby

911require "openai"958require "openai"

912 959 

Details

606System.out.println(store.id());606System.out.println(store.id());

607```607```

608 608 

609```csharp

610using OpenAI.VectorStores;

611#pragma warning disable OPENAI001

612 

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

614VectorStoreClient client = new(key);

615 

616VectorStore store = await client.CreateVectorStoreAsync(new VectorStoreCreationOptions

617{

618 Name = "Support FAQ",

619 FileIds = { "file_123" },

620});

621Console.WriteLine(store.Id);

622```

623 

609```ruby624```ruby

610require "openai"625require "openai"

611 626 


665System.out.println(client.vectorStores().retrieve(vectorStoreId).id());680System.out.println(client.vectorStores().retrieve(vectorStoreId).id());

666```681```

667 682 

683```csharp

684using OpenAI.VectorStores;

685#pragma warning disable OPENAI001

686 

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

688VectorStoreClient client = new(key);

689 

690VectorStore store = await client.GetVectorStoreAsync("vs_123");

691Console.WriteLine(store.Id);

692```

693 

668```ruby694```ruby

669require "openai"695require "openai"

670 696 


734System.out.println(store.name());760System.out.println(store.name());

735```761```

736 762 

763```csharp

764using OpenAI.VectorStores;

765#pragma warning disable OPENAI001

766 

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

768VectorStoreClient client = new(key);

769 

770VectorStore store = await client.ModifyVectorStoreAsync("vs_123", new VectorStoreModificationOptions

771{

772 Name = "Support FAQ Updated",

773});

774Console.WriteLine(store.Name);

775```

776 

737```ruby777```ruby

738require "openai"778require "openai"

739 779 


790System.out.println(client.vectorStores().delete(vectorStoreId).deleted());830System.out.println(client.vectorStores().delete(vectorStoreId).deleted());

791```831```

792 832 

833```csharp

834using OpenAI.VectorStores;

835#pragma warning disable OPENAI001

836 

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

838VectorStoreClient client = new(key);

839 

840VectorStoreDeletionResult result = await client.DeleteVectorStoreAsync("vs_123");

841Console.WriteLine(result.Deleted);

842```

843 

793```ruby844```ruby

794require "openai"845require "openai"

795 846 


842System.out.println(client.vectorStores().list().data());893System.out.println(client.vectorStores().list().data());

843```894```

844 895 

896```csharp

897using OpenAI.VectorStores;

898#pragma warning disable OPENAI001

899 

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

901VectorStoreClient client = new(key);

902 

903// Display the first page; the SDK fetches more pages as you keep iterating.

904VectorStoreCollectionOptions options = new() { PageSizeLimit = 20, Order = VectorStoreCollectionOrder.Descending };

905int count = 0;

906await foreach (VectorStore store in client.GetVectorStoresAsync(options))

907{

908 Console.WriteLine(store.Id);

909 if (++count == 20) break;

910}

911```

912 

845```ruby913```ruby

846require "openai"914require "openai"

847 915 


1097 .id());1165 .id());

1098```1166```

1099 1167 

1168```csharp

1169using OpenAI.VectorStores;

1170#pragma warning disable OPENAI001

1171 

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

1173VectorStoreClient client = new(key);

1174 

1175VectorStoreFile file = await client.GetVectorStoreFileAsync("vs_123", "file_123");

1176Console.WriteLine(file.FileId);

1177```

1178 

1100```ruby1179```ruby

1101require "openai"1180require "openai"

1102 1181 


1180System.out.println(file.id());1259System.out.println(file.id());

1181```1260```

1182 1261 

1262```csharp

1263using OpenAI.VectorStores;

1264#pragma warning disable OPENAI001

1265 

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

1267VectorStoreClient client = new(key);

1268 

1269VectorStoreFile file = await client.UpdateVectorStoreFileAttributesAsync(

1270 "vs_123", "file_123",

1271 new Dictionary<string, BinaryData> { ["key"] = BinaryData.FromObjectAsJson("value") });

1272Console.WriteLine(file.FileId);

1273```

1274 

1183```ruby1275```ruby

1184require "openai"1276require "openai"

1185 1277 


1250 .deleted());1342 .deleted());

1251```1343```

1252 1344 

1345```csharp

1346using OpenAI.VectorStores;

1347#pragma warning disable OPENAI001

1348 

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

1350VectorStoreClient client = new(key);

1351 

1352FileFromStoreRemovalResult result = await client.RemoveFileFromVectorStoreAsync("vs_123", "file_123");

1353Console.WriteLine(result.Removed);

1354```

1355 

1253```ruby1356```ruby

1254require "openai"1357require "openai"

1255 1358 


1306System.out.println(client.vectorStores().files().list(vectorStoreId).data());1409System.out.println(client.vectorStores().files().list(vectorStoreId).data());

1307```1410```

1308 1411 

1412```csharp

1413using OpenAI.VectorStores;

1414#pragma warning disable OPENAI001

1415 

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

1417VectorStoreClient client = new(key);

1418 

1419await foreach (VectorStoreFile file in client.GetVectorStoreFilesAsync("vs_123"))

1420{

1421 Console.WriteLine(file.FileId);

1422}

1423```

1424 

1309```ruby1425```ruby

1310require "openai"1426require "openai"

1311 1427 


1554 .status());1670 .status());

1555```1671```

1556 1672 

1673```csharp

1674using OpenAI.VectorStores;

1675#pragma warning disable OPENAI001

1676 

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

1678VectorStoreClient client = new(key);

1679 

1680VectorStoreFileBatch batch = await client.GetVectorStoreFileBatchAsync("vs_123", "vsfb_123");

1681Console.WriteLine(batch.BatchId);

1682```

1683 

1557```ruby1684```ruby

1558require "openai"1685require "openai"

1559 1686 


1627 .status());1754 .status());

1628```1755```

1629 1756 

1757```csharp

1758using OpenAI.VectorStores;

1759#pragma warning disable OPENAI001

1760 

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

1762VectorStoreClient client = new(key);

1763 

1764VectorStoreFileBatch batch = await client.CancelVectorStoreFileBatchAsync("vs_123", "vsfb_123");

1765```

1766 

1630```ruby1767```ruby

1631require "openai"1768require "openai"

1632 1769 


1700 .data());1837 .data());

1701```1838```

1702 1839 

1840```csharp

1841using OpenAI.VectorStores;

1842#pragma warning disable OPENAI001

1843 

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

1845VectorStoreClient client = new(key);

1846 

1847await foreach (VectorStoreFile file in client.GetVectorStoreFilesInBatchAsync("vs_123", "vsfb_123"))

1848{

1849 Console.WriteLine(file.FileId);

1850}

1851```

1852 

1703```ruby1853```ruby

1704require "openai"1854require "openai"

1705 1855 


1880System.out.println(store.expiresAfter().orElseThrow());2030System.out.println(store.expiresAfter().orElseThrow());

1881```2031```

1882 2032 

2033```csharp

2034using OpenAI.VectorStores;

2035#pragma warning disable OPENAI001

2036 

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

2038VectorStoreClient client = new(key);

2039 

2040VectorStore store = await client.ModifyVectorStoreAsync("vs_123", new VectorStoreModificationOptions

2041{

2042 ExpirationPolicy = new VectorStoreExpirationPolicy(VectorStoreExpirationAnchor.LastActiveAt, 7),

2043});

2044Console.WriteLine(store.ExpirationPolicy.Days);

2045```

2046 

1883```ruby2047```ruby

1884require "openai"2048require "openai"

1885 2049 

guides/ruby-sdk-migration.md +53 −0 created

Details

1# Upgrade to the Ruby SDK 1.0

2 

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

4 

5Use this guide to update an application that uses the `openai` gem. The SDK requires Ruby 3.3.0 or later. Update the gem version in your `Gemfile`, run `bundle update openai`, and run your application's tests and type checker.

6 

7## Migrate off Assistants and Threads

8 

9Replace `client.beta.assistants` and `client.beta.threads` with Responses and Conversations. Create a Conversation for each thread you migrate. Use the history your application already stores, and keep the new conversation ID for later requests.

10 

11Pass the model, instructions, and tools from your application to `client.responses.create`. Use `client.responses.stream` for streamed results. Return function results as `function_call_output` items with the original `call_id`.

12 

13Follow the [Assistants migration guide](https://developers.openai.com/api/docs/assistants/migration) and the [Conversations examples](https://developers.openai.com/api/docs/guides/conversation-state#using-the-conversations-api).

14 

15## Remove Videos and Sora 2 calls

16 

17Remove `client.videos` calls, polling and download jobs, Videos type annotations, and Batch inputs targeting `/v1/videos`. The Videos API and Sora 2 model IDs have retired. For stored `video.completed` or `video.failed` webhook events, read the video ID with `event[:data][:id]` after verification.

18 

19## Use the full compacted history

20 

21Compaction can return retained user, system, and developer input messages alongside output items and compaction records. Update Ruby, Sorbet, and RBS annotations from `ResponseOutputItem` to `ResponseItem` for GA compaction and from `BetaResponseOutputItem` to `BetaResponseItem` for beta compaction.

22 

23When inspecting a message, check its class and role before accessing its content. Function calls in compacted output use `ResponseFunctionToolCallItem` in GA and `BetaResponseFunctionToolCallItem` in beta. Ordinary Responses output keeps its existing types.

24 

25Pass `compacted.deep_to_h.fetch(:output)` as the next request's `input` to preserve the entire window. See [Compaction](https://developers.openai.com/api/docs/guides/compaction).

26 

27## Update Live delegation tool choices

28 

29In `OpenAI::Live::ResponsesDelegationConfig::ToolChoice` and `OpenAI::Live::ResponsesDelegationUpdateConfig::ToolChoice`, replace `LiveFunctionToolChoiceParam` with `Function` and `LiveMCPToolChoiceParam` with `Mcp`. Update constructor calls, class checks, and Sorbet `OrHash` references. In RBS, replace `live_function_tool_choice_param` with `function` and `live_mcp_tool_choice_param` with `mcp`.

30 

31Function choices require a string `name`. MCP choices require a string `server_label`. Omit `name` to leave it out, pass `nil` to send JSON null, or pass a string to select a tool. The same MCP fields apply to allowed-tools entries.

32 

33See [Live Responses delegation](https://developers.openai.com/api/docs/guides/live-delegation#configure-responses-delegation).

34 

35## Pass named graders as a hash

36 

37Set `MultiGrader#graders` to a hash keyed by grader name. For example, pass `graders: {quality: grader}` and refer to `quality` in `calculate_output`. Read each returned grader by its key and use `MultiGrader::Grader` for the value type. See [Graders](https://developers.openai.com/api/docs/guides/graders).

38 

39## Compare returned image sizes as strings

40 

41Image responses and image generation and edit stream events return size strings such as `"1024x1024"`. Use `image.size&.to_s` in code that supports both SDK versions or needs to handle an omitted size. The size constants and `Size.values` also use strings.

42 

43## Replace retired model constants

44 

45Replace `GPT_4_VISION_PREVIEW`, `GPT_3_5_TURBO_0613`, and `GPT_3_5_TURBO_16K_0613` with supported model IDs. If your application sends images, choose a model that accepts image inputs. See the [model list](https://developers.openai.com/api/docs/models).

46 

47## Check typed callers

48 

49- Responses input-item listing decodes assistant messages as `ResponseOutputMessage`. Check that branches that read assistant content use the output message type.

50- To send an SDK request model as keyword arguments, pass `**params.to_hash`. Construct a nested SDK object when you need typed readers for fields in a nested hash.

51- Decisions keeps the released `DecisionInputMessage::User`, `DecisionInputMessage::Developer`, `DecisionInputMessage::System`, and `DecisionInputMessage::Assistant` constructors.

52 

53For Ruby code examples, read the [SDK migration guide](https://github.com/openai/openai-ruby/blob/v1.0.0/docs/MIGRATION_1.0.0.md).

Details

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

135```135```

136 136 

137```csharp

138using OpenAI.Chat;

139#pragma warning disable OPENAI001

140 

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

142ChatClient client = new("gpt-6.2-astra", key);

143 

144ChatCompletion completion = await client.CompleteChatAsync(

145 [new UserChatMessage("This is a test")],

146 new ChatCompletionOptions

147 {

148 SafetyIdentifier = "user_123456",

149 MaxOutputTokenCount = 5,

150 });

151Console.WriteLine(completion.Content[0].Text);

152```

153 

137```ruby154```ruby

138require "openai"155require "openai"

139 156 

Details

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

104```104```

105 105 

106```csharp

107using OpenAI.Responses;

108#pragma warning disable OPENAI001

109 

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

111ResponsesClient client = new(key);

112 

113ResponseResult response = await client.CreateResponseAsync(new CreateResponseOptions(

114 "gpt-6.1-terra", [ResponseItem.CreateUserMessageItem("This is a test")])

115{

116 SafetyIdentifier = "user_123456",

117});

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

119```

120 

106```ruby121```ruby

107require "openai"122require "openai"

108 123 


203 .forEach(System.out::println);218 .forEach(System.out::println);

204```219```

205 220 

221```csharp

222using OpenAI.Chat;

223#pragma warning disable OPENAI001

224 

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

226ChatClient client = new("gpt-6.1-terra", key);

227 

228ChatCompletion completion = await client.CompleteChatAsync(

229 [new UserChatMessage("This is a test")],

230 new ChatCompletionOptions

231 {

232 SafetyIdentifier = "user_123456",

233 });

234Console.WriteLine(completion.Content[0].Text);

235```

236 

206```ruby237```ruby

207require "openai"238require "openai"

208 239 

Details

484}484}

485```485```

486 486 

487```csharp

488using System.Globalization;

489using OpenAI.Audio;

490#pragma warning disable OPENAI001

491 

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

493AudioClient client = new("gpt-4o-transcribe-diarize", key);

494 

495string speaker = "data:audio/wav;base64," + Convert.ToBase64String(await File.ReadAllBytesAsync("agent.wav"));

496AudioTranscriptionOptions options = new()

497{

498 ResponseFormat = AudioTranscriptionFormat.Diarized,

499 ChunkingStrategy = AudioTranscriptionDefaultChunkingStrategy.Auto,

500 KnownSpeakerNames = { "agent" },

501 KnownSpeakerReferenceUris = { speaker },

502};

503DiarizedAudioTranscription transcript = await client.TranscribeAudioDiarizedAsync("meeting.wav", options);

504foreach (DiarizedTranscriptionSegment segment in transcript.Segments)

505 Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{segment.SpeakerLabel}: {segment.Text} ({segment.StartTime.TotalSeconds:F2}-{segment.EndTime.TotalSeconds:F2})"));

506```

507 

487```ruby508```ruby

488require "base64"509require "base64"

489require "openai"510require "openai"

Details

201}201}

202```202```

203 203 

204```csharp

205using System.ClientModel.Primitives;

206using OpenAI.Responses;

207using StreamingEvent = OpenAI.Responses.StreamingResponseUpdate;

208#pragma warning disable OPENAI001

209```

210 

204```ruby211```ruby

205require "openai"212require "openai"

206 213 

Details

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

306```306```

307 307 

308```csharp

309using OpenAI.Containers;

310using OpenAI.Responses;

311#pragma warning disable OPENAI001

312 

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

314ContainerClient client = new(key);

315 

316ContainerResource container = await client.CreateContainerAsync(new ContainerCreationOptions("test-container")

317{

318 MemoryLimit = ContainerMemoryLimit.Max4GB,

319});

320ResponsesClient responses = new(key);

321 

322CreateResponseOptions options = new("gpt-6.2-astra", [ResponseItem.CreateUserMessageItem(

323 "use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result")])

324{

325 ToolChoice = ResponseToolChoice.CreateRequiredChoice(),

326};

327options.Tools.Add(new CodeInterpreterTool(container.Id));

328ResponseResult response = await responses.CreateResponseAsync(options);

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

330```

331 

308```ruby332```ruby

309require "openai"333require "openai"

310 334 

Details

1094}1094}

1095```1095```

1096 1096 

1097```csharp

1098using OpenAI.Responses;

1099#pragma warning disable OPENAI001

1100 

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

1102ResponsesClient client = new(key);

1103 

1104CreateResponseOptions options = new() { Model = "gpt-6.2-astra", StreamingEnabled = true };

1105options.InputItems.Add(ResponseItem.CreateUserMessageItem("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"));

1106options.Tools.Add(new ImageGenerationTool { Model = "gpt-image-2.5-sunburst", PartialImageCount = 2 });

1107bool completed = false;

1108await foreach (StreamingResponseUpdate update in client.CreateResponseStreamingAsync(options))

1109{

1110 if (update is StreamingResponseImageGenerationCallPartialImageUpdate partial)

1111 await File.WriteAllBytesAsync($"river-partial-{partial.PartialImageIndex}.png", partial.PartialImageBytes.ToArray());

1112 else if (update is StreamingResponseCompletedUpdate final)

1113 {

1114 ImageGenerationCallResponseItem image = final.Response.OutputItems.OfType<ImageGenerationCallResponseItem>().FirstOrDefault()

1115 ?? throw new InvalidOperationException("No generated image was returned.");

1116 await File.WriteAllBytesAsync("river-final.png", image.ImageResultBytes.ToArray());

1117 completed = true;

1118 }

1119}

1120if (!completed) throw new InvalidOperationException("Image generation did not complete.");

1121```

1122 

1097```ruby1123```ruby

1098require "base64"1124require "base64"

1099require "openai"1125require "openai"

Details

279System.out.println(container.id());279System.out.println(container.id());

280```280```

281 281 

282```csharp

283using OpenAI.Containers;

284#pragma warning disable OPENAI001

285 

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

287ContainerClient client = new(key);

288 

289ContainerResource container = await client.CreateContainerAsync(new ContainerCreationOptions("analysis-container")

290{

291 MemoryLimit = ContainerMemoryLimit.Max1GB,

292 ExpirationPolicy = new ContainerExpirationPolicy

293 {

294 Anchor = ContainerExpirationPolicyAnchor.LastActiveAt,

295 Duration = TimeSpan.FromMinutes(20),

296 },

297});

298Console.WriteLine(container.Id);

299```

300 

282```ruby301```ruby

283require "openai"302require "openai"

284 303 


1245System.out.println("Container deleted.");1264System.out.println("Container deleted.");

1246```1265```

1247 1266 

1267```csharp

1268using OpenAI.Containers;

1269#pragma warning disable OPENAI001

1270 

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

1272ContainerClient client = new(key);

1273 

1274await client.DeleteContainerAsync("container_id");

1275Console.WriteLine("Container deleted");

1276```

1277 

1248```ruby1278```ruby

1249require "openai"1279require "openai"

1250 1280 

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.104.0`.19For Go, run `go get github.com/openai/openai-go/v3@v3.105.0`.

20For Java, add the Maven dependency `com.openai:openai-java:4.105.0` and use Java 17 or later for these examples.20For Java, add the Maven dependency `com.openai:openai-java:4.105.0` 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 

libraries.md +1 −1

Details

276 276 

277 277

278 278 

279To use the OpenAI API in Ruby, you can use the official [OpenAI SDK for Ruby](https://github.com/openai/openai-ruby). Get started by adding the gem to your application:279The official [OpenAI SDK for Ruby](https://github.com/openai/openai-ruby) requires Ruby 3.3.0 or later. If you use an earlier version of the gem, read the [Ruby SDK 1.0 migration guide](https://developers.openai.com/api/docs/guides/ruby-sdk-migration). To get started, add the gem to your application:

280 280 

281Install the OpenAI SDK with Bundler281Install the OpenAI SDK with Bundler

282 282 

quickstart.md +1 −1

Details

286 286 

287 287

288 288 

289To use the OpenAI API in Ruby, you can use the official [OpenAI SDK for Ruby](https://github.com/openai/openai-ruby). Get started by adding the gem to your application:289The official [OpenAI SDK for Ruby](https://github.com/openai/openai-ruby) requires Ruby 3.3.0 or later. If you use an earlier version of the gem, read the [Ruby SDK 1.0 migration guide](https://developers.openai.com/api/docs/guides/ruby-sdk-migration). To get started, add the gem to your application:

290 290 

291Install the OpenAI SDK with Bundler291Install the OpenAI SDK with Bundler

292 292 

Details

167 }167 }

168```168```

169 169 

170```csharp

171using System.IO.Compression;

172using System.Text.Json;

173using System.Xml.Linq;

174using OpenAI.Audio;

175using OpenAI.Chat;

176 

177internal static class MeetingMinutes

178{

179 private static readonly string Key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

180 private static readonly AudioClient Audio = new("gpt-transcribe", Key);

181 private static readonly ChatClient Chat = new("gpt-5.5", Key);

182 

183private static async Task<string> TranscribeAudioAsync(string path)

184{

185 AudioTranscription transcription = await Audio.TranscribeAudioAsync(path);

186 return transcription.Text;

187}

188```

189 

170```ruby190```ruby

171require "caracal"191require "caracal"

172require "openai"192require "openai"


251}271}

252```272```

253 273 

274```csharp

275private static async Task<string> CompleteAsync(string transcription, string instructions)

276{

277 ChatCompletion completion = await Chat.CompleteChatAsync([new SystemChatMessage(instructions), new UserChatMessage(transcription)]);

278 return completion.Content[0].Text;

279}

280```

281 

254```ruby282```ruby

255def complete(client, transcription, instructions)283def complete(client, transcription, instructions)

256 response = client.chat.completions.create(284 response = client.chat.completions.create(


326}354}

327```355```

328 356 

357```csharp

358private static async Task<Dictionary<string, string>> BuildMeetingMinutesAsync(string transcription) => new()

359{

360 ["Abstract summary"] = await ExtractAbstractSummaryAsync(transcription),

361 ["Key points"] = await ExtractKeyPointsAsync(transcription),

362 ["Action items"] = await ExtractActionItemsAsync(transcription),

363 ["Sentiment"] = await AnalyzeSentimentAsync(transcription),

364};

365```

366 

329```ruby367```ruby

330def build_meeting_minutes(client, transcription)368def build_meeting_minutes(client, transcription)

331 {369 {


379}417}

380```418```

381 419 

420```csharp

421private static Task<string> ExtractAbstractSummaryAsync(string transcription) => CompleteAsync(transcription,

422 "Summarize the meeting transcript in one concise paragraph. Keep the most important decisions and context, and omit tangents.");

423```

424 

382```ruby425```ruby

383def extract_abstract_summary(client, transcription)426def extract_abstract_summary(client, transcription)

384 complete(427 complete(


427}470}

428```471```

429 472 

473```csharp

474private static Task<string> ExtractKeyPointsAsync(string transcription) => CompleteAsync(transcription,

475 "List the most important ideas, findings, and topics from the meeting. Use concise bullet points.");

476```

477 

430```ruby478```ruby

431def extract_key_points(client, transcription)479def extract_key_points(client, transcription)

432 complete(480 complete(


475}523}

476```524```

477 525 

526```csharp

527private static Task<string> ExtractActionItemsAsync(string transcription) => CompleteAsync(transcription,

528 "List every task or follow-up agreed to in the meeting. Include the owner and deadline when the transcript provides them.");

529```

530 

478```ruby531```ruby

479def extract_action_items(client, transcription)532def extract_action_items(client, transcription)

480 complete(533 complete(


523}576}

524```577```

525 578 

579```csharp

580private static Task<string> AnalyzeSentimentAsync(string transcription) => CompleteAsync(transcription,

581 "Describe the meeting's overall sentiment as positive, negative, or neutral, and briefly explain the assessment.");

582```

583 

526```ruby584```ruby

527def analyze_sentiment(client, transcription)585def analyze_sentiment(client, transcription)

528 complete(586 complete(


643}701}

644```702```

645 703 

704```csharp

705private static void SaveAsDocx(Dictionary<string, string> minutes, string path)

706{

707 XNamespace word = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

708 XElement body = new(word + "body");

709 foreach ((string heading, string content) in minutes)

710 {

711 body.Add(new XElement(word + "p", new XElement(word + "r",

712 new XElement(word + "rPr", new XElement(word + "b")), new XElement(word + "t", heading))));

713 foreach (string line in content.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'))

714 body.Add(new XElement(word + "p", new XElement(word + "r", new XElement(word + "t", line))));

715 }

716 using FileStream file = File.Create(path);

717 using ZipArchive archive = new(file, ZipArchiveMode.Create);

718 WriteEntry(archive, "[Content_Types].xml", """

719 

720""");

721 WriteEntry(archive, "_rels/.rels", """

722 

723""");

724 WriteEntry(archive, "word/document.xml", new XDocument(new XElement(word + "document", body)).ToString());

725}

726 

727private static void WriteEntry(ZipArchive archive, string name, string content)

728{

729 using StreamWriter writer = new(archive.CreateEntry(name).Open());

730 writer.Write(content);

731}

732```

733 

646```ruby734```ruby

647def save_as_docx(minutes, filename)735def save_as_docx(minutes, filename)

648 Caracal::Document.save(filename) do |document|736 Caracal::Document.save(filename) do |document|


702}790}

703```791```

704 792 

793```csharp

794internal static async Task RunAsync()

795 {

796 string transcription = await TranscribeAudioAsync("meeting.wav");

797 Dictionary<string, string> minutes = await BuildMeetingMinutesAsync(transcription);

798 Console.WriteLine(JsonSerializer.Serialize(minutes));

799 SaveAsDocx(minutes, "meeting_minutes.docx");

800 }

801}

802```

803 

705```ruby804```ruby

706transcription = transcribe_audio(client, "meeting.wav")805transcription = transcribe_audio(client, "meeting.wav")

707minutes = build_meeting_minutes(client, transcription)806minutes = build_meeting_minutes(client, transcription)

Details

1858 1858 

1859Create an embedding for each chunk with `text-embedding-3-small`. Use the same model for query embeddings. If you change embedding models, rebuild the index before searching it.1859Create an embedding for each chunk with `text-embedding-3-small`. Use the same model for query embeddings. If you change embedding models, rebuild the index before searching it.

1860 1860 

1861For the C# example, first export the `text` column of the chunked `df` to `processed/chunks.json` as a JSON array of strings. The example reads those chunks and writes the embeddings used by the question-answering step.

1862 

1861Create embeddings for the scraped text1863Create embeddings for the scraped text

1862 1864 

1863```typescript1865```typescript


1974}1976}

1975```1977```

1976 1978 

1979```csharp

1980using System.Globalization;

1981using System.Text.Json;

1982using OpenAI.Embeddings;

1983 

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

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

1986EmbeddingClient client = new(model, key);

1987 

1988string[] pageChunks = JsonSerializer.Deserialize<string[]>(

1989 await File.ReadAllTextAsync("processed/chunks.json"))!;

1990Directory.CreateDirectory("processed");

1991using StreamWriter writer = new("processed/embeddings.csv");

1992await writer.WriteLineAsync("text,n_tokens,embeddings");

1993foreach (string text in pageChunks)

1994{

1995 (float[] vector, int tokens) = await EmbedAsync(client, text.Replace("\n", " ", StringComparison.Ordinal));

1996 string encoded = JsonSerializer.Serialize(vector);

1997 await writer.WriteLineAsync($"{CsvField(text)},{tokens.ToString(CultureInfo.InvariantCulture)},{CsvField(encoded)}");

1998}

1999Console.WriteLine("Saved processed/embeddings.csv");

2000 

2001static async Task<(float[] Vector, int Tokens)> EmbedAsync(EmbeddingClient client, string text)

2002{

2003 OpenAIEmbeddingCollection result = await client.GenerateEmbeddingsAsync([text]);

2004 return (result[0].ToFloats().ToArray(), result.Usage.InputTokenCount);

2005}

2006 

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

2008```

2009 

1977```ruby2010```ruby

1978require "openai"2011require "openai"

1979require "csv"2012require "csv"


2144```2177```

2145 2178 

2146 2179 

2147Embed the question using the same model you used to build the index. The example computes cosine distances with NumPy and retrieves the closest text chunks.2180Embed the question using the same model you used to build the index. The example computes cosine distances and retrieves the closest text chunks.

2148 2181 

2149Build context for a question2182Build context for a question

2150 2183 


2400}2433}

2401```2434```

2402 2435 

2436```csharp

2437using System.Globalization;

2438using System.Text.Json;

2439using Microsoft.VisualBasic.FileIO;

2440using OpenAI.Embeddings;

2441using OpenAI.Responses;

2442#pragma warning disable OPENAI001

2443 

2444private sealed record Page(string Text, int Tokens, float[] Embedding);

2445private static double CosineDistance(float[] query, float[] vector)

2446{

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

2448 for (int i = 0; i < query.Length; i++)

2449 {

2450 dot += (double)query[i] * vector[i];

2451 leftNorm += (double)query[i] * query[i];

2452 rightNorm += (double)vector[i] * vector[i];

2453 }

2454 return 1 - dot / Math.Sqrt(leftNorm * rightNorm);

2455}

2456 

2457private static async Task<string> CreateContextAsync(EmbeddingClient embeddings, string question, IEnumerable<Page> pages, int maxTokens = 1800)

2458{

2459 OpenAIEmbedding result = await embeddings.GenerateEmbeddingAsync(question);

2460 float[] query = result.ToFloats().ToArray();

2461 List<string> context = [];

2462 int tokenCount = 0;

2463 foreach (Page page in pages.OrderBy(page => CosineDistance(query, page.Embedding)))

2464 {

2465 tokenCount += page.Tokens + 4;

2466 if (tokenCount > maxTokens) break;

2467 context.Add(page.Text);

2468 }

2469 return string.Join("\n\n###\n\n", context);

2470}

2471```

2472 

2403```ruby2473```ruby

2404require "openai"2474require "openai"

2405require "csv"2475require "csv"


2485}2555}

2486```2556```

2487 2557 

2558```csharp

2559private static async Task<string> AnswerQuestionAsync(EmbeddingClient embeddings, ResponsesClient responses, IEnumerable<Page> pages, string question)

2560{

2561 string context = await CreateContextAsync(embeddings, question, pages);

2562 ResponseResult response = await responses.CreateResponseAsync(new CreateResponseOptions(

2563 "gpt-6-luna", [ResponseItem.CreateUserMessageItem($"Context: {context}\n\nQuestion: {question}")])

2564 {

2565 Instructions = "Answer the question using only the supplied context. If the context doesn't answer the question, say \"I don't know.\"",

2566 });

2567 return response.GetOutputText().Trim();

2568}

2569```

2570 

2488```ruby2571```ruby

2489def answer_question(client, rows, question, max_len: 1800)2572def answer_question(client, rows, question, max_len: 1800)

2490 context = create_context(client, question, rows, max_len: max_len)2573 context = create_context(client, question, rows, max_len: max_len)


2538}2621}

2539```2622```

2540 2623 

2624```csharp

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

2626EmbeddingClient embeddings = new("text-embedding-3-small", key);

2627 

2628ResponsesClient responses = new(key);

2629 

2630using TextFieldParser csv = new("processed/embeddings.csv") { HasFieldsEnclosedInQuotes = true };

2631csv.SetDelimiters(",");

2632csv.ReadFields();

2633List<Page> pages = [];

2634while (!csv.EndOfData)

2635{

2636 string[] row = csv.ReadFields()!;

2637 pages.Add(new(row[0], int.Parse(row[1], CultureInfo.InvariantCulture), JsonSerializer.Deserialize<float[]>(row[2])!));

2638}

2639Console.WriteLine(await AnswerQuestionAsync(embeddings, responses, pages, "What is ChatGPT?"));

2640Console.WriteLine(await AnswerQuestionAsync(embeddings, responses, pages, "What did I have for breakfast today?"));

2641```

2642 

2541```ruby2643```ruby

2542client = OpenAI::Client.new2644client = OpenAI::Client.new

2543rows = CSV.read("processed/embeddings.csv", headers: true).map do |row|2645rows = CSV.read("processed/embeddings.csv", headers: true).map do |row|