From f7c8dbb6b5bd5bab72b7d146dc255d543b0b5a71 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 20 Aug 2025 17:39:45 +0000 Subject: [PATCH 01/10] feat(client): add support for verifying signatures on incoming webhooks From 0af0cd01302d3859a4e43554ed8e665007f69aad Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 19 Aug 2025 19:35:50 +0000 Subject: [PATCH 02/10] chore(internal/ci): setup breaking change detection --- .github/workflows/detect-breaking-changes.yml | 33 +++++++++++ .stats.yml | 2 +- scripts/detect-breaking-changes | 56 +++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/detect-breaking-changes.yml create mode 100755 scripts/detect-breaking-changes diff --git a/.github/workflows/detect-breaking-changes.yml b/.github/workflows/detect-breaking-changes.yml new file mode 100644 index 00000000..0391f030 --- /dev/null +++ b/.github/workflows/detect-breaking-changes.yml @@ -0,0 +1,33 @@ +name: CI +on: + pull_request: + branches: + - main + - next + +jobs: + detect_breaking_changes: + runs-on: 'ubuntu-latest' + name: detect-breaking-changes + if: github.repository == 'openai/openai-go' + steps: + - name: Calculate fetch-depth + run: | + echo "FETCH_DEPTH=$(expr ${{ github.event.pull_request.commits }} + 1)" >> $GITHUB_ENV + + - uses: actions/checkout@v4 + with: + # Ensure we can check out the pull request base in the script below. + fetch-depth: ${{ env.FETCH_DEPTH }} + + - name: Setup go + uses: actions/setup-go@v5 + with: + go-version-file: ./go.mod + + - name: Detect breaking changes + run: | + # Try to check out previous versions of the breaking change detection script. This ensures that + # we still detect breaking changes when entire files and their tests are removed. + git checkout "${{ github.event.pull_request.base.sha }}" -- ./scripts/detect-breaking-changes 2>/dev/null || true + ./scripts/detect-breaking-changes ${{ github.event.pull_request.base.sha }} \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index d5c54d20..564125bf 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-7ef7a457c3bf05364e66e48c9ca34f31bfef1f6c9b7c15b1812346105e0abb16.yml openapi_spec_hash: a2b1f5d8fbb62175c93b0ebea9f10063 -config_hash: 76afa3236f36854a8705f1281b1990b8 +config_hash: 4870312b04f48fd717ea4151053e7fb9 diff --git a/scripts/detect-breaking-changes b/scripts/detect-breaking-changes new file mode 100755 index 00000000..231cde6d --- /dev/null +++ b/scripts/detect-breaking-changes @@ -0,0 +1,56 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +echo "==> Detecting breaking changes" + +TEST_PATHS=( + client_test.go + completion_test.go + chatcompletion_test.go + chatcompletionmessage_test.go + embedding_test.go + file_test.go + image_test.go + audiotranscription_test.go + audiotranslation_test.go + audiospeech_test.go + moderation_test.go + model_test.go + finetuningjob_test.go + finetuningjobcheckpoint_test.go + finetuningcheckpointpermission_test.go + finetuningalphagrader_test.go + vectorstore_test.go + vectorstorefile_test.go + vectorstorefilebatch_test.go + webhooks/webhook_test.go + betaassistant_test.go + betathread_test.go + betathreadrun_test.go + betathreadrunstep_test.go + betathreadmessage_test.go + batch_test.go + upload_test.go + uploadpart_test.go + responses/response_test.go + responses/inputitem_test.go + container_test.go + containerfile_test.go + containerfilecontent_test.go + usage_test.go + paginationauto_test.go + paginationmanual_test.go +) + +for PATHSPEC in "${TEST_PATHS[@]}"; do + # Try to check out previous versions of the test files + # with the current SDK. + git checkout "$1" -- "${PATHSPEC}" 2>/dev/null || true +done + +# Instead of running the tests, use the linter to check if an +# older test is no longer compatible with the latest SDK. +./scripts/lint From 3265795fffa44fb40d65a800b300807d9f1e7b2b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 20 Aug 2025 17:41:52 +0000 Subject: [PATCH 03/10] chore(internal): version bump --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f050e53f..a1f90fac 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Or to pin the version: ```sh -go get -u 'github.com/openai/openai-go@v2.1.1' +go get -u 'github.com/openai/openai-go/v2@v2.1.1' ``` From 5b7c31bde9c1086d3fb71c88dfdf74228845b22e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 21 Aug 2025 16:22:56 +0000 Subject: [PATCH 04/10] feat(api): adding support for /v1/conversations to the API --- .stats.yml | 8 +- api.md | 43 ++ betathreadmessage.go | 2 + client.go | 39 +- conversations/aliases.go | 493 ++++++++++++++++ conversations/conversation.go | 783 ++++++++++++++++++++++++ conversations/conversation_test.go | 126 ++++ conversations/item.go | 916 +++++++++++++++++++++++++++++ conversations/item_test.go | 139 +++++ packages/pagination/pagination.go | 106 ++++ responses/inputitem.go | 2 - responses/inputitem_test.go | 1 - responses/response.go | 92 +++ responses/response_test.go | 5 +- scripts/detect-breaking-changes | 2 + shared/constant/constants.go | 6 + 16 files changed, 2737 insertions(+), 26 deletions(-) create mode 100644 conversations/aliases.go create mode 100644 conversations/conversation.go create mode 100644 conversations/conversation_test.go create mode 100644 conversations/item.go create mode 100644 conversations/item_test.go diff --git a/.stats.yml b/.stats.yml index 564125bf..640f2dee 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-7ef7a457c3bf05364e66e48c9ca34f31bfef1f6c9b7c15b1812346105e0abb16.yml -openapi_spec_hash: a2b1f5d8fbb62175c93b0ebea9f10063 -config_hash: 4870312b04f48fd717ea4151053e7fb9 +configured_endpoints: 105 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bcdfe525558e67a09b32dec7a573e87b94bab47db3951eb4a86a4dafb60296c.yml +openapi_spec_hash: 49e7e46bfe9f61b7b7a60e36840c0cd7 +config_hash: e4514526ae01126a61f9b6c14a351737 diff --git a/api.md b/api.md index 2621d923..821c5519 100644 --- a/api.md +++ b/api.md @@ -628,6 +628,7 @@ Params Types: - responses.ResponseCodeInterpreterToolCallParam - responses.ResponseComputerToolCallParam - responses.ResponseComputerToolCallOutputScreenshotParam +- responses.ResponseConversationParam - responses.ResponseCustomToolCallParam - responses.ResponseCustomToolCallOutputParam - responses.ResponseFileSearchToolCallParam @@ -777,6 +778,48 @@ Methods: - client.Responses.InputItems.List(ctx context.Context, responseID string, query responses.InputItemListParams) (pagination.CursorPage[responses.ResponseItemUnion], error) +# Conversations + +Response Types: + +- conversations.ComputerScreenshotContent +- conversations.ContainerFileCitationBody +- conversations.Conversation +- conversations.ConversationDeletedResource +- conversations.FileCitationBody +- conversations.InputFileContent +- conversations.InputImageContent +- conversations.InputTextContent +- conversations.LobProb +- conversations.Message +- conversations.OutputTextContent +- conversations.RefusalContent +- conversations.SummaryTextContent +- conversations.TextContent +- conversations.TopLogProb +- conversations.URLCitationBody + +Methods: + +- client.Conversations.New(ctx context.Context, body conversations.ConversationNewParams) (conversations.Conversation, error) +- client.Conversations.Get(ctx context.Context, conversationID string) (conversations.Conversation, error) +- client.Conversations.Update(ctx context.Context, conversationID string, body conversations.ConversationUpdateParams) (conversations.Conversation, error) +- client.Conversations.Delete(ctx context.Context, conversationID string) (conversations.ConversationDeletedResource, error) + +## Items + +Response Types: + +- conversations.ConversationItemUnion +- conversations.ConversationItemList + +Methods: + +- client.Conversations.Items.New(ctx context.Context, conversationID string, params conversations.ItemNewParams) (conversations.ConversationItemList, error) +- client.Conversations.Items.Get(ctx context.Context, conversationID string, itemID string, query conversations.ItemGetParams) (conversations.ConversationItemUnion, error) +- client.Conversations.Items.List(ctx context.Context, conversationID string, query conversations.ItemListParams) (pagination.ConversationCursorPage[conversations.ConversationItemUnion], error) +- client.Conversations.Items.Delete(ctx context.Context, conversationID string, itemID string) (conversations.Conversation, error) + # Containers Response Types: diff --git a/betathreadmessage.go b/betathreadmessage.go index 5422a7fd..fc789591 100644 --- a/betathreadmessage.go +++ b/betathreadmessage.go @@ -899,6 +899,8 @@ func (r *Message) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (Message) ImplConversationItemUnion() {} + type MessageAttachment struct { // The ID of the file to attach to the message. FileID string `json:"file_id"` diff --git a/client.go b/client.go index f876af1c..7645f7b1 100644 --- a/client.go +++ b/client.go @@ -7,6 +7,7 @@ import ( "net/http" "os" + "github.com/openai/openai-go/v2/conversations" "github.com/openai/openai-go/v2/internal/requestconfig" "github.com/openai/openai-go/v2/option" "github.com/openai/openai-go/v2/responses" @@ -17,24 +18,25 @@ import ( // interacting with the openai API. You should not instantiate this client // directly, and instead use the [NewClient] method instead. type Client struct { - Options []option.RequestOption - Completions CompletionService - Chat ChatService - Embeddings EmbeddingService - Files FileService - Images ImageService - Audio AudioService - Moderations ModerationService - Models ModelService - FineTuning FineTuningService - Graders GraderService - VectorStores VectorStoreService - Webhooks webhooks.WebhookService - Beta BetaService - Batches BatchService - Uploads UploadService - Responses responses.ResponseService - Containers ContainerService + Options []option.RequestOption + Completions CompletionService + Chat ChatService + Embeddings EmbeddingService + Files FileService + Images ImageService + Audio AudioService + Moderations ModerationService + Models ModelService + FineTuning FineTuningService + Graders GraderService + VectorStores VectorStoreService + Webhooks webhooks.WebhookService + Beta BetaService + Batches BatchService + Uploads UploadService + Responses responses.ResponseService + Conversations conversations.ConversationService + Containers ContainerService } // DefaultClientOptions read from the environment (OPENAI_API_KEY, OPENAI_ORG_ID, @@ -86,6 +88,7 @@ func NewClient(opts ...option.RequestOption) (r Client) { r.Batches = NewBatchService(opts...) r.Uploads = NewUploadService(opts...) r.Responses = responses.NewResponseService(opts...) + r.Conversations = conversations.NewConversationService(opts...) r.Containers = NewContainerService(opts...) return diff --git a/conversations/aliases.go b/conversations/aliases.go new file mode 100644 index 00000000..c42efa01 --- /dev/null +++ b/conversations/aliases.go @@ -0,0 +1,493 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package conversations + +import ( + "github.com/openai/openai-go/v2/internal/apierror" + "github.com/openai/openai-go/v2/packages/param" + "github.com/openai/openai-go/v2/shared" +) + +// aliased to make [param.APIUnion] private when embedding +type paramUnion = param.APIUnion + +// aliased to make [param.APIObject] private when embedding +type paramObj = param.APIObject + +type Error = apierror.Error + +// This is an alias to an internal type. +type ChatModel = shared.ChatModel + +// Equals "gpt-5" +const ChatModelGPT5 = shared.ChatModelGPT5 + +// Equals "gpt-5-mini" +const ChatModelGPT5Mini = shared.ChatModelGPT5Mini + +// Equals "gpt-5-nano" +const ChatModelGPT5Nano = shared.ChatModelGPT5Nano + +// Equals "gpt-5-2025-08-07" +const ChatModelGPT5_2025_08_07 = shared.ChatModelGPT5_2025_08_07 + +// Equals "gpt-5-mini-2025-08-07" +const ChatModelGPT5Mini2025_08_07 = shared.ChatModelGPT5Mini2025_08_07 + +// Equals "gpt-5-nano-2025-08-07" +const ChatModelGPT5Nano2025_08_07 = shared.ChatModelGPT5Nano2025_08_07 + +// Equals "gpt-5-chat-latest" +const ChatModelGPT5ChatLatest = shared.ChatModelGPT5ChatLatest + +// Equals "gpt-4.1" +const ChatModelGPT4_1 = shared.ChatModelGPT4_1 + +// Equals "gpt-4.1-mini" +const ChatModelGPT4_1Mini = shared.ChatModelGPT4_1Mini + +// Equals "gpt-4.1-nano" +const ChatModelGPT4_1Nano = shared.ChatModelGPT4_1Nano + +// Equals "gpt-4.1-2025-04-14" +const ChatModelGPT4_1_2025_04_14 = shared.ChatModelGPT4_1_2025_04_14 + +// Equals "gpt-4.1-mini-2025-04-14" +const ChatModelGPT4_1Mini2025_04_14 = shared.ChatModelGPT4_1Mini2025_04_14 + +// Equals "gpt-4.1-nano-2025-04-14" +const ChatModelGPT4_1Nano2025_04_14 = shared.ChatModelGPT4_1Nano2025_04_14 + +// Equals "o4-mini" +const ChatModelO4Mini = shared.ChatModelO4Mini + +// Equals "o4-mini-2025-04-16" +const ChatModelO4Mini2025_04_16 = shared.ChatModelO4Mini2025_04_16 + +// Equals "o3" +const ChatModelO3 = shared.ChatModelO3 + +// Equals "o3-2025-04-16" +const ChatModelO3_2025_04_16 = shared.ChatModelO3_2025_04_16 + +// Equals "o3-mini" +const ChatModelO3Mini = shared.ChatModelO3Mini + +// Equals "o3-mini-2025-01-31" +const ChatModelO3Mini2025_01_31 = shared.ChatModelO3Mini2025_01_31 + +// Equals "o1" +const ChatModelO1 = shared.ChatModelO1 + +// Equals "o1-2024-12-17" +const ChatModelO1_2024_12_17 = shared.ChatModelO1_2024_12_17 + +// Equals "o1-preview" +const ChatModelO1Preview = shared.ChatModelO1Preview + +// Equals "o1-preview-2024-09-12" +const ChatModelO1Preview2024_09_12 = shared.ChatModelO1Preview2024_09_12 + +// Equals "o1-mini" +const ChatModelO1Mini = shared.ChatModelO1Mini + +// Equals "o1-mini-2024-09-12" +const ChatModelO1Mini2024_09_12 = shared.ChatModelO1Mini2024_09_12 + +// Equals "gpt-4o" +const ChatModelGPT4o = shared.ChatModelGPT4o + +// Equals "gpt-4o-2024-11-20" +const ChatModelGPT4o2024_11_20 = shared.ChatModelGPT4o2024_11_20 + +// Equals "gpt-4o-2024-08-06" +const ChatModelGPT4o2024_08_06 = shared.ChatModelGPT4o2024_08_06 + +// Equals "gpt-4o-2024-05-13" +const ChatModelGPT4o2024_05_13 = shared.ChatModelGPT4o2024_05_13 + +// Equals "gpt-4o-audio-preview" +const ChatModelGPT4oAudioPreview = shared.ChatModelGPT4oAudioPreview + +// Equals "gpt-4o-audio-preview-2024-10-01" +const ChatModelGPT4oAudioPreview2024_10_01 = shared.ChatModelGPT4oAudioPreview2024_10_01 + +// Equals "gpt-4o-audio-preview-2024-12-17" +const ChatModelGPT4oAudioPreview2024_12_17 = shared.ChatModelGPT4oAudioPreview2024_12_17 + +// Equals "gpt-4o-audio-preview-2025-06-03" +const ChatModelGPT4oAudioPreview2025_06_03 = shared.ChatModelGPT4oAudioPreview2025_06_03 + +// Equals "gpt-4o-mini-audio-preview" +const ChatModelGPT4oMiniAudioPreview = shared.ChatModelGPT4oMiniAudioPreview + +// Equals "gpt-4o-mini-audio-preview-2024-12-17" +const ChatModelGPT4oMiniAudioPreview2024_12_17 = shared.ChatModelGPT4oMiniAudioPreview2024_12_17 + +// Equals "gpt-4o-search-preview" +const ChatModelGPT4oSearchPreview = shared.ChatModelGPT4oSearchPreview + +// Equals "gpt-4o-mini-search-preview" +const ChatModelGPT4oMiniSearchPreview = shared.ChatModelGPT4oMiniSearchPreview + +// Equals "gpt-4o-search-preview-2025-03-11" +const ChatModelGPT4oSearchPreview2025_03_11 = shared.ChatModelGPT4oSearchPreview2025_03_11 + +// Equals "gpt-4o-mini-search-preview-2025-03-11" +const ChatModelGPT4oMiniSearchPreview2025_03_11 = shared.ChatModelGPT4oMiniSearchPreview2025_03_11 + +// Equals "chatgpt-4o-latest" +const ChatModelChatgpt4oLatest = shared.ChatModelChatgpt4oLatest + +// Equals "codex-mini-latest" +const ChatModelCodexMiniLatest = shared.ChatModelCodexMiniLatest + +// Equals "gpt-4o-mini" +const ChatModelGPT4oMini = shared.ChatModelGPT4oMini + +// Equals "gpt-4o-mini-2024-07-18" +const ChatModelGPT4oMini2024_07_18 = shared.ChatModelGPT4oMini2024_07_18 + +// Equals "gpt-4-turbo" +const ChatModelGPT4Turbo = shared.ChatModelGPT4Turbo + +// Equals "gpt-4-turbo-2024-04-09" +const ChatModelGPT4Turbo2024_04_09 = shared.ChatModelGPT4Turbo2024_04_09 + +// Equals "gpt-4-0125-preview" +const ChatModelGPT4_0125Preview = shared.ChatModelGPT4_0125Preview + +// Equals "gpt-4-turbo-preview" +const ChatModelGPT4TurboPreview = shared.ChatModelGPT4TurboPreview + +// Equals "gpt-4-1106-preview" +const ChatModelGPT4_1106Preview = shared.ChatModelGPT4_1106Preview + +// Equals "gpt-4-vision-preview" +const ChatModelGPT4VisionPreview = shared.ChatModelGPT4VisionPreview + +// Equals "gpt-4" +const ChatModelGPT4 = shared.ChatModelGPT4 + +// Equals "gpt-4-0314" +const ChatModelGPT4_0314 = shared.ChatModelGPT4_0314 + +// Equals "gpt-4-0613" +const ChatModelGPT4_0613 = shared.ChatModelGPT4_0613 + +// Equals "gpt-4-32k" +const ChatModelGPT4_32k = shared.ChatModelGPT4_32k + +// Equals "gpt-4-32k-0314" +const ChatModelGPT4_32k0314 = shared.ChatModelGPT4_32k0314 + +// Equals "gpt-4-32k-0613" +const ChatModelGPT4_32k0613 = shared.ChatModelGPT4_32k0613 + +// Equals "gpt-3.5-turbo" +const ChatModelGPT3_5Turbo = shared.ChatModelGPT3_5Turbo + +// Equals "gpt-3.5-turbo-16k" +const ChatModelGPT3_5Turbo16k = shared.ChatModelGPT3_5Turbo16k + +// Equals "gpt-3.5-turbo-0301" +const ChatModelGPT3_5Turbo0301 = shared.ChatModelGPT3_5Turbo0301 + +// Equals "gpt-3.5-turbo-0613" +const ChatModelGPT3_5Turbo0613 = shared.ChatModelGPT3_5Turbo0613 + +// Equals "gpt-3.5-turbo-1106" +const ChatModelGPT3_5Turbo1106 = shared.ChatModelGPT3_5Turbo1106 + +// Equals "gpt-3.5-turbo-0125" +const ChatModelGPT3_5Turbo0125 = shared.ChatModelGPT3_5Turbo0125 + +// Equals "gpt-3.5-turbo-16k-0613" +const ChatModelGPT3_5Turbo16k0613 = shared.ChatModelGPT3_5Turbo16k0613 + +// A filter used to compare a specified attribute key to a given value using a +// defined comparison operation. +// +// This is an alias to an internal type. +type ComparisonFilter = shared.ComparisonFilter + +// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. +// +// - `eq`: equals +// - `ne`: not equal +// - `gt`: greater than +// - `gte`: greater than or equal +// - `lt`: less than +// - `lte`: less than or equal +// +// This is an alias to an internal type. +type ComparisonFilterType = shared.ComparisonFilterType + +// Equals "eq" +const ComparisonFilterTypeEq = shared.ComparisonFilterTypeEq + +// Equals "ne" +const ComparisonFilterTypeNe = shared.ComparisonFilterTypeNe + +// Equals "gt" +const ComparisonFilterTypeGt = shared.ComparisonFilterTypeGt + +// Equals "gte" +const ComparisonFilterTypeGte = shared.ComparisonFilterTypeGte + +// Equals "lt" +const ComparisonFilterTypeLt = shared.ComparisonFilterTypeLt + +// Equals "lte" +const ComparisonFilterTypeLte = shared.ComparisonFilterTypeLte + +// The value to compare against the attribute key; supports string, number, or +// boolean types. +// +// This is an alias to an internal type. +type ComparisonFilterValueUnion = shared.ComparisonFilterValueUnion + +// A filter used to compare a specified attribute key to a given value using a +// defined comparison operation. +// +// This is an alias to an internal type. +type ComparisonFilterParam = shared.ComparisonFilterParam + +// The value to compare against the attribute key; supports string, number, or +// boolean types. +// +// This is an alias to an internal type. +type ComparisonFilterValueUnionParam = shared.ComparisonFilterValueUnionParam + +// Combine multiple filters using `and` or `or`. +// +// This is an alias to an internal type. +type CompoundFilter = shared.CompoundFilter + +// Type of operation: `and` or `or`. +// +// This is an alias to an internal type. +type CompoundFilterType = shared.CompoundFilterType + +// Equals "and" +const CompoundFilterTypeAnd = shared.CompoundFilterTypeAnd + +// Equals "or" +const CompoundFilterTypeOr = shared.CompoundFilterTypeOr + +// Combine multiple filters using `and` or `or`. +// +// This is an alias to an internal type. +type CompoundFilterParam = shared.CompoundFilterParam + +// The input format for the custom tool. Default is unconstrained text. +// +// This is an alias to an internal type. +type CustomToolInputFormatUnion = shared.CustomToolInputFormatUnion + +// Unconstrained free-form text. +// +// This is an alias to an internal type. +type CustomToolInputFormatText = shared.CustomToolInputFormatText + +// A grammar defined by the user. +// +// This is an alias to an internal type. +type CustomToolInputFormatGrammar = shared.CustomToolInputFormatGrammar + +// The input format for the custom tool. Default is unconstrained text. +// +// This is an alias to an internal type. +type CustomToolInputFormatUnionParam = shared.CustomToolInputFormatUnionParam + +// Unconstrained free-form text. +// +// This is an alias to an internal type. +type CustomToolInputFormatTextParam = shared.CustomToolInputFormatTextParam + +// A grammar defined by the user. +// +// This is an alias to an internal type. +type CustomToolInputFormatGrammarParam = shared.CustomToolInputFormatGrammarParam + +// This is an alias to an internal type. +type ErrorObject = shared.ErrorObject + +// This is an alias to an internal type. +type FunctionDefinition = shared.FunctionDefinition + +// This is an alias to an internal type. +type FunctionDefinitionParam = shared.FunctionDefinitionParam + +// The parameters the functions accepts, described as a JSON Schema object. See the +// [guide](https://platform.openai.com/docs/guides/function-calling) for examples, +// and the +// [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for +// documentation about the format. +// +// Omitting `parameters` defines a function with an empty parameter list. +// +// This is an alias to an internal type. +type FunctionParameters = shared.FunctionParameters + +// Set of 16 key-value pairs that can be attached to an object. This can be useful +// for storing additional information about the object in a structured format, and +// querying for objects via API or the dashboard. +// +// Keys are strings with a maximum length of 64 characters. Values are strings with +// a maximum length of 512 characters. +// +// This is an alias to an internal type. +type Metadata = shared.Metadata + +// **gpt-5 and o-series models only** +// +// Configuration options for +// [reasoning models](https://platform.openai.com/docs/guides/reasoning). +// +// This is an alias to an internal type. +type Reasoning = shared.Reasoning + +// **Deprecated:** use `summary` instead. +// +// A summary of the reasoning performed by the model. This can be useful for +// debugging and understanding the model's reasoning process. One of `auto`, +// `concise`, or `detailed`. +// +// This is an alias to an internal type. +type ReasoningGenerateSummary = shared.ReasoningGenerateSummary + +// Equals "auto" +const ReasoningGenerateSummaryAuto = shared.ReasoningGenerateSummaryAuto + +// Equals "concise" +const ReasoningGenerateSummaryConcise = shared.ReasoningGenerateSummaryConcise + +// Equals "detailed" +const ReasoningGenerateSummaryDetailed = shared.ReasoningGenerateSummaryDetailed + +// A summary of the reasoning performed by the model. This can be useful for +// debugging and understanding the model's reasoning process. One of `auto`, +// `concise`, or `detailed`. +// +// This is an alias to an internal type. +type ReasoningSummary = shared.ReasoningSummary + +// Equals "auto" +const ReasoningSummaryAuto = shared.ReasoningSummaryAuto + +// Equals "concise" +const ReasoningSummaryConcise = shared.ReasoningSummaryConcise + +// Equals "detailed" +const ReasoningSummaryDetailed = shared.ReasoningSummaryDetailed + +// **gpt-5 and o-series models only** +// +// Configuration options for +// [reasoning models](https://platform.openai.com/docs/guides/reasoning). +// +// This is an alias to an internal type. +type ReasoningParam = shared.ReasoningParam + +// Constrains effort on reasoning for +// [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently +// supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning +// effort can result in faster responses and fewer tokens used on reasoning in a +// response. +// +// This is an alias to an internal type. +type ReasoningEffort = shared.ReasoningEffort + +// Equals "minimal" +const ReasoningEffortMinimal = shared.ReasoningEffortMinimal + +// Equals "low" +const ReasoningEffortLow = shared.ReasoningEffortLow + +// Equals "medium" +const ReasoningEffortMedium = shared.ReasoningEffortMedium + +// Equals "high" +const ReasoningEffortHigh = shared.ReasoningEffortHigh + +// JSON object response format. An older method of generating JSON responses. Using +// `json_schema` is recommended for models that support it. Note that the model +// will not generate JSON without a system or user message instructing it to do so. +// +// This is an alias to an internal type. +type ResponseFormatJSONObject = shared.ResponseFormatJSONObject + +// JSON object response format. An older method of generating JSON responses. Using +// `json_schema` is recommended for models that support it. Note that the model +// will not generate JSON without a system or user message instructing it to do so. +// +// This is an alias to an internal type. +type ResponseFormatJSONObjectParam = shared.ResponseFormatJSONObjectParam + +// JSON Schema response format. Used to generate structured JSON responses. Learn +// more about +// [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). +// +// This is an alias to an internal type. +type ResponseFormatJSONSchema = shared.ResponseFormatJSONSchema + +// Structured Outputs configuration options, including a JSON Schema. +// +// This is an alias to an internal type. +type ResponseFormatJSONSchemaJSONSchema = shared.ResponseFormatJSONSchemaJSONSchema + +// JSON Schema response format. Used to generate structured JSON responses. Learn +// more about +// [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). +// +// This is an alias to an internal type. +type ResponseFormatJSONSchemaParam = shared.ResponseFormatJSONSchemaParam + +// Structured Outputs configuration options, including a JSON Schema. +// +// This is an alias to an internal type. +type ResponseFormatJSONSchemaJSONSchemaParam = shared.ResponseFormatJSONSchemaJSONSchemaParam + +// Default response format. Used to generate text responses. +// +// This is an alias to an internal type. +type ResponseFormatText = shared.ResponseFormatText + +// Default response format. Used to generate text responses. +// +// This is an alias to an internal type. +type ResponseFormatTextParam = shared.ResponseFormatTextParam + +// This is an alias to an internal type. +type ResponsesModel = shared.ResponsesModel + +// Equals "o1-pro" +const ResponsesModelO1Pro = shared.ResponsesModelO1Pro + +// Equals "o1-pro-2025-03-19" +const ResponsesModelO1Pro2025_03_19 = shared.ResponsesModelO1Pro2025_03_19 + +// Equals "o3-pro" +const ResponsesModelO3Pro = shared.ResponsesModelO3Pro + +// Equals "o3-pro-2025-06-10" +const ResponsesModelO3Pro2025_06_10 = shared.ResponsesModelO3Pro2025_06_10 + +// Equals "o3-deep-research" +const ResponsesModelO3DeepResearch = shared.ResponsesModelO3DeepResearch + +// Equals "o3-deep-research-2025-06-26" +const ResponsesModelO3DeepResearch2025_06_26 = shared.ResponsesModelO3DeepResearch2025_06_26 + +// Equals "o4-mini-deep-research" +const ResponsesModelO4MiniDeepResearch = shared.ResponsesModelO4MiniDeepResearch + +// Equals "o4-mini-deep-research-2025-06-26" +const ResponsesModelO4MiniDeepResearch2025_06_26 = shared.ResponsesModelO4MiniDeepResearch2025_06_26 + +// Equals "computer-use-preview" +const ResponsesModelComputerUsePreview = shared.ResponsesModelComputerUsePreview + +// Equals "computer-use-preview-2025-03-11" +const ResponsesModelComputerUsePreview2025_03_11 = shared.ResponsesModelComputerUsePreview2025_03_11 diff --git a/conversations/conversation.go b/conversations/conversation.go new file mode 100644 index 00000000..b9e9d31c --- /dev/null +++ b/conversations/conversation.go @@ -0,0 +1,783 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package conversations + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + + "github.com/openai/openai-go/v2/internal/apijson" + "github.com/openai/openai-go/v2/internal/requestconfig" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/packages/param" + "github.com/openai/openai-go/v2/packages/respjson" + "github.com/openai/openai-go/v2/responses" + "github.com/openai/openai-go/v2/shared" + "github.com/openai/openai-go/v2/shared/constant" +) + +// ConversationService contains methods and other services that help with +// interacting with the openai API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewConversationService] method instead. +type ConversationService struct { + Options []option.RequestOption + Items ItemService +} + +// NewConversationService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewConversationService(opts ...option.RequestOption) (r ConversationService) { + r = ConversationService{} + r.Options = opts + r.Items = NewItemService(opts...) + return +} + +// Create a conversation with the given ID. +func (r *ConversationService) New(ctx context.Context, body ConversationNewParams, opts ...option.RequestOption) (res *Conversation, err error) { + opts = append(r.Options[:], opts...) + path := "conversations" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return +} + +// Get a conversation with the given ID. +func (r *ConversationService) Get(ctx context.Context, conversationID string, opts ...option.RequestOption) (res *Conversation, err error) { + opts = append(r.Options[:], opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + path := fmt.Sprintf("conversations/%s", conversationID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return +} + +// Update a conversation's metadata with the given ID. +func (r *ConversationService) Update(ctx context.Context, conversationID string, body ConversationUpdateParams, opts ...option.RequestOption) (res *Conversation, err error) { + opts = append(r.Options[:], opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + path := fmt.Sprintf("conversations/%s", conversationID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return +} + +// Delete a conversation with the given ID. +func (r *ConversationService) Delete(ctx context.Context, conversationID string, opts ...option.RequestOption) (res *ConversationDeletedResource, err error) { + opts = append(r.Options[:], opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + path := fmt.Sprintf("conversations/%s", conversationID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return +} + +type ComputerScreenshotContent struct { + // The identifier of an uploaded file that contains the screenshot. + FileID string `json:"file_id,required"` + // The URL of the screenshot image. + ImageURL string `json:"image_url,required"` + // Specifies the event type. For a computer screenshot, this property is always set + // to `computer_screenshot`. + Type constant.ComputerScreenshot `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + ImageURL respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ComputerScreenshotContent) RawJSON() string { return r.JSON.raw } +func (r *ComputerScreenshotContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ContainerFileCitationBody struct { + // The ID of the container file. + ContainerID string `json:"container_id,required"` + // The index of the last character of the container file citation in the message. + EndIndex int64 `json:"end_index,required"` + // The ID of the file. + FileID string `json:"file_id,required"` + // The filename of the container file cited. + Filename string `json:"filename,required"` + // The index of the first character of the container file citation in the message. + StartIndex int64 `json:"start_index,required"` + // The type of the container file citation. Always `container_file_citation`. + Type constant.ContainerFileCitation `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ContainerID respjson.Field + EndIndex respjson.Field + FileID respjson.Field + Filename respjson.Field + StartIndex respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ContainerFileCitationBody) RawJSON() string { return r.JSON.raw } +func (r *ContainerFileCitationBody) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type Conversation struct { + // The unique ID of the conversation. + ID string `json:"id,required"` + // The time at which the conversation was created, measured in seconds since the + // Unix epoch. + CreatedAt int64 `json:"created_at,required"` + // Set of 16 key-value pairs that can be attached to an object. This can be useful + // for storing additional information about the object in a structured format, and + // querying for objects via API or the dashboard. Keys are strings with a maximum + // length of 64 characters. Values are strings with a maximum length of 512 + // characters. + Metadata any `json:"metadata,required"` + // The object type, which is always `conversation`. + Object constant.Conversation `json:"object,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + Metadata respjson.Field + Object respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r Conversation) RawJSON() string { return r.JSON.raw } +func (r *Conversation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ConversationDeletedResource struct { + ID string `json:"id,required"` + Deleted bool `json:"deleted,required"` + Object constant.ConversationDeleted `json:"object,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Deleted respjson.Field + Object respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationDeletedResource) RawJSON() string { return r.JSON.raw } +func (r *ConversationDeletedResource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type FileCitationBody struct { + // The ID of the file. + FileID string `json:"file_id,required"` + // The filename of the file cited. + Filename string `json:"filename,required"` + // The index of the file in the list of files. + Index int64 `json:"index,required"` + // The type of the file citation. Always `file_citation`. + Type constant.FileCitation `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + Filename respjson.Field + Index respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r FileCitationBody) RawJSON() string { return r.JSON.raw } +func (r *FileCitationBody) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type InputFileContent struct { + // The ID of the file to be sent to the model. + FileID string `json:"file_id,required"` + // The type of the input item. Always `input_file`. + Type constant.InputFile `json:"type,required"` + // The URL of the file to be sent to the model. + FileURL string `json:"file_url"` + // The name of the file to be sent to the model. + Filename string `json:"filename"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + Type respjson.Field + FileURL respjson.Field + Filename respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r InputFileContent) RawJSON() string { return r.JSON.raw } +func (r *InputFileContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type InputImageContent struct { + // The detail level of the image to be sent to the model. One of `high`, `low`, or + // `auto`. Defaults to `auto`. + // + // Any of "low", "high", "auto". + Detail InputImageContentDetail `json:"detail,required"` + // The ID of the file to be sent to the model. + FileID string `json:"file_id,required"` + // The URL of the image to be sent to the model. A fully qualified URL or base64 + // encoded image in a data URL. + ImageURL string `json:"image_url,required"` + // The type of the input item. Always `input_image`. + Type constant.InputImage `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Detail respjson.Field + FileID respjson.Field + ImageURL respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r InputImageContent) RawJSON() string { return r.JSON.raw } +func (r *InputImageContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The detail level of the image to be sent to the model. One of `high`, `low`, or +// `auto`. Defaults to `auto`. +type InputImageContentDetail string + +const ( + InputImageContentDetailLow InputImageContentDetail = "low" + InputImageContentDetailHigh InputImageContentDetail = "high" + InputImageContentDetailAuto InputImageContentDetail = "auto" +) + +type InputTextContent struct { + // The text input to the model. + Text string `json:"text,required"` + // The type of the input item. Always `input_text`. + Type constant.InputText `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Text respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r InputTextContent) RawJSON() string { return r.JSON.raw } +func (r *InputTextContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type LobProb struct { + Token string `json:"token,required"` + Bytes []int64 `json:"bytes,required"` + Logprob float64 `json:"logprob,required"` + TopLogprobs []TopLogProb `json:"top_logprobs,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Token respjson.Field + Bytes respjson.Field + Logprob respjson.Field + TopLogprobs respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r LobProb) RawJSON() string { return r.JSON.raw } +func (r *LobProb) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type Message struct { + // The unique ID of the message. + ID string `json:"id,required"` + // The content of the message + Content []MessageContentUnion `json:"content,required"` + // The role of the message. One of `unknown`, `user`, `assistant`, `system`, + // `critic`, `discriminator`, `developer`, or `tool`. + // + // Any of "unknown", "user", "assistant", "system", "critic", "discriminator", + // "developer", "tool". + Role MessageRole `json:"role,required"` + // The status of item. One of `in_progress`, `completed`, or `incomplete`. + // Populated when items are returned via API. + // + // Any of "in_progress", "completed", "incomplete". + Status MessageStatus `json:"status,required"` + // The type of the message. Always set to `message`. + Type constant.Message `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Content respjson.Field + Role respjson.Field + Status respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r Message) RawJSON() string { return r.JSON.raw } +func (r *Message) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// MessageContentUnion contains all possible properties and values from +// [InputTextContent], [OutputTextContent], [TextContent], [SummaryTextContent], +// [RefusalContent], [InputImageContent], [ComputerScreenshotContent], +// [InputFileContent]. +// +// Use the [MessageContentUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type MessageContentUnion struct { + Text string `json:"text"` + // Any of "input_text", "output_text", "text", "summary_text", "refusal", + // "input_image", "computer_screenshot", "input_file". + Type string `json:"type"` + // This field is from variant [OutputTextContent]. + Annotations []OutputTextContentAnnotationUnion `json:"annotations"` + // This field is from variant [OutputTextContent]. + Logprobs []LobProb `json:"logprobs"` + // This field is from variant [RefusalContent]. + Refusal string `json:"refusal"` + // This field is from variant [InputImageContent]. + Detail InputImageContentDetail `json:"detail"` + FileID string `json:"file_id"` + ImageURL string `json:"image_url"` + // This field is from variant [InputFileContent]. + FileURL string `json:"file_url"` + // This field is from variant [InputFileContent]. + Filename string `json:"filename"` + JSON struct { + Text respjson.Field + Type respjson.Field + Annotations respjson.Field + Logprobs respjson.Field + Refusal respjson.Field + Detail respjson.Field + FileID respjson.Field + ImageURL respjson.Field + FileURL respjson.Field + Filename respjson.Field + raw string + } `json:"-"` +} + +// anyMessageContent is implemented by each variant of [MessageContentUnion] to add +// type safety for the return type of [MessageContentUnion.AsAny] +type anyMessageContent interface { + implMessageContentUnion() +} + +func (InputTextContent) implMessageContentUnion() {} +func (OutputTextContent) implMessageContentUnion() {} +func (TextContent) implMessageContentUnion() {} +func (SummaryTextContent) implMessageContentUnion() {} +func (RefusalContent) implMessageContentUnion() {} +func (InputImageContent) implMessageContentUnion() {} +func (ComputerScreenshotContent) implMessageContentUnion() {} +func (InputFileContent) implMessageContentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := MessageContentUnion.AsAny().(type) { +// case conversations.InputTextContent: +// case conversations.OutputTextContent: +// case conversations.TextContent: +// case conversations.SummaryTextContent: +// case conversations.RefusalContent: +// case conversations.InputImageContent: +// case conversations.ComputerScreenshotContent: +// case conversations.InputFileContent: +// default: +// fmt.Errorf("no variant present") +// } +func (u MessageContentUnion) AsAny() anyMessageContent { + switch u.Type { + case "input_text": + return u.AsInputText() + case "output_text": + return u.AsOutputText() + case "text": + return u.AsText() + case "summary_text": + return u.AsSummaryText() + case "refusal": + return u.AsRefusal() + case "input_image": + return u.AsInputImage() + case "computer_screenshot": + return u.AsComputerScreenshot() + case "input_file": + return u.AsInputFile() + } + return nil +} + +func (u MessageContentUnion) AsInputText() (v InputTextContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsOutputText() (v OutputTextContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsText() (v TextContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsSummaryText() (v SummaryTextContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsRefusal() (v RefusalContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsInputImage() (v InputImageContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsComputerScreenshot() (v ComputerScreenshotContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageContentUnion) AsInputFile() (v InputFileContent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u MessageContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *MessageContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The role of the message. One of `unknown`, `user`, `assistant`, `system`, +// `critic`, `discriminator`, `developer`, or `tool`. +type MessageRole string + +const ( + MessageRoleUnknown MessageRole = "unknown" + MessageRoleUser MessageRole = "user" + MessageRoleAssistant MessageRole = "assistant" + MessageRoleSystem MessageRole = "system" + MessageRoleCritic MessageRole = "critic" + MessageRoleDiscriminator MessageRole = "discriminator" + MessageRoleDeveloper MessageRole = "developer" + MessageRoleTool MessageRole = "tool" +) + +// The status of item. One of `in_progress`, `completed`, or `incomplete`. +// Populated when items are returned via API. +type MessageStatus string + +const ( + MessageStatusInProgress MessageStatus = "in_progress" + MessageStatusCompleted MessageStatus = "completed" + MessageStatusIncomplete MessageStatus = "incomplete" +) + +type OutputTextContent struct { + // The annotations of the text output. + Annotations []OutputTextContentAnnotationUnion `json:"annotations,required"` + // The text output from the model. + Text string `json:"text,required"` + // The type of the output text. Always `output_text`. + Type constant.OutputText `json:"type,required"` + Logprobs []LobProb `json:"logprobs"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Annotations respjson.Field + Text respjson.Field + Type respjson.Field + Logprobs respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r OutputTextContent) RawJSON() string { return r.JSON.raw } +func (r *OutputTextContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// OutputTextContentAnnotationUnion contains all possible properties and values +// from [FileCitationBody], [URLCitationBody], [ContainerFileCitationBody]. +// +// Use the [OutputTextContentAnnotationUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type OutputTextContentAnnotationUnion struct { + FileID string `json:"file_id"` + Filename string `json:"filename"` + // This field is from variant [FileCitationBody]. + Index int64 `json:"index"` + // Any of "file_citation", "url_citation", "container_file_citation". + Type string `json:"type"` + EndIndex int64 `json:"end_index"` + StartIndex int64 `json:"start_index"` + // This field is from variant [URLCitationBody]. + Title string `json:"title"` + // This field is from variant [URLCitationBody]. + URL string `json:"url"` + // This field is from variant [ContainerFileCitationBody]. + ContainerID string `json:"container_id"` + JSON struct { + FileID respjson.Field + Filename respjson.Field + Index respjson.Field + Type respjson.Field + EndIndex respjson.Field + StartIndex respjson.Field + Title respjson.Field + URL respjson.Field + ContainerID respjson.Field + raw string + } `json:"-"` +} + +// anyOutputTextContentAnnotation is implemented by each variant of +// [OutputTextContentAnnotationUnion] to add type safety for the return type of +// [OutputTextContentAnnotationUnion.AsAny] +type anyOutputTextContentAnnotation interface { + implOutputTextContentAnnotationUnion() +} + +func (FileCitationBody) implOutputTextContentAnnotationUnion() {} +func (URLCitationBody) implOutputTextContentAnnotationUnion() {} +func (ContainerFileCitationBody) implOutputTextContentAnnotationUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := OutputTextContentAnnotationUnion.AsAny().(type) { +// case conversations.FileCitationBody: +// case conversations.URLCitationBody: +// case conversations.ContainerFileCitationBody: +// default: +// fmt.Errorf("no variant present") +// } +func (u OutputTextContentAnnotationUnion) AsAny() anyOutputTextContentAnnotation { + switch u.Type { + case "file_citation": + return u.AsFileCitation() + case "url_citation": + return u.AsURLCitation() + case "container_file_citation": + return u.AsContainerFileCitation() + } + return nil +} + +func (u OutputTextContentAnnotationUnion) AsFileCitation() (v FileCitationBody) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u OutputTextContentAnnotationUnion) AsURLCitation() (v URLCitationBody) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u OutputTextContentAnnotationUnion) AsContainerFileCitation() (v ContainerFileCitationBody) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u OutputTextContentAnnotationUnion) RawJSON() string { return u.JSON.raw } + +func (r *OutputTextContentAnnotationUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type RefusalContent struct { + // The refusal explanation from the model. + Refusal string `json:"refusal,required"` + // The type of the refusal. Always `refusal`. + Type constant.Refusal `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Refusal respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RefusalContent) RawJSON() string { return r.JSON.raw } +func (r *RefusalContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type SummaryTextContent struct { + Text string `json:"text,required"` + Type constant.SummaryText `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Text respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r SummaryTextContent) RawJSON() string { return r.JSON.raw } +func (r *SummaryTextContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type TextContent struct { + Text string `json:"text,required"` + Type constant.Text `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Text respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r TextContent) RawJSON() string { return r.JSON.raw } +func (r *TextContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type TopLogProb struct { + Token string `json:"token,required"` + Bytes []int64 `json:"bytes,required"` + Logprob float64 `json:"logprob,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Token respjson.Field + Bytes respjson.Field + Logprob respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r TopLogProb) RawJSON() string { return r.JSON.raw } +func (r *TopLogProb) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type URLCitationBody struct { + // The index of the last character of the URL citation in the message. + EndIndex int64 `json:"end_index,required"` + // The index of the first character of the URL citation in the message. + StartIndex int64 `json:"start_index,required"` + // The title of the web resource. + Title string `json:"title,required"` + // The type of the URL citation. Always `url_citation`. + Type constant.URLCitation `json:"type,required"` + // The URL of the web resource. + URL string `json:"url,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + EndIndex respjson.Field + StartIndex respjson.Field + Title respjson.Field + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r URLCitationBody) RawJSON() string { return r.JSON.raw } +func (r *URLCitationBody) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ConversationNewParams struct { + // Initial items to include in the conversation context. You may add up to 20 items + // at a time. + Items []responses.ResponseInputItemUnionParam `json:"items,omitzero"` + // Set of 16 key-value pairs that can be attached to an object. Useful for storing + // additional information about the object in a structured format. + Metadata shared.Metadata `json:"metadata,omitzero"` + paramObj +} + +func (r ConversationNewParams) MarshalJSON() (data []byte, err error) { + type shadow ConversationNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ConversationNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ConversationUpdateParams struct { + // Set of 16 key-value pairs that can be attached to an object. This can be useful + // for storing additional information about the object in a structured format, and + // querying for objects via API or the dashboard. Keys are strings with a maximum + // length of 64 characters. Values are strings with a maximum length of 512 + // characters. + Metadata map[string]string `json:"metadata,omitzero,required"` + paramObj +} + +func (r ConversationUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow ConversationUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ConversationUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} diff --git a/conversations/conversation_test.go b/conversations/conversation_test.go new file mode 100644 index 00000000..9b0888fd --- /dev/null +++ b/conversations/conversation_test.go @@ -0,0 +1,126 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package conversations_test + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/openai/openai-go/v2" + "github.com/openai/openai-go/v2/conversations" + "github.com/openai/openai-go/v2/internal/testutil" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/responses" + "github.com/openai/openai-go/v2/shared" +) + +func TestConversationNewWithOptionalParams(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.New(context.TODO(), conversations.ConversationNewParams{ + Items: []responses.ResponseInputItemUnionParam{{ + OfMessage: &responses.EasyInputMessageParam{ + Content: responses.EasyInputMessageContentUnionParam{ + OfString: openai.String("string"), + }, + Role: responses.EasyInputMessageRoleUser, + Type: responses.EasyInputMessageTypeMessage, + }, + }}, + Metadata: shared.Metadata{ + "foo": "string", + }, + }) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} + +func TestConversationGet(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Get(context.TODO(), "conv_123") + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} + +func TestConversationUpdate(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Update( + context.TODO(), + "conv_123", + conversations.ConversationUpdateParams{ + Metadata: map[string]string{ + "foo": "string", + }, + }, + ) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} + +func TestConversationDelete(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Delete(context.TODO(), "conv_123") + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} diff --git a/conversations/item.go b/conversations/item.go new file mode 100644 index 00000000..450f5d4b --- /dev/null +++ b/conversations/item.go @@ -0,0 +1,916 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package conversations + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + + "github.com/openai/openai-go/v2/internal/apijson" + "github.com/openai/openai-go/v2/internal/apiquery" + "github.com/openai/openai-go/v2/internal/requestconfig" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/packages/pagination" + "github.com/openai/openai-go/v2/packages/param" + "github.com/openai/openai-go/v2/packages/respjson" + "github.com/openai/openai-go/v2/responses" + "github.com/openai/openai-go/v2/shared/constant" +) + +// ItemService contains methods and other services that help with interacting with +// the openai API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewItemService] method instead. +type ItemService struct { + Options []option.RequestOption +} + +// NewItemService generates a new service that applies the given options to each +// request. These options are applied after the parent client's options (if there +// is one), and before any request-specific options. +func NewItemService(opts ...option.RequestOption) (r ItemService) { + r = ItemService{} + r.Options = opts + return +} + +// Create items in a conversation with the given ID. +func (r *ItemService) New(ctx context.Context, conversationID string, params ItemNewParams, opts ...option.RequestOption) (res *ConversationItemList, err error) { + opts = append(r.Options[:], opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + path := fmt.Sprintf("conversations/%s/items", conversationID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return +} + +// Get a single item from a conversation with the given IDs. +func (r *ItemService) Get(ctx context.Context, conversationID string, itemID string, query ItemGetParams, opts ...option.RequestOption) (res *ConversationItemUnion, err error) { + opts = append(r.Options[:], opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + if itemID == "" { + err = errors.New("missing required item_id parameter") + return + } + path := fmt.Sprintf("conversations/%s/items/%s", conversationID, itemID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...) + return +} + +// List all items for a conversation with the given ID. +func (r *ItemService) List(ctx context.Context, conversationID string, query ItemListParams, opts ...option.RequestOption) (res *pagination.ConversationCursorPage[ConversationItemUnion], err error) { + var raw *http.Response + opts = append(r.Options[:], opts...) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + path := fmt.Sprintf("conversations/%s/items", conversationID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List all items for a conversation with the given ID. +func (r *ItemService) ListAutoPaging(ctx context.Context, conversationID string, query ItemListParams, opts ...option.RequestOption) *pagination.ConversationCursorPageAutoPager[ConversationItemUnion] { + return pagination.NewConversationCursorPageAutoPager(r.List(ctx, conversationID, query, opts...)) +} + +// Delete an item from a conversation with the given IDs. +func (r *ItemService) Delete(ctx context.Context, conversationID string, itemID string, opts ...option.RequestOption) (res *Conversation, err error) { + opts = append(r.Options[:], opts...) + if conversationID == "" { + err = errors.New("missing required conversation_id parameter") + return + } + if itemID == "" { + err = errors.New("missing required item_id parameter") + return + } + path := fmt.Sprintf("conversations/%s/items/%s", conversationID, itemID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return +} + +// ConversationItemUnion contains all possible properties and values from +// [Message], [responses.ResponseFunctionToolCallItem], +// [responses.ResponseFunctionToolCallOutputItem], +// [responses.ResponseFileSearchToolCall], [responses.ResponseFunctionWebSearch], +// [ConversationItemImageGenerationCall], [responses.ResponseComputerToolCall], +// [responses.ResponseComputerToolCallOutputItem], +// [responses.ResponseReasoningItem], [responses.ResponseCodeInterpreterToolCall], +// [ConversationItemLocalShellCall], [ConversationItemLocalShellCallOutput], +// [ConversationItemMcpListTools], [ConversationItemMcpApprovalRequest], +// [ConversationItemMcpApprovalResponse], [ConversationItemMcpCall], +// [responses.ResponseCustomToolCall], [responses.ResponseCustomToolCallOutput]. +// +// Use the [ConversationItemUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type ConversationItemUnion struct { + ID string `json:"id"` + // This field is a union of [[]MessageContentUnion], + // [[]responses.ResponseReasoningItemContent] + Content ConversationItemUnionContent `json:"content"` + // This field is from variant [Message]. + Role MessageRole `json:"role"` + Status string `json:"status"` + // Any of "message", "function_call", "function_call_output", "file_search_call", + // "web_search_call", "image_generation_call", "computer_call", + // "computer_call_output", "reasoning", "code_interpreter_call", + // "local_shell_call", "local_shell_call_output", "mcp_list_tools", + // "mcp_approval_request", "mcp_approval_response", "mcp_call", "custom_tool_call", + // "custom_tool_call_output". + Type string `json:"type"` + Arguments string `json:"arguments"` + CallID string `json:"call_id"` + Name string `json:"name"` + // This field is a union of [string], + // [responses.ResponseComputerToolCallOutputScreenshot], [string], [string], + // [string] + Output ConversationItemUnionOutput `json:"output"` + // This field is from variant [responses.ResponseFileSearchToolCall]. + Queries []string `json:"queries"` + // This field is from variant [responses.ResponseFileSearchToolCall]. + Results []responses.ResponseFileSearchToolCallResult `json:"results"` + // This field is a union of [responses.ResponseFunctionWebSearchActionUnion], + // [responses.ResponseComputerToolCallActionUnion], + // [ConversationItemLocalShellCallAction] + Action ConversationItemUnionAction `json:"action"` + // This field is from variant [ConversationItemImageGenerationCall]. + Result string `json:"result"` + // This field is from variant [responses.ResponseComputerToolCall]. + PendingSafetyChecks []responses.ResponseComputerToolCallPendingSafetyCheck `json:"pending_safety_checks"` + // This field is from variant [responses.ResponseComputerToolCallOutputItem]. + AcknowledgedSafetyChecks []responses.ResponseComputerToolCallOutputItemAcknowledgedSafetyCheck `json:"acknowledged_safety_checks"` + // This field is from variant [responses.ResponseReasoningItem]. + Summary []responses.ResponseReasoningItemSummary `json:"summary"` + // This field is from variant [responses.ResponseReasoningItem]. + EncryptedContent string `json:"encrypted_content"` + // This field is from variant [responses.ResponseCodeInterpreterToolCall]. + Code string `json:"code"` + // This field is from variant [responses.ResponseCodeInterpreterToolCall]. + ContainerID string `json:"container_id"` + // This field is from variant [responses.ResponseCodeInterpreterToolCall]. + Outputs []responses.ResponseCodeInterpreterToolCallOutputUnion `json:"outputs"` + ServerLabel string `json:"server_label"` + // This field is from variant [ConversationItemMcpListTools]. + Tools []ConversationItemMcpListToolsTool `json:"tools"` + Error string `json:"error"` + // This field is from variant [ConversationItemMcpApprovalResponse]. + ApprovalRequestID string `json:"approval_request_id"` + // This field is from variant [ConversationItemMcpApprovalResponse]. + Approve bool `json:"approve"` + // This field is from variant [ConversationItemMcpApprovalResponse]. + Reason string `json:"reason"` + // This field is from variant [responses.ResponseCustomToolCall]. + Input string `json:"input"` + JSON struct { + ID respjson.Field + Content respjson.Field + Role respjson.Field + Status respjson.Field + Type respjson.Field + Arguments respjson.Field + CallID respjson.Field + Name respjson.Field + Output respjson.Field + Queries respjson.Field + Results respjson.Field + Action respjson.Field + Result respjson.Field + PendingSafetyChecks respjson.Field + AcknowledgedSafetyChecks respjson.Field + Summary respjson.Field + EncryptedContent respjson.Field + Code respjson.Field + ContainerID respjson.Field + Outputs respjson.Field + ServerLabel respjson.Field + Tools respjson.Field + Error respjson.Field + ApprovalRequestID respjson.Field + Approve respjson.Field + Reason respjson.Field + Input respjson.Field + raw string + } `json:"-"` +} + +// anyConversationItem is implemented by each variant of [ConversationItemUnion] to +// add type safety for the return type of [ConversationItemUnion.AsAny] +type anyConversationItem interface { + ImplConversationItemUnion() +} + +func (Message) ImplConversationItemUnion() {} +func (ConversationItemImageGenerationCall) ImplConversationItemUnion() {} +func (ConversationItemLocalShellCall) ImplConversationItemUnion() {} +func (ConversationItemLocalShellCallOutput) ImplConversationItemUnion() {} +func (ConversationItemMcpListTools) ImplConversationItemUnion() {} +func (ConversationItemMcpApprovalRequest) ImplConversationItemUnion() {} +func (ConversationItemMcpApprovalResponse) ImplConversationItemUnion() {} +func (ConversationItemMcpCall) ImplConversationItemUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := ConversationItemUnion.AsAny().(type) { +// case conversations.Message: +// case responses.ResponseFunctionToolCallItem: +// case responses.ResponseFunctionToolCallOutputItem: +// case responses.ResponseFileSearchToolCall: +// case responses.ResponseFunctionWebSearch: +// case conversations.ConversationItemImageGenerationCall: +// case responses.ResponseComputerToolCall: +// case responses.ResponseComputerToolCallOutputItem: +// case responses.ResponseReasoningItem: +// case responses.ResponseCodeInterpreterToolCall: +// case conversations.ConversationItemLocalShellCall: +// case conversations.ConversationItemLocalShellCallOutput: +// case conversations.ConversationItemMcpListTools: +// case conversations.ConversationItemMcpApprovalRequest: +// case conversations.ConversationItemMcpApprovalResponse: +// case conversations.ConversationItemMcpCall: +// case responses.ResponseCustomToolCall: +// case responses.ResponseCustomToolCallOutput: +// default: +// fmt.Errorf("no variant present") +// } +func (u ConversationItemUnion) AsAny() anyConversationItem { + switch u.Type { + case "message": + return u.AsMessage() + case "function_call": + return u.AsFunctionCall() + case "function_call_output": + return u.AsFunctionCallOutput() + case "file_search_call": + return u.AsFileSearchCall() + case "web_search_call": + return u.AsWebSearchCall() + case "image_generation_call": + return u.AsImageGenerationCall() + case "computer_call": + return u.AsComputerCall() + case "computer_call_output": + return u.AsComputerCallOutput() + case "reasoning": + return u.AsReasoning() + case "code_interpreter_call": + return u.AsCodeInterpreterCall() + case "local_shell_call": + return u.AsLocalShellCall() + case "local_shell_call_output": + return u.AsLocalShellCallOutput() + case "mcp_list_tools": + return u.AsMcpListTools() + case "mcp_approval_request": + return u.AsMcpApprovalRequest() + case "mcp_approval_response": + return u.AsMcpApprovalResponse() + case "mcp_call": + return u.AsMcpCall() + case "custom_tool_call": + return u.AsCustomToolCall() + case "custom_tool_call_output": + return u.AsCustomToolCallOutput() + } + return nil +} + +func (u ConversationItemUnion) AsMessage() (v Message) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsFunctionCall() (v responses.ResponseFunctionToolCallItem) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsFunctionCallOutput() (v responses.ResponseFunctionToolCallOutputItem) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsFileSearchCall() (v responses.ResponseFileSearchToolCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsWebSearchCall() (v responses.ResponseFunctionWebSearch) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsImageGenerationCall() (v ConversationItemImageGenerationCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsComputerCall() (v responses.ResponseComputerToolCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsComputerCallOutput() (v responses.ResponseComputerToolCallOutputItem) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsReasoning() (v responses.ResponseReasoningItem) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsCodeInterpreterCall() (v responses.ResponseCodeInterpreterToolCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsLocalShellCall() (v ConversationItemLocalShellCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsLocalShellCallOutput() (v ConversationItemLocalShellCallOutput) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsMcpListTools() (v ConversationItemMcpListTools) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsMcpApprovalRequest() (v ConversationItemMcpApprovalRequest) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsMcpApprovalResponse() (v ConversationItemMcpApprovalResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsMcpCall() (v ConversationItemMcpCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsCustomToolCall() (v responses.ResponseCustomToolCall) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ConversationItemUnion) AsCustomToolCallOutput() (v responses.ResponseCustomToolCallOutput) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u ConversationItemUnion) RawJSON() string { return u.JSON.raw } + +func (r *ConversationItemUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ConversationItemUnionContent is an implicit subunion of [ConversationItemUnion]. +// ConversationItemUnionContent provides convenient access to the sub-properties of +// the union. +// +// For type safety it is recommended to directly use a variant of the +// [ConversationItemUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfMessageContentArray OfResponseReasoningItemContentArray] +type ConversationItemUnionContent struct { + // This field will be present if the value is a [[]MessageContentUnion] instead of + // an object. + OfMessageContentArray []MessageContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]responses.ResponseReasoningItemContent] instead of an object. + OfResponseReasoningItemContentArray []responses.ResponseReasoningItemContent `json:",inline"` + JSON struct { + OfMessageContentArray respjson.Field + OfResponseReasoningItemContentArray respjson.Field + raw string + } `json:"-"` +} + +func (r *ConversationItemUnionContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ConversationItemUnionOutput is an implicit subunion of [ConversationItemUnion]. +// ConversationItemUnionOutput provides convenient access to the sub-properties of +// the union. +// +// For type safety it is recommended to directly use a variant of the +// [ConversationItemUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] +type ConversationItemUnionOutput struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field is from variant [responses.ResponseComputerToolCallOutputScreenshot]. + Type constant.ComputerScreenshot `json:"type"` + // This field is from variant [responses.ResponseComputerToolCallOutputScreenshot]. + FileID string `json:"file_id"` + // This field is from variant [responses.ResponseComputerToolCallOutputScreenshot]. + ImageURL string `json:"image_url"` + JSON struct { + OfString respjson.Field + Type respjson.Field + FileID respjson.Field + ImageURL respjson.Field + raw string + } `json:"-"` +} + +func (r *ConversationItemUnionOutput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ConversationItemUnionAction is an implicit subunion of [ConversationItemUnion]. +// ConversationItemUnionAction provides convenient access to the sub-properties of +// the union. +// +// For type safety it is recommended to directly use a variant of the +// [ConversationItemUnion]. +type ConversationItemUnionAction struct { + // This field is from variant [responses.ResponseFunctionWebSearchActionUnion]. + Query string `json:"query"` + Type string `json:"type"` + URL string `json:"url"` + // This field is from variant [responses.ResponseFunctionWebSearchActionUnion]. + Pattern string `json:"pattern"` + // This field is from variant [responses.ResponseComputerToolCallActionUnion]. + Button string `json:"button"` + X int64 `json:"x"` + Y int64 `json:"y"` + // This field is from variant [responses.ResponseComputerToolCallActionUnion]. + Path []responses.ResponseComputerToolCallActionDragPath `json:"path"` + // This field is from variant [responses.ResponseComputerToolCallActionUnion]. + Keys []string `json:"keys"` + // This field is from variant [responses.ResponseComputerToolCallActionUnion]. + ScrollX int64 `json:"scroll_x"` + // This field is from variant [responses.ResponseComputerToolCallActionUnion]. + ScrollY int64 `json:"scroll_y"` + // This field is from variant [responses.ResponseComputerToolCallActionUnion]. + Text string `json:"text"` + // This field is from variant [ConversationItemLocalShellCallAction]. + Command []string `json:"command"` + // This field is from variant [ConversationItemLocalShellCallAction]. + Env map[string]string `json:"env"` + // This field is from variant [ConversationItemLocalShellCallAction]. + TimeoutMs int64 `json:"timeout_ms"` + // This field is from variant [ConversationItemLocalShellCallAction]. + User string `json:"user"` + // This field is from variant [ConversationItemLocalShellCallAction]. + WorkingDirectory string `json:"working_directory"` + JSON struct { + Query respjson.Field + Type respjson.Field + URL respjson.Field + Pattern respjson.Field + Button respjson.Field + X respjson.Field + Y respjson.Field + Path respjson.Field + Keys respjson.Field + ScrollX respjson.Field + ScrollY respjson.Field + Text respjson.Field + Command respjson.Field + Env respjson.Field + TimeoutMs respjson.Field + User respjson.Field + WorkingDirectory respjson.Field + raw string + } `json:"-"` +} + +func (r *ConversationItemUnionAction) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// An image generation request made by the model. +type ConversationItemImageGenerationCall struct { + // The unique ID of the image generation call. + ID string `json:"id,required"` + // The generated image encoded in base64. + Result string `json:"result,required"` + // The status of the image generation call. + // + // Any of "in_progress", "completed", "generating", "failed". + Status string `json:"status,required"` + // The type of the image generation call. Always `image_generation_call`. + Type constant.ImageGenerationCall `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Result respjson.Field + Status respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemImageGenerationCall) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemImageGenerationCall) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A tool call to run a command on the local shell. +type ConversationItemLocalShellCall struct { + // The unique ID of the local shell call. + ID string `json:"id,required"` + // Execute a shell command on the server. + Action ConversationItemLocalShellCallAction `json:"action,required"` + // The unique ID of the local shell tool call generated by the model. + CallID string `json:"call_id,required"` + // The status of the local shell call. + // + // Any of "in_progress", "completed", "incomplete". + Status string `json:"status,required"` + // The type of the local shell call. Always `local_shell_call`. + Type constant.LocalShellCall `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Action respjson.Field + CallID respjson.Field + Status respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemLocalShellCall) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemLocalShellCall) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Execute a shell command on the server. +type ConversationItemLocalShellCallAction struct { + // The command to run. + Command []string `json:"command,required"` + // Environment variables to set for the command. + Env map[string]string `json:"env,required"` + // The type of the local shell action. Always `exec`. + Type constant.Exec `json:"type,required"` + // Optional timeout in milliseconds for the command. + TimeoutMs int64 `json:"timeout_ms,nullable"` + // Optional user to run the command as. + User string `json:"user,nullable"` + // Optional working directory to run the command in. + WorkingDirectory string `json:"working_directory,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + Env respjson.Field + Type respjson.Field + TimeoutMs respjson.Field + User respjson.Field + WorkingDirectory respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemLocalShellCallAction) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemLocalShellCallAction) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The output of a local shell tool call. +type ConversationItemLocalShellCallOutput struct { + // The unique ID of the local shell tool call generated by the model. + ID string `json:"id,required"` + // A JSON string of the output of the local shell tool call. + Output string `json:"output,required"` + // The type of the local shell tool call output. Always `local_shell_call_output`. + Type constant.LocalShellCallOutput `json:"type,required"` + // The status of the item. One of `in_progress`, `completed`, or `incomplete`. + // + // Any of "in_progress", "completed", "incomplete". + Status string `json:"status,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Output respjson.Field + Type respjson.Field + Status respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemLocalShellCallOutput) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemLocalShellCallOutput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A list of tools available on an MCP server. +type ConversationItemMcpListTools struct { + // The unique ID of the list. + ID string `json:"id,required"` + // The label of the MCP server. + ServerLabel string `json:"server_label,required"` + // The tools available on the server. + Tools []ConversationItemMcpListToolsTool `json:"tools,required"` + // The type of the item. Always `mcp_list_tools`. + Type constant.McpListTools `json:"type,required"` + // Error message if the server could not list tools. + Error string `json:"error,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ServerLabel respjson.Field + Tools respjson.Field + Type respjson.Field + Error respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemMcpListTools) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemMcpListTools) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A tool available on an MCP server. +type ConversationItemMcpListToolsTool struct { + // The JSON schema describing the tool's input. + InputSchema any `json:"input_schema,required"` + // The name of the tool. + Name string `json:"name,required"` + // Additional annotations about the tool. + Annotations any `json:"annotations,nullable"` + // The description of the tool. + Description string `json:"description,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + InputSchema respjson.Field + Name respjson.Field + Annotations respjson.Field + Description respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemMcpListToolsTool) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemMcpListToolsTool) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A request for human approval of a tool invocation. +type ConversationItemMcpApprovalRequest struct { + // The unique ID of the approval request. + ID string `json:"id,required"` + // A JSON string of arguments for the tool. + Arguments string `json:"arguments,required"` + // The name of the tool to run. + Name string `json:"name,required"` + // The label of the MCP server making the request. + ServerLabel string `json:"server_label,required"` + // The type of the item. Always `mcp_approval_request`. + Type constant.McpApprovalRequest `json:"type,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Arguments respjson.Field + Name respjson.Field + ServerLabel respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemMcpApprovalRequest) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemMcpApprovalRequest) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A response to an MCP approval request. +type ConversationItemMcpApprovalResponse struct { + // The unique ID of the approval response + ID string `json:"id,required"` + // The ID of the approval request being answered. + ApprovalRequestID string `json:"approval_request_id,required"` + // Whether the request was approved. + Approve bool `json:"approve,required"` + // The type of the item. Always `mcp_approval_response`. + Type constant.McpApprovalResponse `json:"type,required"` + // Optional reason for the decision. + Reason string `json:"reason,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ApprovalRequestID respjson.Field + Approve respjson.Field + Type respjson.Field + Reason respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemMcpApprovalResponse) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemMcpApprovalResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// An invocation of a tool on an MCP server. +type ConversationItemMcpCall struct { + // The unique ID of the tool call. + ID string `json:"id,required"` + // A JSON string of the arguments passed to the tool. + Arguments string `json:"arguments,required"` + // The name of the tool that was run. + Name string `json:"name,required"` + // The label of the MCP server running the tool. + ServerLabel string `json:"server_label,required"` + // The type of the item. Always `mcp_call`. + Type constant.McpCall `json:"type,required"` + // The error from the tool call, if any. + Error string `json:"error,nullable"` + // The output from the tool call. + Output string `json:"output,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Arguments respjson.Field + Name respjson.Field + ServerLabel respjson.Field + Type respjson.Field + Error respjson.Field + Output respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemMcpCall) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemMcpCall) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A list of Conversation items. +type ConversationItemList struct { + // A list of conversation items. + Data []ConversationItemUnion `json:"data,required"` + // The ID of the first item in the list. + FirstID string `json:"first_id,required"` + // Whether there are more items available. + HasMore bool `json:"has_more,required"` + // The ID of the last item in the list. + LastID string `json:"last_id,required"` + // The type of object returned, must be `list`. + Object constant.List `json:"object,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + FirstID respjson.Field + HasMore respjson.Field + LastID respjson.Field + Object respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ConversationItemList) RawJSON() string { return r.JSON.raw } +func (r *ConversationItemList) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ItemNewParams struct { + // The items to add to the conversation. You may add up to 20 items at a time. + Items []responses.ResponseInputItemUnionParam `json:"items,omitzero,required"` + // Additional fields to include in the response. See the `include` parameter for + // [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) + // for more information. + Include []responses.ResponseIncludable `query:"include,omitzero" json:"-"` + paramObj +} + +func (r ItemNewParams) MarshalJSON() (data []byte, err error) { + type shadow ItemNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ItemNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// URLQuery serializes [ItemNewParams]'s query parameters as `url.Values`. +func (r ItemNewParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type ItemGetParams struct { + // Additional fields to include in the response. See the `include` parameter for + // [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) + // for more information. + Include []responses.ResponseIncludable `query:"include,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [ItemGetParams]'s query parameters as `url.Values`. +func (r ItemGetParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type ItemListParams struct { + // An item ID to list items after, used in pagination. + After param.Opt[string] `query:"after,omitzero" json:"-"` + // A limit on the number of objects to be returned. Limit can range between 1 and + // 100, and the default is 20. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Specify additional output data to include in the model response. Currently + // supported values are: + // + // - `code_interpreter_call.outputs`: Includes the outputs of python code execution + // in code interpreter tool call items. + // - `computer_call_output.output.image_url`: Include image urls from the computer + // call output. + // - `file_search_call.results`: Include the search results of the file search tool + // call. + // - `message.input_image.image_url`: Include image urls from the input message. + // - `message.output_text.logprobs`: Include logprobs with assistant messages. + // - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + // tokens in reasoning item outputs. This enables reasoning items to be used in + // multi-turn conversations when using the Responses API statelessly (like when + // the `store` parameter is set to `false`, or when an organization is enrolled + // in the zero data retention program). + Include []responses.ResponseIncludable `query:"include,omitzero" json:"-"` + // The order to return the input items in. Default is `desc`. + // + // - `asc`: Return the input items in ascending order. + // - `desc`: Return the input items in descending order. + // + // Any of "asc", "desc". + Order ItemListParamsOrder `query:"order,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [ItemListParams]'s query parameters as `url.Values`. +func (r ItemListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +// The order to return the input items in. Default is `desc`. +// +// - `asc`: Return the input items in ascending order. +// - `desc`: Return the input items in descending order. +type ItemListParamsOrder string + +const ( + ItemListParamsOrderAsc ItemListParamsOrder = "asc" + ItemListParamsOrderDesc ItemListParamsOrder = "desc" +) diff --git a/conversations/item_test.go b/conversations/item_test.go new file mode 100644 index 00000000..0ca54904 --- /dev/null +++ b/conversations/item_test.go @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package conversations_test + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/openai/openai-go/v2" + "github.com/openai/openai-go/v2/conversations" + "github.com/openai/openai-go/v2/internal/testutil" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/responses" +) + +func TestItemNewWithOptionalParams(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Items.New( + context.TODO(), + "conv_123", + conversations.ItemNewParams{ + Items: []responses.ResponseInputItemUnionParam{{ + OfMessage: &responses.EasyInputMessageParam{ + Content: responses.EasyInputMessageContentUnionParam{ + OfString: openai.String("string"), + }, + Role: responses.EasyInputMessageRoleUser, + Type: responses.EasyInputMessageTypeMessage, + }, + }}, + Include: []responses.ResponseIncludable{responses.ResponseIncludableCodeInterpreterCallOutputs}, + }, + ) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} + +func TestItemGetWithOptionalParams(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Items.Get( + context.TODO(), + "conv_123", + "msg_abc", + conversations.ItemGetParams{ + Include: []responses.ResponseIncludable{responses.ResponseIncludableCodeInterpreterCallOutputs}, + }, + ) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} + +func TestItemListWithOptionalParams(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Items.List( + context.TODO(), + "conv_123", + conversations.ItemListParams{ + After: openai.String("after"), + Include: []responses.ResponseIncludable{responses.ResponseIncludableCodeInterpreterCallOutputs}, + Limit: openai.Int(0), + Order: conversations.ItemListParamsOrderAsc, + }, + ) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} + +func TestItemDelete(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Conversations.Items.Delete( + context.TODO(), + "conv_123", + "msg_abc", + ) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} diff --git a/packages/pagination/pagination.go b/packages/pagination/pagination.go index c8914c0a..de9a330a 100644 --- a/packages/pagination/pagination.go +++ b/packages/pagination/pagination.go @@ -221,3 +221,109 @@ func (r *CursorPageAutoPager[T]) Err() error { func (r *CursorPageAutoPager[T]) Index() int { return r.run } + +type ConversationCursorPage[T any] struct { + Data []T `json:"data"` + HasMore bool `json:"has_more"` + LastID string `json:"last_id"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + HasMore respjson.Field + LastID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` + cfg *requestconfig.RequestConfig + res *http.Response +} + +// Returns the unmodified JSON received from the API +func (r ConversationCursorPage[T]) RawJSON() string { return r.JSON.raw } +func (r *ConversationCursorPage[T]) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// GetNextPage returns the next page as defined by this pagination style. When +// there is no next page, this function will return a 'nil' for the page value, but +// will not return an error +func (r *ConversationCursorPage[T]) GetNextPage() (res *ConversationCursorPage[T], err error) { + if len(r.Data) == 0 { + return nil, nil + } + + if r.JSON.HasMore.Valid() && r.HasMore == false { + return nil, nil + } + next := r.LastID + if len(next) == 0 { + return nil, nil + } + cfg := r.cfg.Clone(r.cfg.Context) + err = cfg.Apply(option.WithQuery("after", next)) + if err != nil { + return nil, err + } + var raw *http.Response + cfg.ResponseInto = &raw + cfg.ResponseBodyInto = &res + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +func (r *ConversationCursorPage[T]) SetPageConfig(cfg *requestconfig.RequestConfig, res *http.Response) { + if r == nil { + r = &ConversationCursorPage[T]{} + } + r.cfg = cfg + r.res = res +} + +type ConversationCursorPageAutoPager[T any] struct { + page *ConversationCursorPage[T] + cur T + idx int + run int + err error + paramObj +} + +func NewConversationCursorPageAutoPager[T any](page *ConversationCursorPage[T], err error) *ConversationCursorPageAutoPager[T] { + return &ConversationCursorPageAutoPager[T]{ + page: page, + err: err, + } +} + +func (r *ConversationCursorPageAutoPager[T]) Next() bool { + if r.page == nil || len(r.page.Data) == 0 { + return false + } + if r.idx >= len(r.page.Data) { + r.idx = 0 + r.page, r.err = r.page.GetNextPage() + if r.err != nil || r.page == nil || len(r.page.Data) == 0 { + return false + } + } + r.cur = r.page.Data[r.idx] + r.run += 1 + r.idx += 1 + return true +} + +func (r *ConversationCursorPageAutoPager[T]) Current() T { + return r.cur +} + +func (r *ConversationCursorPageAutoPager[T]) Err() error { + return r.err +} + +func (r *ConversationCursorPageAutoPager[T]) Index() int { + return r.run +} diff --git a/responses/inputitem.go b/responses/inputitem.go index 68f0fdc6..bb604769 100644 --- a/responses/inputitem.go +++ b/responses/inputitem.go @@ -98,8 +98,6 @@ func (r *ResponseItemList) UnmarshalJSON(data []byte) error { type InputItemListParams struct { // An item ID to list items after, used in pagination. After param.Opt[string] `query:"after,omitzero" json:"-"` - // An item ID to list items before, used in pagination. - Before param.Opt[string] `query:"before,omitzero" json:"-"` // A limit on the number of objects to be returned. Limit can range between 1 and // 100, and the default is 20. Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` diff --git a/responses/inputitem_test.go b/responses/inputitem_test.go index ed1f7bc8..3cae1a47 100644 --- a/responses/inputitem_test.go +++ b/responses/inputitem_test.go @@ -31,7 +31,6 @@ func TestInputItemListWithOptionalParams(t *testing.T) { "response_id", responses.InputItemListParams{ After: openai.String("after"), - Before: openai.String("before"), Include: []responses.ResponseIncludable{responses.ResponseIncludableCodeInterpreterCallOutputs}, Limit: openai.Int(0), Order: responses.InputItemListParamsOrderAsc, diff --git a/responses/response.go b/responses/response.go index 180aa95f..9ad3a8e0 100644 --- a/responses/response.go +++ b/responses/response.go @@ -805,6 +805,9 @@ type Response struct { // Whether to run the model response in the background. // [Learn more](https://platform.openai.com/docs/guides/background). Background bool `json:"background,nullable"` + // The conversation that this response belongs to. Input items and output items + // from this response are automatically added to this conversation. + Conversation ResponseConversation `json:"conversation,nullable"` // An upper bound for the number of tokens that can be generated for a response, // including visible output tokens and // [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). @@ -817,6 +820,7 @@ type Response struct { // The unique ID of the previous response to the model. Use this to create // multi-turn conversations. Learn more about // [conversation state](https://platform.openai.com/docs/guides/conversation-state). + // Cannot be used in conjunction with `conversation`. PreviousResponseID string `json:"previous_response_id,nullable"` // Reference to a prompt template and its variables. // [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). @@ -908,6 +912,7 @@ type Response struct { Tools respjson.Field TopP respjson.Field Background respjson.Field + Conversation respjson.Field MaxOutputTokens respjson.Field MaxToolCalls respjson.Field PreviousResponseID respjson.Field @@ -1070,6 +1075,25 @@ func (r *ResponseToolChoiceUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// The conversation that this response belongs to. Input items and output items +// from this response are automatically added to this conversation. +type ResponseConversation struct { + // The unique ID of the conversation. + ID string `json:"id,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ResponseConversation) RawJSON() string { return r.JSON.raw } +func (r *ResponseConversation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Specifies the processing type used for serving the request. // // - If set to 'auto', then the request will be processed with the service tier @@ -1382,6 +1406,8 @@ func (r *ResponseCodeInterpreterToolCall) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseCodeInterpreterToolCall) ImplConversationItemUnion() {} + // ToParam converts this ResponseCodeInterpreterToolCall to a // ResponseCodeInterpreterToolCallParam. // @@ -1713,6 +1739,8 @@ func (r *ResponseComputerToolCall) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseComputerToolCall) ImplConversationItemUnion() {} + // ToParam converts this ResponseComputerToolCall to a // ResponseComputerToolCallParam. // @@ -2683,6 +2711,8 @@ func (r *ResponseComputerToolCallOutputItem) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseComputerToolCallOutputItem) ImplConversationItemUnion() {} + // A pending safety check for the computer call. type ResponseComputerToolCallOutputItemAcknowledgedSafetyCheck struct { // The ID of the pending safety check. @@ -2991,6 +3021,23 @@ func (r *ResponseContentPartDoneEventPartUnion) UnmarshalJSON(data []byte) error return apijson.UnmarshalRoot(data, r) } +// The conversation that this response belongs to. +// +// The property ID is required. +type ResponseConversationParam struct { + // The unique ID of the conversation. + ID string `json:"id,required"` + paramObj +} + +func (r ResponseConversationParam) MarshalJSON() (data []byte, err error) { + type shadow ResponseConversationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ResponseConversationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // An event that is emitted when a response is created. type ResponseCreatedEvent struct { // The response that was created. @@ -3045,6 +3092,8 @@ func (r *ResponseCustomToolCall) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseCustomToolCall) ImplConversationItemUnion() {} + // ToParam converts this ResponseCustomToolCall to a ResponseCustomToolCallParam. // // Warning: the fields of the param type will not be present. ToParam should only @@ -3168,6 +3217,8 @@ func (r *ResponseCustomToolCallOutput) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseCustomToolCallOutput) ImplConversationItemUnion() {} + // ToParam converts this ResponseCustomToolCallOutput to a // ResponseCustomToolCallOutputParam. // @@ -3426,6 +3477,8 @@ func (r *ResponseFileSearchToolCall) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseFileSearchToolCall) ImplConversationItemUnion() {} + // ToParam converts this ResponseFileSearchToolCall to a // ResponseFileSearchToolCallParam. // @@ -4046,6 +4099,8 @@ func (r *ResponseFunctionToolCallItem) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseFunctionToolCallItem) ImplConversationItemUnion() {} + type ResponseFunctionToolCallOutputItem struct { // The unique ID of the function call tool output. ID string `json:"id,required"` @@ -4078,6 +4133,8 @@ func (r *ResponseFunctionToolCallOutputItem) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseFunctionToolCallOutputItem) ImplConversationItemUnion() {} + // The status of the item. One of `in_progress`, `completed`, or `incomplete`. // Populated when items are returned via API. type ResponseFunctionToolCallOutputItemStatus string @@ -4120,6 +4177,8 @@ func (r *ResponseFunctionWebSearch) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseFunctionWebSearch) ImplConversationItemUnion() {} + // ToParam converts this ResponseFunctionWebSearch to a // ResponseFunctionWebSearchParam. // @@ -9987,6 +10046,8 @@ func (r *ResponseReasoningItem) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func (ResponseReasoningItem) ImplConversationItemUnion() {} + // ToParam converts this ResponseReasoningItem to a ResponseReasoningItemParam. // // Warning: the fields of the param type will not be present. ToParam should only @@ -13397,6 +13458,7 @@ type ResponseNewParams struct { // The unique ID of the previous response to the model. Use this to create // multi-turn conversations. Learn more about // [conversation state](https://platform.openai.com/docs/guides/conversation-state). + // Cannot be used in conjunction with `conversation`. PreviousResponseID param.Opt[string] `json:"previous_response_id,omitzero"` // Whether to store the generated model response for later retrieval via API. Store param.Opt[bool] `json:"store,omitzero"` @@ -13430,6 +13492,11 @@ type ResponseNewParams struct { // similar requests and to help OpenAI detect and prevent abuse. // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). User param.Opt[string] `json:"user,omitzero"` + // The conversation that this response belongs to. Items from this conversation are + // prepended to `input_items` for this response request. Input items and output + // items from this response are automatically added to this conversation after this + // response completes. + Conversation ResponseNewParamsConversationUnion `json:"conversation,omitzero"` // Specify additional output data to include in the model response. Currently // supported values are: // @@ -13547,6 +13614,31 @@ func (r *ResponseNewParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ResponseNewParamsConversationUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfConversationObject *ResponseConversationParam `json:",omitzero,inline"` + paramUnion +} + +func (u ResponseNewParamsConversationUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfConversationObject) +} +func (u *ResponseNewParamsConversationUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *ResponseNewParamsConversationUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfConversationObject) { + return u.OfConversationObject + } + return nil +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. diff --git a/responses/response_test.go b/responses/response_test.go index 7b73951f..cf8dda0e 100644 --- a/responses/response_test.go +++ b/responses/response_test.go @@ -29,7 +29,10 @@ func TestResponseNewWithOptionalParams(t *testing.T) { ) _, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ Background: openai.Bool(true), - Include: []responses.ResponseIncludable{responses.ResponseIncludableCodeInterpreterCallOutputs}, + Conversation: responses.ResponseNewParamsConversationUnion{ + OfString: openai.String("string"), + }, + Include: []responses.ResponseIncludable{responses.ResponseIncludableCodeInterpreterCallOutputs}, Input: responses.ResponseNewParamsInputUnion{ OfString: openai.String("string"), }, diff --git a/scripts/detect-breaking-changes b/scripts/detect-breaking-changes index 231cde6d..591075c8 100755 --- a/scripts/detect-breaking-changes +++ b/scripts/detect-breaking-changes @@ -37,6 +37,8 @@ TEST_PATHS=( uploadpart_test.go responses/response_test.go responses/inputitem_test.go + conversations/conversation_test.go + conversations/item_test.go container_test.go containerfile_test.go containerfilecontent_test.go diff --git a/shared/constant/constants.go b/shared/constant/constants.go index fdc26c32..aa5e34d6 100644 --- a/shared/constant/constants.go +++ b/shared/constant/constants.go @@ -41,6 +41,8 @@ type ComputerUsePreview string // Always "computer_use_prev type ContainerFileCitation string // Always "container_file_citation" type ContainerFile string // Always "container.file" type Content string // Always "content" +type Conversation string // Always "conversation" +type ConversationDeleted string // Always "conversation.deleted" type CreatedAt string // Always "created_at" type Custom string // Always "custom" type CustomToolCall string // Always "custom_tool_call" @@ -251,6 +253,8 @@ func (c ComputerUsePreview) Default() ComputerUsePreview { return "compu func (c ContainerFileCitation) Default() ContainerFileCitation { return "container_file_citation" } func (c ContainerFile) Default() ContainerFile { return "container.file" } func (c Content) Default() Content { return "content" } +func (c Conversation) Default() Conversation { return "conversation" } +func (c ConversationDeleted) Default() ConversationDeleted { return "conversation.deleted" } func (c CreatedAt) Default() CreatedAt { return "created_at" } func (c Custom) Default() Custom { return "custom" } func (c CustomToolCall) Default() CustomToolCall { return "custom_tool_call" } @@ -557,6 +561,8 @@ func (c ComputerUsePreview) MarshalJSON() ([]byte, error) { r func (c ContainerFileCitation) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ContainerFile) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Content) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Conversation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c CreatedAt) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Custom) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c CustomToolCall) MarshalJSON() ([]byte, error) { return marshalString(c) } From 35888bcd26c7633e8ea68f9213cc3977b8ac49eb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 21 Aug 2025 20:30:09 +0000 Subject: [PATCH 05/10] feat(api): Add connectors support for MCP tool --- .stats.yml | 6 +- responses/response.go | 203 +++++++++++++++++++++++++++++++++--------- 2 files changed, 164 insertions(+), 45 deletions(-) diff --git a/.stats.yml b/.stats.yml index 640f2dee..88014691 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 105 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bcdfe525558e67a09b32dec7a573e87b94bab47db3951eb4a86a4dafb60296c.yml -openapi_spec_hash: 49e7e46bfe9f61b7b7a60e36840c0cd7 -config_hash: e4514526ae01126a61f9b6c14a351737 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-ddbdf9343316047e8a773c54fb24e4a8d225955e202a1888fde6f9c8898ebf98.yml +openapi_spec_hash: 9802f6dd381558466c897f6e387e06ca +config_hash: fe0ea26680ac2075a6cd66416aefe7db diff --git a/responses/response.go b/responses/response.go index 9ad3a8e0..8893502d 100644 --- a/responses/response.go +++ b/responses/response.go @@ -11644,15 +11644,19 @@ type ToolUnion struct { // This field is from variant [ToolMcp]. ServerLabel string `json:"server_label"` // This field is from variant [ToolMcp]. - ServerURL string `json:"server_url"` - // This field is from variant [ToolMcp]. AllowedTools ToolMcpAllowedToolsUnion `json:"allowed_tools"` // This field is from variant [ToolMcp]. + Authorization string `json:"authorization"` + // This field is from variant [ToolMcp]. + ConnectorID string `json:"connector_id"` + // This field is from variant [ToolMcp]. Headers map[string]string `json:"headers"` // This field is from variant [ToolMcp]. RequireApproval ToolMcpRequireApprovalUnion `json:"require_approval"` // This field is from variant [ToolMcp]. ServerDescription string `json:"server_description"` + // This field is from variant [ToolMcp]. + ServerURL string `json:"server_url"` // This field is from variant [ToolCodeInterpreter]. Container ToolCodeInterpreterContainerUnion `json:"container"` // This field is from variant [ToolImageGeneration]. @@ -11693,11 +11697,13 @@ type ToolUnion struct { DisplayWidth respjson.Field Environment respjson.Field ServerLabel respjson.Field - ServerURL respjson.Field AllowedTools respjson.Field + Authorization respjson.Field + ConnectorID respjson.Field Headers respjson.Field RequireApproval respjson.Field ServerDescription respjson.Field + ServerURL respjson.Field Container respjson.Field Background respjson.Field InputFidelity respjson.Field @@ -11781,12 +11787,34 @@ func (r ToolUnion) ToParam() ToolUnionParam { type ToolMcp struct { // A label for this MCP server, used to identify it in tool calls. ServerLabel string `json:"server_label,required"` - // The URL for the MCP server. - ServerURL string `json:"server_url,required"` // The type of the MCP tool. Always `mcp`. Type constant.Mcp `json:"type,required"` // List of allowed tool names or a filter object. AllowedTools ToolMcpAllowedToolsUnion `json:"allowed_tools,nullable"` + // An OAuth access token that can be used with a remote MCP server, either with a + // custom MCP server URL or a service connector. Your application must handle the + // OAuth authorization flow and provide the token here. + Authorization string `json:"authorization"` + // Identifier for service connectors, like those available in ChatGPT. One of + // `server_url` or `connector_id` must be provided. Learn more about service + // connectors + // [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors). + // + // Currently supported `connector_id` values are: + // + // - Dropbox: `connector_dropbox` + // - Gmail: `connector_gmail` + // - Google Calendar: `connector_googlecalendar` + // - Google Drive: `connector_googledrive` + // - Microsoft Teams: `connector_microsoftteams` + // - Outlook Calendar: `connector_outlookcalendar` + // - Outlook Email: `connector_outlookemail` + // - SharePoint: `connector_sharepoint` + // + // Any of "connector_dropbox", "connector_gmail", "connector_googlecalendar", + // "connector_googledrive", "connector_microsoftteams", + // "connector_outlookcalendar", "connector_outlookemail", "connector_sharepoint". + ConnectorID string `json:"connector_id"` // Optional HTTP headers to send to the MCP server. Use for authentication or other // purposes. Headers map[string]string `json:"headers,nullable"` @@ -11794,15 +11822,20 @@ type ToolMcp struct { RequireApproval ToolMcpRequireApprovalUnion `json:"require_approval,nullable"` // Optional description of the MCP server, used to provide more context. ServerDescription string `json:"server_description"` + // The URL for the MCP server. One of `server_url` or `connector_id` must be + // provided. + ServerURL string `json:"server_url"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ServerLabel respjson.Field - ServerURL respjson.Field Type respjson.Field AllowedTools respjson.Field + Authorization respjson.Field + ConnectorID respjson.Field Headers respjson.Field RequireApproval respjson.Field ServerDescription respjson.Field + ServerURL respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -11815,7 +11848,7 @@ func (r *ToolMcp) UnmarshalJSON(data []byte) error { } // ToolMcpAllowedToolsUnion contains all possible properties and values from -// [[]string], [ToolMcpAllowedToolsMcpAllowedToolsFilter]. +// [[]string], [ToolMcpAllowedToolsMcpToolFilter]. // // Use the methods beginning with 'As' to cast the union to one of its variants. // @@ -11824,10 +11857,13 @@ func (r *ToolMcp) UnmarshalJSON(data []byte) error { type ToolMcpAllowedToolsUnion struct { // This field will be present if the value is a [[]string] instead of an object. OfMcpAllowedTools []string `json:",inline"` - // This field is from variant [ToolMcpAllowedToolsMcpAllowedToolsFilter]. + // This field is from variant [ToolMcpAllowedToolsMcpToolFilter]. + ReadOnly bool `json:"read_only"` + // This field is from variant [ToolMcpAllowedToolsMcpToolFilter]. ToolNames []string `json:"tool_names"` JSON struct { OfMcpAllowedTools respjson.Field + ReadOnly respjson.Field ToolNames respjson.Field raw string } `json:"-"` @@ -11838,7 +11874,7 @@ func (u ToolMcpAllowedToolsUnion) AsMcpAllowedTools() (v []string) { return } -func (u ToolMcpAllowedToolsUnion) AsMcpAllowedToolsFilter() (v ToolMcpAllowedToolsMcpAllowedToolsFilter) { +func (u ToolMcpAllowedToolsUnion) AsMcpToolFilter() (v ToolMcpAllowedToolsMcpToolFilter) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } @@ -11851,11 +11887,17 @@ func (r *ToolMcpAllowedToolsUnion) UnmarshalJSON(data []byte) error { } // A filter object to specify which tools are allowed. -type ToolMcpAllowedToolsMcpAllowedToolsFilter struct { +type ToolMcpAllowedToolsMcpToolFilter struct { + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly bool `json:"read_only"` // List of allowed tool names. ToolNames []string `json:"tool_names"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + ReadOnly respjson.Field ToolNames respjson.Field ExtraFields map[string]respjson.Field raw string @@ -11863,8 +11905,8 @@ type ToolMcpAllowedToolsMcpAllowedToolsFilter struct { } // Returns the unmodified JSON received from the API -func (r ToolMcpAllowedToolsMcpAllowedToolsFilter) RawJSON() string { return r.JSON.raw } -func (r *ToolMcpAllowedToolsMcpAllowedToolsFilter) UnmarshalJSON(data []byte) error { +func (r ToolMcpAllowedToolsMcpToolFilter) RawJSON() string { return r.JSON.raw } +func (r *ToolMcpAllowedToolsMcpToolFilter) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } @@ -11907,10 +11949,12 @@ func (r *ToolMcpRequireApprovalUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Specify which of the MCP server's tools require approval. Can be `always`, +// `never`, or a filter object associated with tools that require approval. type ToolMcpRequireApprovalMcpToolApprovalFilter struct { - // A list of tools that always require approval. + // A filter object to specify which tools are allowed. Always ToolMcpRequireApprovalMcpToolApprovalFilterAlways `json:"always"` - // A list of tools that never require approval. + // A filter object to specify which tools are allowed. Never ToolMcpRequireApprovalMcpToolApprovalFilterNever `json:"never"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { @@ -11927,12 +11971,18 @@ func (r *ToolMcpRequireApprovalMcpToolApprovalFilter) UnmarshalJSON(data []byte) return apijson.UnmarshalRoot(data, r) } -// A list of tools that always require approval. +// A filter object to specify which tools are allowed. type ToolMcpRequireApprovalMcpToolApprovalFilterAlways struct { - // List of tools that require approval. + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly bool `json:"read_only"` + // List of allowed tool names. ToolNames []string `json:"tool_names"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + ReadOnly respjson.Field ToolNames respjson.Field ExtraFields map[string]respjson.Field raw string @@ -11945,12 +11995,18 @@ func (r *ToolMcpRequireApprovalMcpToolApprovalFilterAlways) UnmarshalJSON(data [ return apijson.UnmarshalRoot(data, r) } -// A list of tools that never require approval. +// A filter object to specify which tools are allowed. type ToolMcpRequireApprovalMcpToolApprovalFilterNever struct { - // List of tools that do not require approval. + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly bool `json:"read_only"` + // List of allowed tool names. ToolNames []string `json:"tool_names"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + ReadOnly respjson.Field ToolNames respjson.Field ExtraFields map[string]respjson.Field raw string @@ -12196,10 +12252,9 @@ func ToolParamOfComputerUsePreview(displayHeight int64, displayWidth int64, envi return ToolUnionParam{OfComputerUsePreview: &computerUsePreview} } -func ToolParamOfMcp(serverLabel string, serverURL string) ToolUnionParam { +func ToolParamOfMcp(serverLabel string) ToolUnionParam { var mcp ToolMcpParam mcp.ServerLabel = serverLabel - mcp.ServerURL = serverURL return ToolUnionParam{OfMcp: &mcp} } @@ -12373,17 +12428,25 @@ func (u ToolUnionParam) GetServerLabel() *string { } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetServerURL() *string { +func (u ToolUnionParam) GetAllowedTools() *ToolMcpAllowedToolsUnionParam { if vt := u.OfMcp; vt != nil { - return &vt.ServerURL + return &vt.AllowedTools } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetAllowedTools() *ToolMcpAllowedToolsUnionParam { +func (u ToolUnionParam) GetAuthorization() *string { + if vt := u.OfMcp; vt != nil && vt.Authorization.Valid() { + return &vt.Authorization.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetConnectorID() *string { if vt := u.OfMcp; vt != nil { - return &vt.AllowedTools + return &vt.ConnectorID } return nil } @@ -12412,6 +12475,14 @@ func (u ToolUnionParam) GetServerDescription() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetServerURL() *string { + if vt := u.OfMcp; vt != nil && vt.ServerURL.Valid() { + return &vt.ServerURL.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u ToolUnionParam) GetContainer() *ToolCodeInterpreterContainerUnionParam { if vt := u.OfCodeInterpreter; vt != nil { @@ -12572,14 +12643,19 @@ func init() { // (MCP) servers. // [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). // -// The properties ServerLabel, ServerURL, Type are required. +// The properties ServerLabel, Type are required. type ToolMcpParam struct { // A label for this MCP server, used to identify it in tool calls. ServerLabel string `json:"server_label,required"` - // The URL for the MCP server. - ServerURL string `json:"server_url,required"` + // An OAuth access token that can be used with a remote MCP server, either with a + // custom MCP server URL or a service connector. Your application must handle the + // OAuth authorization flow and provide the token here. + Authorization param.Opt[string] `json:"authorization,omitzero"` // Optional description of the MCP server, used to provide more context. ServerDescription param.Opt[string] `json:"server_description,omitzero"` + // The URL for the MCP server. One of `server_url` or `connector_id` must be + // provided. + ServerURL param.Opt[string] `json:"server_url,omitzero"` // List of allowed tool names or a filter object. AllowedTools ToolMcpAllowedToolsUnionParam `json:"allowed_tools,omitzero"` // Optional HTTP headers to send to the MCP server. Use for authentication or other @@ -12587,6 +12663,26 @@ type ToolMcpParam struct { Headers map[string]string `json:"headers,omitzero"` // Specify which of the MCP server's tools require approval. RequireApproval ToolMcpRequireApprovalUnionParam `json:"require_approval,omitzero"` + // Identifier for service connectors, like those available in ChatGPT. One of + // `server_url` or `connector_id` must be provided. Learn more about service + // connectors + // [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors). + // + // Currently supported `connector_id` values are: + // + // - Dropbox: `connector_dropbox` + // - Gmail: `connector_gmail` + // - Google Calendar: `connector_googlecalendar` + // - Google Drive: `connector_googledrive` + // - Microsoft Teams: `connector_microsoftteams` + // - Outlook Calendar: `connector_outlookcalendar` + // - Outlook Email: `connector_outlookemail` + // - SharePoint: `connector_sharepoint` + // + // Any of "connector_dropbox", "connector_gmail", "connector_googlecalendar", + // "connector_googledrive", "connector_microsoftteams", + // "connector_outlookcalendar", "connector_outlookemail", "connector_sharepoint". + ConnectorID string `json:"connector_id,omitzero"` // The type of the MCP tool. Always `mcp`. // // This field can be elided, and will marshal its zero value as "mcp". @@ -12602,17 +12698,23 @@ func (r *ToolMcpParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func init() { + apijson.RegisterFieldValidator[ToolMcpParam]( + "connector_id", "connector_dropbox", "connector_gmail", "connector_googlecalendar", "connector_googledrive", "connector_microsoftteams", "connector_outlookcalendar", "connector_outlookemail", "connector_sharepoint", + ) +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. type ToolMcpAllowedToolsUnionParam struct { - OfMcpAllowedTools []string `json:",omitzero,inline"` - OfMcpAllowedToolsFilter *ToolMcpAllowedToolsMcpAllowedToolsFilterParam `json:",omitzero,inline"` + OfMcpAllowedTools []string `json:",omitzero,inline"` + OfMcpToolFilter *ToolMcpAllowedToolsMcpToolFilterParam `json:",omitzero,inline"` paramUnion } func (u ToolMcpAllowedToolsUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfMcpAllowedTools, u.OfMcpAllowedToolsFilter) + return param.MarshalUnion(u, u.OfMcpAllowedTools, u.OfMcpToolFilter) } func (u *ToolMcpAllowedToolsUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -12621,24 +12723,29 @@ func (u *ToolMcpAllowedToolsUnionParam) UnmarshalJSON(data []byte) error { func (u *ToolMcpAllowedToolsUnionParam) asAny() any { if !param.IsOmitted(u.OfMcpAllowedTools) { return &u.OfMcpAllowedTools - } else if !param.IsOmitted(u.OfMcpAllowedToolsFilter) { - return u.OfMcpAllowedToolsFilter + } else if !param.IsOmitted(u.OfMcpToolFilter) { + return u.OfMcpToolFilter } return nil } // A filter object to specify which tools are allowed. -type ToolMcpAllowedToolsMcpAllowedToolsFilterParam struct { +type ToolMcpAllowedToolsMcpToolFilterParam struct { + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly param.Opt[bool] `json:"read_only,omitzero"` // List of allowed tool names. ToolNames []string `json:"tool_names,omitzero"` paramObj } -func (r ToolMcpAllowedToolsMcpAllowedToolsFilterParam) MarshalJSON() (data []byte, err error) { - type shadow ToolMcpAllowedToolsMcpAllowedToolsFilterParam +func (r ToolMcpAllowedToolsMcpToolFilterParam) MarshalJSON() (data []byte, err error) { + type shadow ToolMcpAllowedToolsMcpToolFilterParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ToolMcpAllowedToolsMcpAllowedToolsFilterParam) UnmarshalJSON(data []byte) error { +func (r *ToolMcpAllowedToolsMcpToolFilterParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } @@ -12669,10 +12776,12 @@ func (u *ToolMcpRequireApprovalUnionParam) asAny() any { return nil } +// Specify which of the MCP server's tools require approval. Can be `always`, +// `never`, or a filter object associated with tools that require approval. type ToolMcpRequireApprovalMcpToolApprovalFilterParam struct { - // A list of tools that always require approval. + // A filter object to specify which tools are allowed. Always ToolMcpRequireApprovalMcpToolApprovalFilterAlwaysParam `json:"always,omitzero"` - // A list of tools that never require approval. + // A filter object to specify which tools are allowed. Never ToolMcpRequireApprovalMcpToolApprovalFilterNeverParam `json:"never,omitzero"` paramObj } @@ -12685,9 +12794,14 @@ func (r *ToolMcpRequireApprovalMcpToolApprovalFilterParam) UnmarshalJSON(data [] return apijson.UnmarshalRoot(data, r) } -// A list of tools that always require approval. +// A filter object to specify which tools are allowed. type ToolMcpRequireApprovalMcpToolApprovalFilterAlwaysParam struct { - // List of tools that require approval. + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly param.Opt[bool] `json:"read_only,omitzero"` + // List of allowed tool names. ToolNames []string `json:"tool_names,omitzero"` paramObj } @@ -12700,9 +12814,14 @@ func (r *ToolMcpRequireApprovalMcpToolApprovalFilterAlwaysParam) UnmarshalJSON(d return apijson.UnmarshalRoot(data, r) } -// A list of tools that never require approval. +// A filter object to specify which tools are allowed. type ToolMcpRequireApprovalMcpToolApprovalFilterNeverParam struct { - // List of tools that do not require approval. + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly param.Opt[bool] `json:"read_only,omitzero"` + // List of allowed tool names. ToolNames []string `json:"tool_names,omitzero"` paramObj } From 6f2c71d4e28971fc73e7e291d40f3b875d9cc42a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 26 Aug 2025 20:42:30 +0000 Subject: [PATCH 06/10] feat(api): add web search filters --- .stats.yml | 4 +- conversations/conversation.go | 2 +- conversations/item.go | 7 +- responses/response.go | 585 ++++++++++++++++++++++++++++++---- shared/constant/constants.go | 3 + 5 files changed, 539 insertions(+), 62 deletions(-) diff --git a/.stats.yml b/.stats.yml index 88014691..0c18b873 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 105 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-ddbdf9343316047e8a773c54fb24e4a8d225955e202a1888fde6f9c8898ebf98.yml -openapi_spec_hash: 9802f6dd381558466c897f6e387e06ca +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-8517ffa1004e31ca2523d617629e64be6fe4f13403ddfd9db5b3be002656cbde.yml +openapi_spec_hash: b64dd8c8b23082a7aa2a3e5c5fffd8bd config_hash: fe0ea26680ac2075a6cd66416aefe7db diff --git a/conversations/conversation.go b/conversations/conversation.go index b9e9d31c..b4b54701 100644 --- a/conversations/conversation.go +++ b/conversations/conversation.go @@ -40,7 +40,7 @@ func NewConversationService(opts ...option.RequestOption) (r ConversationService return } -// Create a conversation with the given ID. +// Create a conversation. func (r *ConversationService) New(ctx context.Context, body ConversationNewParams, opts ...option.RequestOption) (res *Conversation, err error) { opts = append(r.Options[:], opts...) path := "conversations" diff --git a/conversations/item.go b/conversations/item.go index 450f5d4b..d7c5d933 100644 --- a/conversations/item.go +++ b/conversations/item.go @@ -462,7 +462,9 @@ type ConversationItemUnionAction struct { // This field is from variant [responses.ResponseFunctionWebSearchActionUnion]. Query string `json:"query"` Type string `json:"type"` - URL string `json:"url"` + // This field is from variant [responses.ResponseFunctionWebSearchActionUnion]. + Sources []responses.ResponseFunctionWebSearchActionSearchSource `json:"sources"` + URL string `json:"url"` // This field is from variant [responses.ResponseFunctionWebSearchActionUnion]. Pattern string `json:"pattern"` // This field is from variant [responses.ResponseComputerToolCallActionUnion]. @@ -492,6 +494,7 @@ type ConversationItemUnionAction struct { JSON struct { Query respjson.Field Type respjson.Field + Sources respjson.Field URL respjson.Field Pattern respjson.Field Button respjson.Field @@ -872,6 +875,8 @@ type ItemListParams struct { // Specify additional output data to include in the model response. Currently // supported values are: // + // - `web_search_call.action.sources`: Include the sources of the web search tool + // call. // - `code_interpreter_call.outputs`: Includes the outputs of python code execution // in code interpreter tool call items. // - `computer_call_output.output.image_url`: Include image urls from the computer diff --git a/responses/response.go b/responses/response.go index 8893502d..e97edb38 100644 --- a/responses/response.go +++ b/responses/response.go @@ -4203,12 +4203,15 @@ type ResponseFunctionWebSearchActionUnion struct { Query string `json:"query"` // Any of "search", "open_page", "find". Type string `json:"type"` - URL string `json:"url"` + // This field is from variant [ResponseFunctionWebSearchActionSearch]. + Sources []ResponseFunctionWebSearchActionSearchSource `json:"sources"` + URL string `json:"url"` // This field is from variant [ResponseFunctionWebSearchActionFind]. Pattern string `json:"pattern"` JSON struct { Query respjson.Field Type respjson.Field + Sources respjson.Field URL respjson.Field Pattern respjson.Field raw string @@ -4275,10 +4278,13 @@ type ResponseFunctionWebSearchActionSearch struct { Query string `json:"query,required"` // The action type. Type constant.Search `json:"type,required"` + // The sources used in the search. + Sources []ResponseFunctionWebSearchActionSearchSource `json:"sources"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Query respjson.Field Type respjson.Field + Sources respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -4290,6 +4296,27 @@ func (r *ResponseFunctionWebSearchActionSearch) UnmarshalJSON(data []byte) error return apijson.UnmarshalRoot(data, r) } +// A source used in the search. +type ResponseFunctionWebSearchActionSearchSource struct { + // The type of source. Always `url`. + Type constant.URL `json:"type,required"` + // The URL of the source. + URL string `json:"url,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ResponseFunctionWebSearchActionSearchSource) RawJSON() string { return r.JSON.raw } +func (r *ResponseFunctionWebSearchActionSearchSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Action type "open_page" - Opens a specific URL from search results. type ResponseFunctionWebSearchActionOpenPage struct { // The action type. @@ -4411,6 +4438,14 @@ func (u ResponseFunctionWebSearchActionUnionParam) GetQuery() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u ResponseFunctionWebSearchActionUnionParam) GetSources() []ResponseFunctionWebSearchActionSearchSourceParam { + if vt := u.OfSearch; vt != nil { + return vt.Sources + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u ResponseFunctionWebSearchActionUnionParam) GetPattern() *string { if vt := u.OfFind; vt != nil { @@ -4456,6 +4491,8 @@ func init() { type ResponseFunctionWebSearchActionSearchParam struct { // The search query. Query string `json:"query,required"` + // The sources used in the search. + Sources []ResponseFunctionWebSearchActionSearchSourceParam `json:"sources,omitzero"` // The action type. // // This field can be elided, and will marshal its zero value as "search". @@ -4471,6 +4508,27 @@ func (r *ResponseFunctionWebSearchActionSearchParam) UnmarshalJSON(data []byte) return apijson.UnmarshalRoot(data, r) } +// A source used in the search. +// +// The properties Type, URL are required. +type ResponseFunctionWebSearchActionSearchSourceParam struct { + // The URL of the source. + URL string `json:"url,required"` + // The type of source. Always `url`. + // + // This field can be elided, and will marshal its zero value as "url". + Type constant.URL `json:"type,required"` + paramObj +} + +func (r ResponseFunctionWebSearchActionSearchSourceParam) MarshalJSON() (data []byte, err error) { + type shadow ResponseFunctionWebSearchActionSearchSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ResponseFunctionWebSearchActionSearchSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Action type "open_page" - Opens a specific URL from search results. // // The properties Type, URL are required. @@ -4659,6 +4717,8 @@ func (r *ResponseInProgressEvent) UnmarshalJSON(data []byte) error { // Specify additional output data to include in the model response. Currently // supported values are: // +// - `web_search_call.action.sources`: Include the sources of the web search tool +// call. // - `code_interpreter_call.outputs`: Includes the outputs of python code execution // in code interpreter tool call items. // - `computer_call_output.output.image_url`: Include image urls from the computer @@ -5447,7 +5507,9 @@ type ResponseInputItemUnionAction struct { Text string `json:"text"` // This field is from variant [ResponseFunctionWebSearchActionUnion]. Query string `json:"query"` - URL string `json:"url"` + // This field is from variant [ResponseFunctionWebSearchActionUnion]. + Sources []ResponseFunctionWebSearchActionSearchSource `json:"sources"` + URL string `json:"url"` // This field is from variant [ResponseFunctionWebSearchActionUnion]. Pattern string `json:"pattern"` // This field is from variant [ResponseInputItemLocalShellCallAction]. @@ -5471,6 +5533,7 @@ type ResponseInputItemUnionAction struct { ScrollY respjson.Field Text respjson.Field Query respjson.Field + Sources respjson.Field URL respjson.Field Pattern respjson.Field Command respjson.Field @@ -6663,6 +6726,15 @@ func (u responseInputItemUnionParamAction) GetQuery() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u responseInputItemUnionParamAction) GetSources() []ResponseFunctionWebSearchActionSearchSourceParam { + switch vt := u.any.(type) { + case *ResponseFunctionWebSearchActionUnionParam: + return vt.GetSources() + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u responseInputItemUnionParamAction) GetPattern() *string { switch vt := u.any.(type) { @@ -7683,7 +7755,9 @@ type ResponseItemUnionAction struct { Text string `json:"text"` // This field is from variant [ResponseFunctionWebSearchActionUnion]. Query string `json:"query"` - URL string `json:"url"` + // This field is from variant [ResponseFunctionWebSearchActionUnion]. + Sources []ResponseFunctionWebSearchActionSearchSource `json:"sources"` + URL string `json:"url"` // This field is from variant [ResponseFunctionWebSearchActionUnion]. Pattern string `json:"pattern"` // This field is from variant [ResponseItemLocalShellCallAction]. @@ -7707,6 +7781,7 @@ type ResponseItemUnionAction struct { ScrollY respjson.Field Text respjson.Field Query respjson.Field + Sources respjson.Field URL respjson.Field Pattern respjson.Field Command respjson.Field @@ -8521,7 +8596,9 @@ type ResponseOutputItemUnionAction struct { // This field is from variant [ResponseFunctionWebSearchActionUnion]. Query string `json:"query"` Type string `json:"type"` - URL string `json:"url"` + // This field is from variant [ResponseFunctionWebSearchActionUnion]. + Sources []ResponseFunctionWebSearchActionSearchSource `json:"sources"` + URL string `json:"url"` // This field is from variant [ResponseFunctionWebSearchActionUnion]. Pattern string `json:"pattern"` // This field is from variant [ResponseComputerToolCallActionUnion]. @@ -8551,6 +8628,7 @@ type ResponseOutputItemUnionAction struct { JSON struct { Query respjson.Field Type respjson.Field + Sources respjson.Field URL respjson.Field Pattern respjson.Field Button respjson.Field @@ -11607,8 +11685,9 @@ func (r *ResponseWebSearchCallSearchingEvent) UnmarshalJSON(data []byte) error { } // ToolUnion contains all possible properties and values from [FunctionTool], -// [FileSearchTool], [WebSearchTool], [ComputerTool], [ToolMcp], -// [ToolCodeInterpreter], [ToolImageGeneration], [ToolLocalShell], [CustomTool]. +// [FileSearchTool], [ComputerTool], [ToolWebSearch], [ToolMcp], +// [ToolCodeInterpreter], [ToolImageGeneration], [ToolLocalShell], [CustomTool], +// [WebSearchTool]. // // Use the [ToolUnion.AsAny] method to switch on the variant. // @@ -11619,28 +11698,28 @@ type ToolUnion struct { Parameters map[string]any `json:"parameters"` // This field is from variant [FunctionTool]. Strict bool `json:"strict"` - // Any of "function", "file_search", nil, "computer_use_preview", "mcp", - // "code_interpreter", "image_generation", "local_shell", "custom". + // Any of "function", "file_search", "computer_use_preview", nil, "mcp", + // "code_interpreter", "image_generation", "local_shell", "custom", nil. Type string `json:"type"` Description string `json:"description"` // This field is from variant [FileSearchTool]. VectorStoreIDs []string `json:"vector_store_ids"` - // This field is from variant [FileSearchTool]. - Filters FileSearchToolFiltersUnion `json:"filters"` + // This field is a union of [FileSearchToolFiltersUnion], [ToolWebSearchFilters] + Filters ToolUnionFilters `json:"filters"` // This field is from variant [FileSearchTool]. MaxNumResults int64 `json:"max_num_results"` // This field is from variant [FileSearchTool]. RankingOptions FileSearchToolRankingOptions `json:"ranking_options"` - // This field is from variant [WebSearchTool]. - SearchContextSize WebSearchToolSearchContextSize `json:"search_context_size"` - // This field is from variant [WebSearchTool]. - UserLocation WebSearchToolUserLocation `json:"user_location"` // This field is from variant [ComputerTool]. DisplayHeight int64 `json:"display_height"` // This field is from variant [ComputerTool]. DisplayWidth int64 `json:"display_width"` // This field is from variant [ComputerTool]. - Environment ComputerToolEnvironment `json:"environment"` + Environment ComputerToolEnvironment `json:"environment"` + SearchContextSize string `json:"search_context_size"` + // This field is a union of [ToolWebSearchUserLocation], + // [WebSearchToolUserLocation] + UserLocation ToolUnionUserLocation `json:"user_location"` // This field is from variant [ToolMcp]. ServerLabel string `json:"server_label"` // This field is from variant [ToolMcp]. @@ -11691,11 +11770,11 @@ type ToolUnion struct { Filters respjson.Field MaxNumResults respjson.Field RankingOptions respjson.Field - SearchContextSize respjson.Field - UserLocation respjson.Field DisplayHeight respjson.Field DisplayWidth respjson.Field Environment respjson.Field + SearchContextSize respjson.Field + UserLocation respjson.Field ServerLabel respjson.Field AllowedTools respjson.Field Authorization respjson.Field @@ -11730,12 +11809,12 @@ func (u ToolUnion) AsFileSearch() (v FileSearchTool) { return } -func (u ToolUnion) AsWebSearchPreview() (v WebSearchTool) { +func (u ToolUnion) AsComputerUsePreview() (v ComputerTool) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u ToolUnion) AsComputerUsePreview() (v ComputerTool) { +func (u ToolUnion) AsWebSearch() (v ToolWebSearch) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } @@ -11765,6 +11844,11 @@ func (u ToolUnion) AsCustom() (v CustomTool) { return } +func (u ToolUnion) AsWebSearchPreview() (v WebSearchTool) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u ToolUnion) RawJSON() string { return u.JSON.raw } @@ -11772,6 +11856,59 @@ func (r *ToolUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// ToolUnionFilters is an implicit subunion of [ToolUnion]. ToolUnionFilters +// provides convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the [ToolUnion]. +type ToolUnionFilters struct { + // This field is from variant [FileSearchToolFiltersUnion]. + Key string `json:"key"` + Type string `json:"type"` + // This field is from variant [FileSearchToolFiltersUnion]. + Value shared.ComparisonFilterValueUnion `json:"value"` + // This field is from variant [FileSearchToolFiltersUnion]. + Filters []shared.ComparisonFilter `json:"filters"` + // This field is from variant [ToolWebSearchFilters]. + AllowedDomains []string `json:"allowed_domains"` + JSON struct { + Key respjson.Field + Type respjson.Field + Value respjson.Field + Filters respjson.Field + AllowedDomains respjson.Field + raw string + } `json:"-"` +} + +func (r *ToolUnionFilters) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToolUnionUserLocation is an implicit subunion of [ToolUnion]. +// ToolUnionUserLocation provides convenient access to the sub-properties of the +// union. +// +// For type safety it is recommended to directly use a variant of the [ToolUnion]. +type ToolUnionUserLocation struct { + City string `json:"city"` + Country string `json:"country"` + Region string `json:"region"` + Timezone string `json:"timezone"` + Type string `json:"type"` + JSON struct { + City respjson.Field + Country respjson.Field + Region respjson.Field + Timezone respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +func (r *ToolUnionUserLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // ToParam converts this ToolUnion to a ToolUnionParam. // // Warning: the fields of the param type will not be present. ToParam should only @@ -11781,6 +11918,94 @@ func (r ToolUnion) ToParam() ToolUnionParam { return param.Override[ToolUnionParam](json.RawMessage(r.RawJSON())) } +// Search the Internet for sources related to the prompt. Learn more about the +// [web search tool](https://platform.openai.com/docs/guides/tools-web-search). +type ToolWebSearch struct { + // The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + // + // Any of "web_search", "web_search_2025_08_26". + Type string `json:"type,required"` + // Filters for the search. + Filters ToolWebSearchFilters `json:"filters,nullable"` + // High level guidance for the amount of context window space to use for the + // search. One of `low`, `medium`, or `high`. `medium` is the default. + // + // Any of "low", "medium", "high". + SearchContextSize string `json:"search_context_size"` + // The approximate location of the user. + UserLocation ToolWebSearchUserLocation `json:"user_location,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + Filters respjson.Field + SearchContextSize respjson.Field + UserLocation respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ToolWebSearch) RawJSON() string { return r.JSON.raw } +func (r *ToolWebSearch) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Filters for the search. +type ToolWebSearchFilters struct { + // Allowed domains for the search. If not provided, all domains are allowed. + // Subdomains of the provided domains are allowed as well. + // + // Example: `["pubmed.ncbi.nlm.nih.gov"]` + AllowedDomains []string `json:"allowed_domains,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + AllowedDomains respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ToolWebSearchFilters) RawJSON() string { return r.JSON.raw } +func (r *ToolWebSearchFilters) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The approximate location of the user. +type ToolWebSearchUserLocation struct { + // Free text input for the city of the user, e.g. `San Francisco`. + City string `json:"city,nullable"` + // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + // the user, e.g. `US`. + Country string `json:"country,nullable"` + // Free text input for the region of the user, e.g. `California`. + Region string `json:"region,nullable"` + // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + // user, e.g. `America/Los_Angeles`. + Timezone string `json:"timezone,nullable"` + // The type of location approximation. Always `approximate`. + // + // Any of "approximate". + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + City respjson.Field + Country respjson.Field + Region respjson.Field + Timezone respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ToolWebSearchUserLocation) RawJSON() string { return r.JSON.raw } +func (r *ToolWebSearchUserLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Give the model access to additional tools via remote Model Context Protocol // (MCP) servers. // [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). @@ -12238,12 +12463,6 @@ func ToolParamOfFileSearch(vectorStoreIDs []string) ToolUnionParam { return ToolUnionParam{OfFileSearch: &fileSearch} } -func ToolParamOfWebSearchPreview(type_ WebSearchToolType) ToolUnionParam { - var variant WebSearchToolParam - variant.Type = type_ - return ToolUnionParam{OfWebSearchPreview: &variant} -} - func ToolParamOfComputerUsePreview(displayHeight int64, displayWidth int64, environment ComputerToolEnvironment) ToolUnionParam { var computerUsePreview ComputerToolParam computerUsePreview.DisplayHeight = displayHeight @@ -12252,6 +12471,12 @@ func ToolParamOfComputerUsePreview(displayHeight int64, displayWidth int64, envi return ToolUnionParam{OfComputerUsePreview: &computerUsePreview} } +func ToolParamOfWebSearch(type_ string) ToolUnionParam { + var variant ToolWebSearchParam + variant.Type = type_ + return ToolUnionParam{OfWebSearch: &variant} +} + func ToolParamOfMcp(serverLabel string) ToolUnionParam { var mcp ToolMcpParam mcp.ServerLabel = serverLabel @@ -12277,32 +12502,40 @@ func ToolParamOfCustom(name string) ToolUnionParam { return ToolUnionParam{OfCustom: &custom} } +func ToolParamOfWebSearchPreview(type_ WebSearchToolType) ToolUnionParam { + var variant WebSearchToolParam + variant.Type = type_ + return ToolUnionParam{OfWebSearchPreview: &variant} +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. type ToolUnionParam struct { OfFunction *FunctionToolParam `json:",omitzero,inline"` OfFileSearch *FileSearchToolParam `json:",omitzero,inline"` - OfWebSearchPreview *WebSearchToolParam `json:",omitzero,inline"` OfComputerUsePreview *ComputerToolParam `json:",omitzero,inline"` + OfWebSearch *ToolWebSearchParam `json:",omitzero,inline"` OfMcp *ToolMcpParam `json:",omitzero,inline"` OfCodeInterpreter *ToolCodeInterpreterParam `json:",omitzero,inline"` OfImageGeneration *ToolImageGenerationParam `json:",omitzero,inline"` OfLocalShell *ToolLocalShellParam `json:",omitzero,inline"` OfCustom *CustomToolParam `json:",omitzero,inline"` + OfWebSearchPreview *WebSearchToolParam `json:",omitzero,inline"` paramUnion } func (u ToolUnionParam) MarshalJSON() ([]byte, error) { return param.MarshalUnion(u, u.OfFunction, u.OfFileSearch, - u.OfWebSearchPreview, u.OfComputerUsePreview, + u.OfWebSearch, u.OfMcp, u.OfCodeInterpreter, u.OfImageGeneration, u.OfLocalShell, - u.OfCustom) + u.OfCustom, + u.OfWebSearchPreview) } func (u *ToolUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -12313,10 +12546,10 @@ func (u *ToolUnionParam) asAny() any { return u.OfFunction } else if !param.IsOmitted(u.OfFileSearch) { return u.OfFileSearch - } else if !param.IsOmitted(u.OfWebSearchPreview) { - return u.OfWebSearchPreview } else if !param.IsOmitted(u.OfComputerUsePreview) { return u.OfComputerUsePreview + } else if !param.IsOmitted(u.OfWebSearch) { + return u.OfWebSearch } else if !param.IsOmitted(u.OfMcp) { return u.OfMcp } else if !param.IsOmitted(u.OfCodeInterpreter) { @@ -12327,6 +12560,8 @@ func (u *ToolUnionParam) asAny() any { return u.OfLocalShell } else if !param.IsOmitted(u.OfCustom) { return u.OfCustom + } else if !param.IsOmitted(u.OfWebSearchPreview) { + return u.OfWebSearchPreview } return nil } @@ -12355,14 +12590,6 @@ func (u ToolUnionParam) GetVectorStoreIDs() []string { return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetFilters() *FileSearchToolFiltersUnionParam { - if vt := u.OfFileSearch; vt != nil { - return &vt.Filters - } - return nil -} - // Returns a pointer to the underlying variant's property, if present. func (u ToolUnionParam) GetMaxNumResults() *int64 { if vt := u.OfFileSearch; vt != nil && vt.MaxNumResults.Valid() { @@ -12379,22 +12606,6 @@ func (u ToolUnionParam) GetRankingOptions() *FileSearchToolRankingOptionsParam { return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetSearchContextSize() *string { - if vt := u.OfWebSearchPreview; vt != nil { - return (*string)(&vt.SearchContextSize) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetUserLocation() *WebSearchToolUserLocationParam { - if vt := u.OfWebSearchPreview; vt != nil { - return &vt.UserLocation - } - return nil -} - // Returns a pointer to the underlying variant's property, if present. func (u ToolUnionParam) GetDisplayHeight() *int64 { if vt := u.OfComputerUsePreview; vt != nil { @@ -12595,10 +12806,10 @@ func (u ToolUnionParam) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfFileSearch; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfWebSearchPreview; vt != nil { - return (*string)(&vt.Type) } else if vt := u.OfComputerUsePreview; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebSearch; vt != nil { + return (*string)(&vt.Type) } else if vt := u.OfMcp; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfCodeInterpreter; vt != nil { @@ -12609,6 +12820,8 @@ func (u ToolUnionParam) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfCustom; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebSearchPreview; vt != nil { + return (*string)(&vt.Type) } return nil } @@ -12623,19 +12836,273 @@ func (u ToolUnionParam) GetDescription() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetSearchContextSize() *string { + if vt := u.OfWebSearch; vt != nil { + return (*string)(&vt.SearchContextSize) + } else if vt := u.OfWebSearchPreview; vt != nil { + return (*string)(&vt.SearchContextSize) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ToolUnionParam) GetFilters() (res toolUnionParamFilters) { + if vt := u.OfFileSearch; vt != nil { + res.any = vt.Filters.asAny() + } else if vt := u.OfWebSearch; vt != nil { + res.any = &vt.Filters + } + return +} + +// Can have the runtime types [*shared.ComparisonFilterParam], +// [*shared.CompoundFilterParam], [*ToolWebSearchFiltersParam] +type toolUnionParamFilters struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *shared.ComparisonFilterParam: +// case *shared.CompoundFilterParam: +// case *responses.ToolWebSearchFiltersParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamFilters) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamFilters) GetKey() *string { + switch vt := u.any.(type) { + case *FileSearchToolFiltersUnionParam: + return vt.GetKey() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamFilters) GetValue() *shared.ComparisonFilterValueUnionParam { + switch vt := u.any.(type) { + case *FileSearchToolFiltersUnionParam: + return vt.GetValue() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamFilters) GetFilters() []shared.ComparisonFilterParam { + switch vt := u.any.(type) { + case *FileSearchToolFiltersUnionParam: + return vt.GetFilters() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamFilters) GetAllowedDomains() []string { + switch vt := u.any.(type) { + case *ToolWebSearchFiltersParam: + return vt.AllowedDomains + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamFilters) GetType() *string { + switch vt := u.any.(type) { + case *FileSearchToolFiltersUnionParam: + return vt.GetType() + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ToolUnionParam) GetUserLocation() (res toolUnionParamUserLocation) { + if vt := u.OfWebSearch; vt != nil { + res.any = &vt.UserLocation + } else if vt := u.OfWebSearchPreview; vt != nil { + res.any = &vt.UserLocation + } + return +} + +// Can have the runtime types [*ToolWebSearchUserLocationParam], +// [*WebSearchToolUserLocationParam] +type toolUnionParamUserLocation struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *responses.ToolWebSearchUserLocationParam: +// case *responses.WebSearchToolUserLocationParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamUserLocation) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamUserLocation) GetCity() *string { + switch vt := u.any.(type) { + case *ToolWebSearchUserLocationParam: + return paramutil.AddrIfPresent(vt.City) + case *WebSearchToolUserLocationParam: + return paramutil.AddrIfPresent(vt.City) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamUserLocation) GetCountry() *string { + switch vt := u.any.(type) { + case *ToolWebSearchUserLocationParam: + return paramutil.AddrIfPresent(vt.Country) + case *WebSearchToolUserLocationParam: + return paramutil.AddrIfPresent(vt.Country) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamUserLocation) GetRegion() *string { + switch vt := u.any.(type) { + case *ToolWebSearchUserLocationParam: + return paramutil.AddrIfPresent(vt.Region) + case *WebSearchToolUserLocationParam: + return paramutil.AddrIfPresent(vt.Region) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamUserLocation) GetTimezone() *string { + switch vt := u.any.(type) { + case *ToolWebSearchUserLocationParam: + return paramutil.AddrIfPresent(vt.Timezone) + case *WebSearchToolUserLocationParam: + return paramutil.AddrIfPresent(vt.Timezone) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamUserLocation) GetType() *string { + switch vt := u.any.(type) { + case *ToolWebSearchUserLocationParam: + return (*string)(&vt.Type) + case *WebSearchToolUserLocationParam: + return (*string)(&vt.Type) + } + return nil +} + func init() { apijson.RegisterUnion[ToolUnionParam]( "type", apijson.Discriminator[FunctionToolParam]("function"), apijson.Discriminator[FileSearchToolParam]("file_search"), - apijson.Discriminator[WebSearchToolParam]("web_search_preview"), - apijson.Discriminator[WebSearchToolParam]("web_search_preview_2025_03_11"), apijson.Discriminator[ComputerToolParam]("computer_use_preview"), + apijson.Discriminator[ToolWebSearchParam]("web_search"), + apijson.Discriminator[ToolWebSearchParam]("web_search_2025_08_26"), apijson.Discriminator[ToolMcpParam]("mcp"), apijson.Discriminator[ToolCodeInterpreterParam]("code_interpreter"), apijson.Discriminator[ToolImageGenerationParam]("image_generation"), apijson.Discriminator[ToolLocalShellParam]("local_shell"), apijson.Discriminator[CustomToolParam]("custom"), + apijson.Discriminator[WebSearchToolParam]("web_search_preview"), + apijson.Discriminator[WebSearchToolParam]("web_search_preview_2025_03_11"), + ) +} + +// Search the Internet for sources related to the prompt. Learn more about the +// [web search tool](https://platform.openai.com/docs/guides/tools-web-search). +// +// The property Type is required. +type ToolWebSearchParam struct { + // The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + // + // Any of "web_search", "web_search_2025_08_26". + Type string `json:"type,omitzero,required"` + // Filters for the search. + Filters ToolWebSearchFiltersParam `json:"filters,omitzero"` + // The approximate location of the user. + UserLocation ToolWebSearchUserLocationParam `json:"user_location,omitzero"` + // High level guidance for the amount of context window space to use for the + // search. One of `low`, `medium`, or `high`. `medium` is the default. + // + // Any of "low", "medium", "high". + SearchContextSize string `json:"search_context_size,omitzero"` + paramObj +} + +func (r ToolWebSearchParam) MarshalJSON() (data []byte, err error) { + type shadow ToolWebSearchParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolWebSearchParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[ToolWebSearchParam]( + "type", "web_search", "web_search_2025_08_26", + ) + apijson.RegisterFieldValidator[ToolWebSearchParam]( + "search_context_size", "low", "medium", "high", + ) +} + +// Filters for the search. +type ToolWebSearchFiltersParam struct { + // Allowed domains for the search. If not provided, all domains are allowed. + // Subdomains of the provided domains are allowed as well. + // + // Example: `["pubmed.ncbi.nlm.nih.gov"]` + AllowedDomains []string `json:"allowed_domains,omitzero"` + paramObj +} + +func (r ToolWebSearchFiltersParam) MarshalJSON() (data []byte, err error) { + type shadow ToolWebSearchFiltersParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolWebSearchFiltersParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The approximate location of the user. +type ToolWebSearchUserLocationParam struct { + // Free text input for the city of the user, e.g. `San Francisco`. + City param.Opt[string] `json:"city,omitzero"` + // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + // the user, e.g. `US`. + Country param.Opt[string] `json:"country,omitzero"` + // Free text input for the region of the user, e.g. `California`. + Region param.Opt[string] `json:"region,omitzero"` + // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + // user, e.g. `America/Los_Angeles`. + Timezone param.Opt[string] `json:"timezone,omitzero"` + // The type of location approximation. Always `approximate`. + // + // Any of "approximate". + Type string `json:"type,omitzero"` + paramObj +} + +func (r ToolWebSearchUserLocationParam) MarshalJSON() (data []byte, err error) { + type shadow ToolWebSearchUserLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolWebSearchUserLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[ToolWebSearchUserLocationParam]( + "type", "approximate", ) } @@ -13619,6 +14086,8 @@ type ResponseNewParams struct { // Specify additional output data to include in the model response. Currently // supported values are: // + // - `web_search_call.action.sources`: Include the sources of the web search tool + // call. // - `code_interpreter_call.outputs`: Includes the outputs of python code execution // in code interpreter tool call items. // - `computer_call_output.output.image_url`: Include image urls from the computer diff --git a/shared/constant/constants.go b/shared/constant/constants.go index aa5e34d6..65061525 100644 --- a/shared/constant/constants.go +++ b/shared/constant/constants.go @@ -217,6 +217,7 @@ type TranscriptTextDone string // Always "transcript.text.d type Type string // Always "type" type Upload string // Always "upload" type UploadPart string // Always "upload.part" +type URL string // Always "url" type URLCitation string // Always "url_citation" type User string // Always "user" type VectorStore string // Always "vector_store" @@ -521,6 +522,7 @@ func (c TranscriptTextDone) Default() TranscriptTextDone { return "transcript. func (c Type) Default() Type { return "type" } func (c Upload) Default() Upload { return "upload" } func (c UploadPart) Default() UploadPart { return "upload.part" } +func (c URL) Default() URL { return "url" } func (c URLCitation) Default() URLCitation { return "url_citation" } func (c User) Default() User { return "user" } func (c VectorStore) Default() VectorStore { return "vector_store" } @@ -741,6 +743,7 @@ func (c TranscriptTextDone) MarshalJSON() ([]byte, error) { retur func (c Type) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Upload) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c UploadPart) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c URL) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c URLCitation) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c User) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c VectorStore) MarshalJSON() ([]byte, error) { return marshalString(c) } From d156eeca37bc86a5d8e1c973063a8425744810f1 Mon Sep 17 00:00:00 2001 From: Luis Jones <11049493+luisjones@users.noreply.github.com> Date: Thu, 28 Aug 2025 03:00:20 +0100 Subject: [PATCH 07/10] fix(azure): compatibility with edit image endpoint (#477) --- azure/azure.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/azure/azure.go b/azure/azure.go index 866e80ad..ac729c09 100644 --- a/azure/azure.go +++ b/azure/azure.go @@ -136,11 +136,12 @@ var jsonRoutes = map[string]bool{ "/openai/images/generations": true, } -// audioMultipartRoutes have mime/multipart payloads. These are less generic - we're very much +// multipartRoutes have mime/multipart payloads. These are less generic - we're very much // expecting a transcription or translation payload for these. -var audioMultipartRoutes = map[string]bool{ +var multipartRoutes = map[string]bool{ "/openai/audio/transcriptions": true, "/openai/audio/translations": true, + "/openai/images/edits": true, } // getReplacementPathWithDeployment parses the request body to extract out the Model parameter (or equivalent) @@ -150,8 +151,8 @@ func getReplacementPathWithDeployment(req *http.Request) (string, error) { return getJSONRoute(req) } - if audioMultipartRoutes[req.URL.Path] { - return getAudioMultipartRoute(req) + if multipartRoutes[req.URL.Path] { + return getMultipartRoute(req) } // No need to relocate the path. We've already tacked on /openai when we setup the endpoint. @@ -181,7 +182,7 @@ func getJSONRoute(req *http.Request) (string, error) { return strings.Replace(req.URL.Path, "/openai/", "/openai/deployments/"+escapedDeployment+"/", 1), nil } -func getAudioMultipartRoute(req *http.Request) (string, error) { +func getMultipartRoute(req *http.Request) (string, error) { // body is a multipart/mime body type instead. mimeBytes, err := io.ReadAll(req.Body) From 8dfed35f11a00970ad804ab985cf393c2332ea8f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 28 Aug 2025 16:50:00 +0000 Subject: [PATCH 08/10] fix: close body before retrying --- internal/requestconfig/requestconfig.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/requestconfig/requestconfig.go b/internal/requestconfig/requestconfig.go index f8ea4b57..71f1805c 100644 --- a/internal/requestconfig/requestconfig.go +++ b/internal/requestconfig/requestconfig.go @@ -465,6 +465,11 @@ func (cfg *RequestConfig) Execute() (err error) { break } + // Close the response body before retrying to prevent connection leaks + if res != nil && res.Body != nil { + res.Body.Close() + } + time.Sleep(retryDelay(res, retryCount)) } From 130fc8ea5ba39e6c1457ed6d26ef827d931a6242 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Sep 2025 00:05:13 +0000 Subject: [PATCH 09/10] feat(api): realtime API updates --- .stats.yml | 8 +- api.md | 28 + audiospeech.go | 2 + chatcompletion.go | 2 + client.go | 3 + realtime/aliases.go | 493 +++++++++++++ realtime/clientsecret.go | 1049 ++++++++++++++++++++++++++++ realtime/clientsecret_test.go | 116 ++++ realtime/realtime.go | 1153 +++++++++++++++++++++++++++++++ responses/response.go | 508 +++++++------- scripts/detect-breaking-changes | 1 + shared/constant/constants.go | 943 +++++++++++++++---------- webhooks/webhook.go | 116 +++- 13 files changed, 3804 insertions(+), 618 deletions(-) create mode 100644 realtime/aliases.go create mode 100644 realtime/clientsecret.go create mode 100644 realtime/clientsecret_test.go create mode 100644 realtime/realtime.go diff --git a/.stats.yml b/.stats.yml index 0c18b873..d101c77a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 105 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-8517ffa1004e31ca2523d617629e64be6fe4f13403ddfd9db5b3be002656cbde.yml -openapi_spec_hash: b64dd8c8b23082a7aa2a3e5c5fffd8bd -config_hash: fe0ea26680ac2075a6cd66416aefe7db +configured_endpoints: 106 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-356b4364203ff36d7724074cd04f6e684253bfcc3c9d969122d730aa7bc51b46.yml +openapi_spec_hash: 4ab8e96f52699bc3d2b0c4432aa92af8 +config_hash: b854932c0ea24b400bdd64e4376936bd diff --git a/api.md b/api.md index 821c5519..ff92f6dd 100644 --- a/api.md +++ b/api.md @@ -413,6 +413,7 @@ Response Types: - webhooks.FineTuningJobCancelledWebhookEvent - webhooks.FineTuningJobFailedWebhookEvent - webhooks.FineTuningJobSucceededWebhookEvent +- webhooks.RealtimeCallIncomingWebhookEvent - webhooks.ResponseCancelledWebhookEvent - webhooks.ResponseCompletedWebhookEvent - webhooks.ResponseFailedWebhookEvent @@ -657,6 +658,7 @@ Params Types: - responses.ToolChoiceMcpParam - responses.ToolChoiceOptions - responses.ToolChoiceTypesParam +- responses.WebSearchPreviewToolParam - responses.WebSearchToolParam Response Types: @@ -759,6 +761,7 @@ Response Types: - responses.ToolChoiceMcp - responses.ToolChoiceOptions - responses.ToolChoiceTypes +- responses.WebSearchPreviewTool - responses.WebSearchTool Methods: @@ -778,6 +781,31 @@ Methods: - client.Responses.InputItems.List(ctx context.Context, responseID string, query responses.InputItemListParams) (pagination.CursorPage[responses.ResponseItemUnion], error) +# Realtime + +Params Types: + +- realtime.RealtimeAudioConfigParam +- realtime.RealtimeClientSecretConfigParam +- realtime.RealtimeSessionCreateRequestParam +- realtime.RealtimeToolChoiceConfigUnionParam +- realtime.RealtimeToolsConfigParam +- realtime.RealtimeToolsConfigUnionParam +- realtime.RealtimeTracingConfigUnionParam +- realtime.RealtimeTranscriptionSessionCreateRequestParam +- realtime.RealtimeTruncationUnionParam + +## ClientSecrets + +Response Types: + +- realtime.RealtimeSessionCreateResponse +- realtime.ClientSecretNewResponse + +Methods: + +- client.Realtime.ClientSecrets.New(ctx context.Context, body realtime.ClientSecretNewParams) (realtime.ClientSecretNewResponse, error) + # Conversations Response Types: diff --git a/audiospeech.go b/audiospeech.go index b05c7b3f..099549d8 100644 --- a/audiospeech.go +++ b/audiospeech.go @@ -101,6 +101,8 @@ const ( AudioSpeechNewParamsVoiceSage AudioSpeechNewParamsVoice = "sage" AudioSpeechNewParamsVoiceShimmer AudioSpeechNewParamsVoice = "shimmer" AudioSpeechNewParamsVoiceVerse AudioSpeechNewParamsVoice = "verse" + AudioSpeechNewParamsVoiceMarin AudioSpeechNewParamsVoice = "marin" + AudioSpeechNewParamsVoiceCedar AudioSpeechNewParamsVoice = "cedar" ) // The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, diff --git a/chatcompletion.go b/chatcompletion.go index bca168b2..7d2a658b 100644 --- a/chatcompletion.go +++ b/chatcompletion.go @@ -571,6 +571,8 @@ const ( ChatCompletionAudioParamVoiceSage ChatCompletionAudioParamVoice = "sage" ChatCompletionAudioParamVoiceShimmer ChatCompletionAudioParamVoice = "shimmer" ChatCompletionAudioParamVoiceVerse ChatCompletionAudioParamVoice = "verse" + ChatCompletionAudioParamVoiceMarin ChatCompletionAudioParamVoice = "marin" + ChatCompletionAudioParamVoiceCedar ChatCompletionAudioParamVoice = "cedar" ) // Represents a streamed chunk of a chat completion response returned by the model, diff --git a/client.go b/client.go index 7645f7b1..e2938d7c 100644 --- a/client.go +++ b/client.go @@ -10,6 +10,7 @@ import ( "github.com/openai/openai-go/v2/conversations" "github.com/openai/openai-go/v2/internal/requestconfig" "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/realtime" "github.com/openai/openai-go/v2/responses" "github.com/openai/openai-go/v2/webhooks" ) @@ -35,6 +36,7 @@ type Client struct { Batches BatchService Uploads UploadService Responses responses.ResponseService + Realtime realtime.RealtimeService Conversations conversations.ConversationService Containers ContainerService } @@ -88,6 +90,7 @@ func NewClient(opts ...option.RequestOption) (r Client) { r.Batches = NewBatchService(opts...) r.Uploads = NewUploadService(opts...) r.Responses = responses.NewResponseService(opts...) + r.Realtime = realtime.NewRealtimeService(opts...) r.Conversations = conversations.NewConversationService(opts...) r.Containers = NewContainerService(opts...) diff --git a/realtime/aliases.go b/realtime/aliases.go new file mode 100644 index 00000000..c70c7b33 --- /dev/null +++ b/realtime/aliases.go @@ -0,0 +1,493 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package realtime + +import ( + "github.com/openai/openai-go/v2/internal/apierror" + "github.com/openai/openai-go/v2/packages/param" + "github.com/openai/openai-go/v2/shared" +) + +// aliased to make [param.APIUnion] private when embedding +type paramUnion = param.APIUnion + +// aliased to make [param.APIObject] private when embedding +type paramObj = param.APIObject + +type Error = apierror.Error + +// This is an alias to an internal type. +type ChatModel = shared.ChatModel + +// Equals "gpt-5" +const ChatModelGPT5 = shared.ChatModelGPT5 + +// Equals "gpt-5-mini" +const ChatModelGPT5Mini = shared.ChatModelGPT5Mini + +// Equals "gpt-5-nano" +const ChatModelGPT5Nano = shared.ChatModelGPT5Nano + +// Equals "gpt-5-2025-08-07" +const ChatModelGPT5_2025_08_07 = shared.ChatModelGPT5_2025_08_07 + +// Equals "gpt-5-mini-2025-08-07" +const ChatModelGPT5Mini2025_08_07 = shared.ChatModelGPT5Mini2025_08_07 + +// Equals "gpt-5-nano-2025-08-07" +const ChatModelGPT5Nano2025_08_07 = shared.ChatModelGPT5Nano2025_08_07 + +// Equals "gpt-5-chat-latest" +const ChatModelGPT5ChatLatest = shared.ChatModelGPT5ChatLatest + +// Equals "gpt-4.1" +const ChatModelGPT4_1 = shared.ChatModelGPT4_1 + +// Equals "gpt-4.1-mini" +const ChatModelGPT4_1Mini = shared.ChatModelGPT4_1Mini + +// Equals "gpt-4.1-nano" +const ChatModelGPT4_1Nano = shared.ChatModelGPT4_1Nano + +// Equals "gpt-4.1-2025-04-14" +const ChatModelGPT4_1_2025_04_14 = shared.ChatModelGPT4_1_2025_04_14 + +// Equals "gpt-4.1-mini-2025-04-14" +const ChatModelGPT4_1Mini2025_04_14 = shared.ChatModelGPT4_1Mini2025_04_14 + +// Equals "gpt-4.1-nano-2025-04-14" +const ChatModelGPT4_1Nano2025_04_14 = shared.ChatModelGPT4_1Nano2025_04_14 + +// Equals "o4-mini" +const ChatModelO4Mini = shared.ChatModelO4Mini + +// Equals "o4-mini-2025-04-16" +const ChatModelO4Mini2025_04_16 = shared.ChatModelO4Mini2025_04_16 + +// Equals "o3" +const ChatModelO3 = shared.ChatModelO3 + +// Equals "o3-2025-04-16" +const ChatModelO3_2025_04_16 = shared.ChatModelO3_2025_04_16 + +// Equals "o3-mini" +const ChatModelO3Mini = shared.ChatModelO3Mini + +// Equals "o3-mini-2025-01-31" +const ChatModelO3Mini2025_01_31 = shared.ChatModelO3Mini2025_01_31 + +// Equals "o1" +const ChatModelO1 = shared.ChatModelO1 + +// Equals "o1-2024-12-17" +const ChatModelO1_2024_12_17 = shared.ChatModelO1_2024_12_17 + +// Equals "o1-preview" +const ChatModelO1Preview = shared.ChatModelO1Preview + +// Equals "o1-preview-2024-09-12" +const ChatModelO1Preview2024_09_12 = shared.ChatModelO1Preview2024_09_12 + +// Equals "o1-mini" +const ChatModelO1Mini = shared.ChatModelO1Mini + +// Equals "o1-mini-2024-09-12" +const ChatModelO1Mini2024_09_12 = shared.ChatModelO1Mini2024_09_12 + +// Equals "gpt-4o" +const ChatModelGPT4o = shared.ChatModelGPT4o + +// Equals "gpt-4o-2024-11-20" +const ChatModelGPT4o2024_11_20 = shared.ChatModelGPT4o2024_11_20 + +// Equals "gpt-4o-2024-08-06" +const ChatModelGPT4o2024_08_06 = shared.ChatModelGPT4o2024_08_06 + +// Equals "gpt-4o-2024-05-13" +const ChatModelGPT4o2024_05_13 = shared.ChatModelGPT4o2024_05_13 + +// Equals "gpt-4o-audio-preview" +const ChatModelGPT4oAudioPreview = shared.ChatModelGPT4oAudioPreview + +// Equals "gpt-4o-audio-preview-2024-10-01" +const ChatModelGPT4oAudioPreview2024_10_01 = shared.ChatModelGPT4oAudioPreview2024_10_01 + +// Equals "gpt-4o-audio-preview-2024-12-17" +const ChatModelGPT4oAudioPreview2024_12_17 = shared.ChatModelGPT4oAudioPreview2024_12_17 + +// Equals "gpt-4o-audio-preview-2025-06-03" +const ChatModelGPT4oAudioPreview2025_06_03 = shared.ChatModelGPT4oAudioPreview2025_06_03 + +// Equals "gpt-4o-mini-audio-preview" +const ChatModelGPT4oMiniAudioPreview = shared.ChatModelGPT4oMiniAudioPreview + +// Equals "gpt-4o-mini-audio-preview-2024-12-17" +const ChatModelGPT4oMiniAudioPreview2024_12_17 = shared.ChatModelGPT4oMiniAudioPreview2024_12_17 + +// Equals "gpt-4o-search-preview" +const ChatModelGPT4oSearchPreview = shared.ChatModelGPT4oSearchPreview + +// Equals "gpt-4o-mini-search-preview" +const ChatModelGPT4oMiniSearchPreview = shared.ChatModelGPT4oMiniSearchPreview + +// Equals "gpt-4o-search-preview-2025-03-11" +const ChatModelGPT4oSearchPreview2025_03_11 = shared.ChatModelGPT4oSearchPreview2025_03_11 + +// Equals "gpt-4o-mini-search-preview-2025-03-11" +const ChatModelGPT4oMiniSearchPreview2025_03_11 = shared.ChatModelGPT4oMiniSearchPreview2025_03_11 + +// Equals "chatgpt-4o-latest" +const ChatModelChatgpt4oLatest = shared.ChatModelChatgpt4oLatest + +// Equals "codex-mini-latest" +const ChatModelCodexMiniLatest = shared.ChatModelCodexMiniLatest + +// Equals "gpt-4o-mini" +const ChatModelGPT4oMini = shared.ChatModelGPT4oMini + +// Equals "gpt-4o-mini-2024-07-18" +const ChatModelGPT4oMini2024_07_18 = shared.ChatModelGPT4oMini2024_07_18 + +// Equals "gpt-4-turbo" +const ChatModelGPT4Turbo = shared.ChatModelGPT4Turbo + +// Equals "gpt-4-turbo-2024-04-09" +const ChatModelGPT4Turbo2024_04_09 = shared.ChatModelGPT4Turbo2024_04_09 + +// Equals "gpt-4-0125-preview" +const ChatModelGPT4_0125Preview = shared.ChatModelGPT4_0125Preview + +// Equals "gpt-4-turbo-preview" +const ChatModelGPT4TurboPreview = shared.ChatModelGPT4TurboPreview + +// Equals "gpt-4-1106-preview" +const ChatModelGPT4_1106Preview = shared.ChatModelGPT4_1106Preview + +// Equals "gpt-4-vision-preview" +const ChatModelGPT4VisionPreview = shared.ChatModelGPT4VisionPreview + +// Equals "gpt-4" +const ChatModelGPT4 = shared.ChatModelGPT4 + +// Equals "gpt-4-0314" +const ChatModelGPT4_0314 = shared.ChatModelGPT4_0314 + +// Equals "gpt-4-0613" +const ChatModelGPT4_0613 = shared.ChatModelGPT4_0613 + +// Equals "gpt-4-32k" +const ChatModelGPT4_32k = shared.ChatModelGPT4_32k + +// Equals "gpt-4-32k-0314" +const ChatModelGPT4_32k0314 = shared.ChatModelGPT4_32k0314 + +// Equals "gpt-4-32k-0613" +const ChatModelGPT4_32k0613 = shared.ChatModelGPT4_32k0613 + +// Equals "gpt-3.5-turbo" +const ChatModelGPT3_5Turbo = shared.ChatModelGPT3_5Turbo + +// Equals "gpt-3.5-turbo-16k" +const ChatModelGPT3_5Turbo16k = shared.ChatModelGPT3_5Turbo16k + +// Equals "gpt-3.5-turbo-0301" +const ChatModelGPT3_5Turbo0301 = shared.ChatModelGPT3_5Turbo0301 + +// Equals "gpt-3.5-turbo-0613" +const ChatModelGPT3_5Turbo0613 = shared.ChatModelGPT3_5Turbo0613 + +// Equals "gpt-3.5-turbo-1106" +const ChatModelGPT3_5Turbo1106 = shared.ChatModelGPT3_5Turbo1106 + +// Equals "gpt-3.5-turbo-0125" +const ChatModelGPT3_5Turbo0125 = shared.ChatModelGPT3_5Turbo0125 + +// Equals "gpt-3.5-turbo-16k-0613" +const ChatModelGPT3_5Turbo16k0613 = shared.ChatModelGPT3_5Turbo16k0613 + +// A filter used to compare a specified attribute key to a given value using a +// defined comparison operation. +// +// This is an alias to an internal type. +type ComparisonFilter = shared.ComparisonFilter + +// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. +// +// - `eq`: equals +// - `ne`: not equal +// - `gt`: greater than +// - `gte`: greater than or equal +// - `lt`: less than +// - `lte`: less than or equal +// +// This is an alias to an internal type. +type ComparisonFilterType = shared.ComparisonFilterType + +// Equals "eq" +const ComparisonFilterTypeEq = shared.ComparisonFilterTypeEq + +// Equals "ne" +const ComparisonFilterTypeNe = shared.ComparisonFilterTypeNe + +// Equals "gt" +const ComparisonFilterTypeGt = shared.ComparisonFilterTypeGt + +// Equals "gte" +const ComparisonFilterTypeGte = shared.ComparisonFilterTypeGte + +// Equals "lt" +const ComparisonFilterTypeLt = shared.ComparisonFilterTypeLt + +// Equals "lte" +const ComparisonFilterTypeLte = shared.ComparisonFilterTypeLte + +// The value to compare against the attribute key; supports string, number, or +// boolean types. +// +// This is an alias to an internal type. +type ComparisonFilterValueUnion = shared.ComparisonFilterValueUnion + +// A filter used to compare a specified attribute key to a given value using a +// defined comparison operation. +// +// This is an alias to an internal type. +type ComparisonFilterParam = shared.ComparisonFilterParam + +// The value to compare against the attribute key; supports string, number, or +// boolean types. +// +// This is an alias to an internal type. +type ComparisonFilterValueUnionParam = shared.ComparisonFilterValueUnionParam + +// Combine multiple filters using `and` or `or`. +// +// This is an alias to an internal type. +type CompoundFilter = shared.CompoundFilter + +// Type of operation: `and` or `or`. +// +// This is an alias to an internal type. +type CompoundFilterType = shared.CompoundFilterType + +// Equals "and" +const CompoundFilterTypeAnd = shared.CompoundFilterTypeAnd + +// Equals "or" +const CompoundFilterTypeOr = shared.CompoundFilterTypeOr + +// Combine multiple filters using `and` or `or`. +// +// This is an alias to an internal type. +type CompoundFilterParam = shared.CompoundFilterParam + +// The input format for the custom tool. Default is unconstrained text. +// +// This is an alias to an internal type. +type CustomToolInputFormatUnion = shared.CustomToolInputFormatUnion + +// Unconstrained free-form text. +// +// This is an alias to an internal type. +type CustomToolInputFormatText = shared.CustomToolInputFormatText + +// A grammar defined by the user. +// +// This is an alias to an internal type. +type CustomToolInputFormatGrammar = shared.CustomToolInputFormatGrammar + +// The input format for the custom tool. Default is unconstrained text. +// +// This is an alias to an internal type. +type CustomToolInputFormatUnionParam = shared.CustomToolInputFormatUnionParam + +// Unconstrained free-form text. +// +// This is an alias to an internal type. +type CustomToolInputFormatTextParam = shared.CustomToolInputFormatTextParam + +// A grammar defined by the user. +// +// This is an alias to an internal type. +type CustomToolInputFormatGrammarParam = shared.CustomToolInputFormatGrammarParam + +// This is an alias to an internal type. +type ErrorObject = shared.ErrorObject + +// This is an alias to an internal type. +type FunctionDefinition = shared.FunctionDefinition + +// This is an alias to an internal type. +type FunctionDefinitionParam = shared.FunctionDefinitionParam + +// The parameters the functions accepts, described as a JSON Schema object. See the +// [guide](https://platform.openai.com/docs/guides/function-calling) for examples, +// and the +// [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for +// documentation about the format. +// +// Omitting `parameters` defines a function with an empty parameter list. +// +// This is an alias to an internal type. +type FunctionParameters = shared.FunctionParameters + +// Set of 16 key-value pairs that can be attached to an object. This can be useful +// for storing additional information about the object in a structured format, and +// querying for objects via API or the dashboard. +// +// Keys are strings with a maximum length of 64 characters. Values are strings with +// a maximum length of 512 characters. +// +// This is an alias to an internal type. +type Metadata = shared.Metadata + +// **gpt-5 and o-series models only** +// +// Configuration options for +// [reasoning models](https://platform.openai.com/docs/guides/reasoning). +// +// This is an alias to an internal type. +type Reasoning = shared.Reasoning + +// **Deprecated:** use `summary` instead. +// +// A summary of the reasoning performed by the model. This can be useful for +// debugging and understanding the model's reasoning process. One of `auto`, +// `concise`, or `detailed`. +// +// This is an alias to an internal type. +type ReasoningGenerateSummary = shared.ReasoningGenerateSummary + +// Equals "auto" +const ReasoningGenerateSummaryAuto = shared.ReasoningGenerateSummaryAuto + +// Equals "concise" +const ReasoningGenerateSummaryConcise = shared.ReasoningGenerateSummaryConcise + +// Equals "detailed" +const ReasoningGenerateSummaryDetailed = shared.ReasoningGenerateSummaryDetailed + +// A summary of the reasoning performed by the model. This can be useful for +// debugging and understanding the model's reasoning process. One of `auto`, +// `concise`, or `detailed`. +// +// This is an alias to an internal type. +type ReasoningSummary = shared.ReasoningSummary + +// Equals "auto" +const ReasoningSummaryAuto = shared.ReasoningSummaryAuto + +// Equals "concise" +const ReasoningSummaryConcise = shared.ReasoningSummaryConcise + +// Equals "detailed" +const ReasoningSummaryDetailed = shared.ReasoningSummaryDetailed + +// **gpt-5 and o-series models only** +// +// Configuration options for +// [reasoning models](https://platform.openai.com/docs/guides/reasoning). +// +// This is an alias to an internal type. +type ReasoningParam = shared.ReasoningParam + +// Constrains effort on reasoning for +// [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently +// supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning +// effort can result in faster responses and fewer tokens used on reasoning in a +// response. +// +// This is an alias to an internal type. +type ReasoningEffort = shared.ReasoningEffort + +// Equals "minimal" +const ReasoningEffortMinimal = shared.ReasoningEffortMinimal + +// Equals "low" +const ReasoningEffortLow = shared.ReasoningEffortLow + +// Equals "medium" +const ReasoningEffortMedium = shared.ReasoningEffortMedium + +// Equals "high" +const ReasoningEffortHigh = shared.ReasoningEffortHigh + +// JSON object response format. An older method of generating JSON responses. Using +// `json_schema` is recommended for models that support it. Note that the model +// will not generate JSON without a system or user message instructing it to do so. +// +// This is an alias to an internal type. +type ResponseFormatJSONObject = shared.ResponseFormatJSONObject + +// JSON object response format. An older method of generating JSON responses. Using +// `json_schema` is recommended for models that support it. Note that the model +// will not generate JSON without a system or user message instructing it to do so. +// +// This is an alias to an internal type. +type ResponseFormatJSONObjectParam = shared.ResponseFormatJSONObjectParam + +// JSON Schema response format. Used to generate structured JSON responses. Learn +// more about +// [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). +// +// This is an alias to an internal type. +type ResponseFormatJSONSchema = shared.ResponseFormatJSONSchema + +// Structured Outputs configuration options, including a JSON Schema. +// +// This is an alias to an internal type. +type ResponseFormatJSONSchemaJSONSchema = shared.ResponseFormatJSONSchemaJSONSchema + +// JSON Schema response format. Used to generate structured JSON responses. Learn +// more about +// [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). +// +// This is an alias to an internal type. +type ResponseFormatJSONSchemaParam = shared.ResponseFormatJSONSchemaParam + +// Structured Outputs configuration options, including a JSON Schema. +// +// This is an alias to an internal type. +type ResponseFormatJSONSchemaJSONSchemaParam = shared.ResponseFormatJSONSchemaJSONSchemaParam + +// Default response format. Used to generate text responses. +// +// This is an alias to an internal type. +type ResponseFormatText = shared.ResponseFormatText + +// Default response format. Used to generate text responses. +// +// This is an alias to an internal type. +type ResponseFormatTextParam = shared.ResponseFormatTextParam + +// This is an alias to an internal type. +type ResponsesModel = shared.ResponsesModel + +// Equals "o1-pro" +const ResponsesModelO1Pro = shared.ResponsesModelO1Pro + +// Equals "o1-pro-2025-03-19" +const ResponsesModelO1Pro2025_03_19 = shared.ResponsesModelO1Pro2025_03_19 + +// Equals "o3-pro" +const ResponsesModelO3Pro = shared.ResponsesModelO3Pro + +// Equals "o3-pro-2025-06-10" +const ResponsesModelO3Pro2025_06_10 = shared.ResponsesModelO3Pro2025_06_10 + +// Equals "o3-deep-research" +const ResponsesModelO3DeepResearch = shared.ResponsesModelO3DeepResearch + +// Equals "o3-deep-research-2025-06-26" +const ResponsesModelO3DeepResearch2025_06_26 = shared.ResponsesModelO3DeepResearch2025_06_26 + +// Equals "o4-mini-deep-research" +const ResponsesModelO4MiniDeepResearch = shared.ResponsesModelO4MiniDeepResearch + +// Equals "o4-mini-deep-research-2025-06-26" +const ResponsesModelO4MiniDeepResearch2025_06_26 = shared.ResponsesModelO4MiniDeepResearch2025_06_26 + +// Equals "computer-use-preview" +const ResponsesModelComputerUsePreview = shared.ResponsesModelComputerUsePreview + +// Equals "computer-use-preview-2025-03-11" +const ResponsesModelComputerUsePreview2025_03_11 = shared.ResponsesModelComputerUsePreview2025_03_11 diff --git a/realtime/clientsecret.go b/realtime/clientsecret.go new file mode 100644 index 00000000..c294ab3e --- /dev/null +++ b/realtime/clientsecret.go @@ -0,0 +1,1049 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package realtime + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/openai/openai-go/v2/internal/apijson" + "github.com/openai/openai-go/v2/internal/requestconfig" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/packages/param" + "github.com/openai/openai-go/v2/packages/respjson" + "github.com/openai/openai-go/v2/responses" + "github.com/openai/openai-go/v2/shared/constant" +) + +// ClientSecretService contains methods and other services that help with +// interacting with the openai API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewClientSecretService] method instead. +type ClientSecretService struct { + Options []option.RequestOption +} + +// NewClientSecretService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewClientSecretService(opts ...option.RequestOption) (r ClientSecretService) { + r = ClientSecretService{} + r.Options = opts + return +} + +// Create a Realtime session and client secret for either realtime or +// transcription. +func (r *ClientSecretService) New(ctx context.Context, body ClientSecretNewParams, opts ...option.RequestOption) (res *ClientSecretNewResponse, err error) { + opts = append(r.Options[:], opts...) + path := "realtime/client_secrets" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return +} + +// A Realtime session configuration object. +type RealtimeSessionCreateResponse struct { + // Unique identifier for the session that looks like `sess_1234567890abcdef`. + ID string `json:"id"` + // Configuration for input and output audio for the session. + Audio RealtimeSessionCreateResponseAudio `json:"audio"` + // Expiration timestamp for the session, in seconds since epoch. + ExpiresAt int64 `json:"expires_at"` + // Additional fields to include in server outputs. + // + // - `item.input_audio_transcription.logprobs`: Include logprobs for input audio + // transcription. + // + // Any of "item.input_audio_transcription.logprobs". + Include []string `json:"include"` + // The default system instructions (i.e. system message) prepended to model calls. + // This field allows the client to guide the model on desired responses. The model + // can be instructed on response content and format, (e.g. "be extremely succinct", + // "act friendly", "here are examples of good responses") and on audio behavior + // (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + // instructions are not guaranteed to be followed by the model, but they provide + // guidance to the model on the desired behavior. + // + // Note that the server sets default instructions which will be used if this field + // is not set and are visible in the `session.created` event at the start of the + // session. + Instructions string `json:"instructions"` + // Maximum number of output tokens for a single assistant response, inclusive of + // tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + // `inf` for the maximum available tokens for a given model. Defaults to `inf`. + MaxOutputTokens RealtimeSessionCreateResponseMaxOutputTokensUnion `json:"max_output_tokens"` + // The Realtime model used for this session. + Model string `json:"model"` + // The object type. Always `realtime.session`. + Object string `json:"object"` + // The set of modalities the model can respond with. To disable audio, set this to + // ["text"]. + // + // Any of "text", "audio". + OutputModalities []string `json:"output_modalities"` + // How the model chooses tools. Options are `auto`, `none`, `required`, or specify + // a function. + ToolChoice string `json:"tool_choice"` + // Tools (functions) available to the model. + Tools []RealtimeSessionCreateResponseTool `json:"tools"` + // Configuration options for tracing. Set to null to disable tracing. Once tracing + // is enabled for a session, the configuration cannot be modified. + // + // `auto` will create a trace for the session with default values for the workflow + // name, group id, and metadata. + Tracing RealtimeSessionCreateResponseTracingUnion `json:"tracing"` + // Configuration for turn detection. Can be set to `null` to turn off. Server VAD + // means that the model will detect the start and end of speech based on audio + // volume and respond at the end of user speech. + TurnDetection RealtimeSessionCreateResponseTurnDetection `json:"turn_detection"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Audio respjson.Field + ExpiresAt respjson.Field + Include respjson.Field + Instructions respjson.Field + MaxOutputTokens respjson.Field + Model respjson.Field + Object respjson.Field + OutputModalities respjson.Field + ToolChoice respjson.Field + Tools respjson.Field + Tracing respjson.Field + TurnDetection respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponse) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for input and output audio for the session. +type RealtimeSessionCreateResponseAudio struct { + Input RealtimeSessionCreateResponseAudioInput `json:"input"` + Output RealtimeSessionCreateResponseAudioOutput `json:"output"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Input respjson.Field + Output respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseAudio) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseAudio) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type RealtimeSessionCreateResponseAudioInput struct { + // The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + Format string `json:"format"` + // Configuration for input audio noise reduction. + NoiseReduction RealtimeSessionCreateResponseAudioInputNoiseReduction `json:"noise_reduction"` + // Configuration for input audio transcription. + Transcription RealtimeSessionCreateResponseAudioInputTranscription `json:"transcription"` + // Configuration for turn detection. + TurnDetection RealtimeSessionCreateResponseAudioInputTurnDetection `json:"turn_detection"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Format respjson.Field + NoiseReduction respjson.Field + Transcription respjson.Field + TurnDetection respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseAudioInput) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseAudioInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for input audio noise reduction. +type RealtimeSessionCreateResponseAudioInputNoiseReduction struct { + // Any of "near_field", "far_field". + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseAudioInputNoiseReduction) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseAudioInputNoiseReduction) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for input audio transcription. +type RealtimeSessionCreateResponseAudioInputTranscription struct { + // The language of the input audio. + Language string `json:"language"` + // The model to use for transcription. + Model string `json:"model"` + // Optional text to guide the model's style or continue a previous audio segment. + Prompt string `json:"prompt"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Language respjson.Field + Model respjson.Field + Prompt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseAudioInputTranscription) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseAudioInputTranscription) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for turn detection. +type RealtimeSessionCreateResponseAudioInputTurnDetection struct { + PrefixPaddingMs int64 `json:"prefix_padding_ms"` + SilenceDurationMs int64 `json:"silence_duration_ms"` + Threshold float64 `json:"threshold"` + // Type of turn detection, only `server_vad` is currently supported. + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + PrefixPaddingMs respjson.Field + SilenceDurationMs respjson.Field + Threshold respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseAudioInputTurnDetection) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseAudioInputTurnDetection) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type RealtimeSessionCreateResponseAudioOutput struct { + // The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + Format string `json:"format"` + Speed float64 `json:"speed"` + Voice string `json:"voice"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Format respjson.Field + Speed respjson.Field + Voice respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseAudioOutput) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseAudioOutput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// RealtimeSessionCreateResponseMaxOutputTokensUnion contains all possible +// properties and values from [int64], [constant.Inf]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfInt OfInf] +type RealtimeSessionCreateResponseMaxOutputTokensUnion struct { + // This field will be present if the value is a [int64] instead of an object. + OfInt int64 `json:",inline"` + // This field will be present if the value is a [constant.Inf] instead of an + // object. + OfInf constant.Inf `json:",inline"` + JSON struct { + OfInt respjson.Field + OfInf respjson.Field + raw string + } `json:"-"` +} + +func (u RealtimeSessionCreateResponseMaxOutputTokensUnion) AsInt() (v int64) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u RealtimeSessionCreateResponseMaxOutputTokensUnion) AsInf() (v constant.Inf) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u RealtimeSessionCreateResponseMaxOutputTokensUnion) RawJSON() string { return u.JSON.raw } + +func (r *RealtimeSessionCreateResponseMaxOutputTokensUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type RealtimeSessionCreateResponseTool struct { + // The description of the function, including guidance on when and how to call it, + // and guidance about what to tell the user when calling (if anything). + Description string `json:"description"` + // The name of the function. + Name string `json:"name"` + // Parameters of the function in JSON Schema. + Parameters any `json:"parameters"` + // The type of the tool, i.e. `function`. + // + // Any of "function". + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Description respjson.Field + Name respjson.Field + Parameters respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseTool) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseTool) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// RealtimeSessionCreateResponseTracingUnion contains all possible properties and +// values from [constant.Auto], +// [RealtimeSessionCreateResponseTracingTracingConfiguration]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfAuto] +type RealtimeSessionCreateResponseTracingUnion struct { + // This field will be present if the value is a [constant.Auto] instead of an + // object. + OfAuto constant.Auto `json:",inline"` + // This field is from variant + // [RealtimeSessionCreateResponseTracingTracingConfiguration]. + GroupID string `json:"group_id"` + // This field is from variant + // [RealtimeSessionCreateResponseTracingTracingConfiguration]. + Metadata any `json:"metadata"` + // This field is from variant + // [RealtimeSessionCreateResponseTracingTracingConfiguration]. + WorkflowName string `json:"workflow_name"` + JSON struct { + OfAuto respjson.Field + GroupID respjson.Field + Metadata respjson.Field + WorkflowName respjson.Field + raw string + } `json:"-"` +} + +func (u RealtimeSessionCreateResponseTracingUnion) AsAuto() (v constant.Auto) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u RealtimeSessionCreateResponseTracingUnion) AsTracingConfiguration() (v RealtimeSessionCreateResponseTracingTracingConfiguration) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u RealtimeSessionCreateResponseTracingUnion) RawJSON() string { return u.JSON.raw } + +func (r *RealtimeSessionCreateResponseTracingUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Granular configuration for tracing. +type RealtimeSessionCreateResponseTracingTracingConfiguration struct { + // The group id to attach to this trace to enable filtering and grouping in the + // traces dashboard. + GroupID string `json:"group_id"` + // The arbitrary metadata to attach to this trace to enable filtering in the traces + // dashboard. + Metadata any `json:"metadata"` + // The name of the workflow to attach to this trace. This is used to name the trace + // in the traces dashboard. + WorkflowName string `json:"workflow_name"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + GroupID respjson.Field + Metadata respjson.Field + WorkflowName respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseTracingTracingConfiguration) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseTracingTracingConfiguration) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for turn detection. Can be set to `null` to turn off. Server VAD +// means that the model will detect the start and end of speech based on audio +// volume and respond at the end of user speech. +type RealtimeSessionCreateResponseTurnDetection struct { + // Amount of audio to include before the VAD detected speech (in milliseconds). + // Defaults to 300ms. + PrefixPaddingMs int64 `json:"prefix_padding_ms"` + // Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + // With shorter values the model will respond more quickly, but may jump in on + // short pauses from the user. + SilenceDurationMs int64 `json:"silence_duration_ms"` + // Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + // threshold will require louder audio to activate the model, and thus might + // perform better in noisy environments. + Threshold float64 `json:"threshold"` + // Type of turn detection, only `server_vad` is currently supported. + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + PrefixPaddingMs respjson.Field + SilenceDurationMs respjson.Field + Threshold respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeSessionCreateResponseTurnDetection) RawJSON() string { return r.JSON.raw } +func (r *RealtimeSessionCreateResponseTurnDetection) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Response from creating a session and client secret for the Realtime API. +type ClientSecretNewResponse struct { + // Expiration timestamp for the client secret, in seconds since epoch. + ExpiresAt int64 `json:"expires_at,required"` + // The session configuration for either a realtime or transcription session. + Session ClientSecretNewResponseSessionUnion `json:"session,required"` + // The generated client secret value. + Value string `json:"value,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ExpiresAt respjson.Field + Session respjson.Field + Value respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponse) RawJSON() string { return r.JSON.raw } +func (r *ClientSecretNewResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ClientSecretNewResponseSessionUnion contains all possible properties and values +// from [RealtimeSessionCreateResponse], +// [ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObject]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type ClientSecretNewResponseSessionUnion struct { + ID string `json:"id"` + // This field is a union of [RealtimeSessionCreateResponseAudio], + // [ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudio] + Audio ClientSecretNewResponseSessionUnionAudio `json:"audio"` + ExpiresAt int64 `json:"expires_at"` + Include []string `json:"include"` + // This field is from variant [RealtimeSessionCreateResponse]. + Instructions string `json:"instructions"` + // This field is from variant [RealtimeSessionCreateResponse]. + MaxOutputTokens RealtimeSessionCreateResponseMaxOutputTokensUnion `json:"max_output_tokens"` + // This field is from variant [RealtimeSessionCreateResponse]. + Model string `json:"model"` + Object string `json:"object"` + // This field is from variant [RealtimeSessionCreateResponse]. + OutputModalities []string `json:"output_modalities"` + // This field is from variant [RealtimeSessionCreateResponse]. + ToolChoice string `json:"tool_choice"` + // This field is from variant [RealtimeSessionCreateResponse]. + Tools []RealtimeSessionCreateResponseTool `json:"tools"` + // This field is from variant [RealtimeSessionCreateResponse]. + Tracing RealtimeSessionCreateResponseTracingUnion `json:"tracing"` + // This field is from variant [RealtimeSessionCreateResponse]. + TurnDetection RealtimeSessionCreateResponseTurnDetection `json:"turn_detection"` + JSON struct { + ID respjson.Field + Audio respjson.Field + ExpiresAt respjson.Field + Include respjson.Field + Instructions respjson.Field + MaxOutputTokens respjson.Field + Model respjson.Field + Object respjson.Field + OutputModalities respjson.Field + ToolChoice respjson.Field + Tools respjson.Field + Tracing respjson.Field + TurnDetection respjson.Field + raw string + } `json:"-"` +} + +func (u ClientSecretNewResponseSessionUnion) AsRealtimeSessionConfigurationObject() (v RealtimeSessionCreateResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u ClientSecretNewResponseSessionUnion) AsRealtimeTranscriptionSessionConfigurationObject() (v ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObject) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u ClientSecretNewResponseSessionUnion) RawJSON() string { return u.JSON.raw } + +func (r *ClientSecretNewResponseSessionUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ClientSecretNewResponseSessionUnionAudio is an implicit subunion of +// [ClientSecretNewResponseSessionUnion]. ClientSecretNewResponseSessionUnionAudio +// provides convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [ClientSecretNewResponseSessionUnion]. +type ClientSecretNewResponseSessionUnionAudio struct { + // This field is a union of [RealtimeSessionCreateResponseAudioInput], + // [ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInput] + Input ClientSecretNewResponseSessionUnionAudioInput `json:"input"` + // This field is from variant [RealtimeSessionCreateResponseAudio]. + Output RealtimeSessionCreateResponseAudioOutput `json:"output"` + JSON struct { + Input respjson.Field + Output respjson.Field + raw string + } `json:"-"` +} + +func (r *ClientSecretNewResponseSessionUnionAudio) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ClientSecretNewResponseSessionUnionAudioInput is an implicit subunion of +// [ClientSecretNewResponseSessionUnion]. +// ClientSecretNewResponseSessionUnionAudioInput provides convenient access to the +// sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [ClientSecretNewResponseSessionUnion]. +type ClientSecretNewResponseSessionUnionAudioInput struct { + Format string `json:"format"` + // This field is a union of + // [RealtimeSessionCreateResponseAudioInputNoiseReduction], + // [ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputNoiseReduction] + NoiseReduction ClientSecretNewResponseSessionUnionAudioInputNoiseReduction `json:"noise_reduction"` + // This field is a union of [RealtimeSessionCreateResponseAudioInputTranscription], + // [ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTranscription] + Transcription ClientSecretNewResponseSessionUnionAudioInputTranscription `json:"transcription"` + // This field is a union of [RealtimeSessionCreateResponseAudioInputTurnDetection], + // [ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTurnDetection] + TurnDetection ClientSecretNewResponseSessionUnionAudioInputTurnDetection `json:"turn_detection"` + JSON struct { + Format respjson.Field + NoiseReduction respjson.Field + Transcription respjson.Field + TurnDetection respjson.Field + raw string + } `json:"-"` +} + +func (r *ClientSecretNewResponseSessionUnionAudioInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ClientSecretNewResponseSessionUnionAudioInputNoiseReduction is an implicit +// subunion of [ClientSecretNewResponseSessionUnion]. +// ClientSecretNewResponseSessionUnionAudioInputNoiseReduction provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [ClientSecretNewResponseSessionUnion]. +type ClientSecretNewResponseSessionUnionAudioInputNoiseReduction struct { + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +func (r *ClientSecretNewResponseSessionUnionAudioInputNoiseReduction) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ClientSecretNewResponseSessionUnionAudioInputTranscription is an implicit +// subunion of [ClientSecretNewResponseSessionUnion]. +// ClientSecretNewResponseSessionUnionAudioInputTranscription provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [ClientSecretNewResponseSessionUnion]. +type ClientSecretNewResponseSessionUnionAudioInputTranscription struct { + Language string `json:"language"` + Model string `json:"model"` + Prompt string `json:"prompt"` + JSON struct { + Language respjson.Field + Model respjson.Field + Prompt respjson.Field + raw string + } `json:"-"` +} + +func (r *ClientSecretNewResponseSessionUnionAudioInputTranscription) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ClientSecretNewResponseSessionUnionAudioInputTurnDetection is an implicit +// subunion of [ClientSecretNewResponseSessionUnion]. +// ClientSecretNewResponseSessionUnionAudioInputTurnDetection provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [ClientSecretNewResponseSessionUnion]. +type ClientSecretNewResponseSessionUnionAudioInputTurnDetection struct { + PrefixPaddingMs int64 `json:"prefix_padding_ms"` + SilenceDurationMs int64 `json:"silence_duration_ms"` + Threshold float64 `json:"threshold"` + Type string `json:"type"` + JSON struct { + PrefixPaddingMs respjson.Field + SilenceDurationMs respjson.Field + Threshold respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +func (r *ClientSecretNewResponseSessionUnionAudioInputTurnDetection) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A Realtime transcription session configuration object. +type ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObject struct { + // Unique identifier for the session that looks like `sess_1234567890abcdef`. + ID string `json:"id"` + // Configuration for input audio for the session. + Audio ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudio `json:"audio"` + // Expiration timestamp for the session, in seconds since epoch. + ExpiresAt int64 `json:"expires_at"` + // Additional fields to include in server outputs. + // + // - `item.input_audio_transcription.logprobs`: Include logprobs for input audio + // transcription. + // + // Any of "item.input_audio_transcription.logprobs". + Include []string `json:"include"` + // The object type. Always `realtime.transcription_session`. + Object string `json:"object"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Audio respjson.Field + ExpiresAt respjson.Field + Include respjson.Field + Object respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObject) RawJSON() string { + return r.JSON.raw +} +func (r *ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObject) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for input audio for the session. +type ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudio struct { + Input ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInput `json:"input"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Input respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudio) RawJSON() string { + return r.JSON.raw +} +func (r *ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudio) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInput struct { + // The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + Format string `json:"format"` + // Configuration for input audio noise reduction. + NoiseReduction ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputNoiseReduction `json:"noise_reduction"` + // Configuration of the transcription model. + Transcription ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTranscription `json:"transcription"` + // Configuration for turn detection. + TurnDetection ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTurnDetection `json:"turn_detection"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Format respjson.Field + NoiseReduction respjson.Field + Transcription respjson.Field + TurnDetection respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInput) RawJSON() string { + return r.JSON.raw +} +func (r *ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for input audio noise reduction. +type ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputNoiseReduction struct { + // Any of "near_field", "far_field". + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputNoiseReduction) RawJSON() string { + return r.JSON.raw +} +func (r *ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputNoiseReduction) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration of the transcription model. +type ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTranscription struct { + // The language of the input audio. Supplying the input language in + // [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + // format will improve accuracy and latency. + Language string `json:"language"` + // The model to use for transcription. Can be `gpt-4o-transcribe`, + // `gpt-4o-mini-transcribe`, or `whisper-1`. + // + // Any of "gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1". + Model string `json:"model"` + // An optional text to guide the model's style or continue a previous audio + // segment. The + // [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + // should match the audio language. + Prompt string `json:"prompt"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Language respjson.Field + Model respjson.Field + Prompt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTranscription) RawJSON() string { + return r.JSON.raw +} +func (r *ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTranscription) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for turn detection. +type ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTurnDetection struct { + PrefixPaddingMs int64 `json:"prefix_padding_ms"` + SilenceDurationMs int64 `json:"silence_duration_ms"` + Threshold float64 `json:"threshold"` + // Type of turn detection, only `server_vad` is currently supported. + Type string `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + PrefixPaddingMs respjson.Field + SilenceDurationMs respjson.Field + Threshold respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTurnDetection) RawJSON() string { + return r.JSON.raw +} +func (r *ClientSecretNewResponseSessionRealtimeTranscriptionSessionConfigurationObjectAudioInputTurnDetection) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ClientSecretNewParams struct { + // Configuration for the ephemeral token expiration. + ExpiresAfter ClientSecretNewParamsExpiresAfter `json:"expires_after,omitzero"` + // Session configuration to use for the client secret. Choose either a realtime + // session or a transcription session. + Session ClientSecretNewParamsSessionUnion `json:"session,omitzero"` + paramObj +} + +func (r ClientSecretNewParams) MarshalJSON() (data []byte, err error) { + type shadow ClientSecretNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ClientSecretNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for the ephemeral token expiration. +type ClientSecretNewParamsExpiresAfter struct { + // The number of seconds from the anchor point to the expiration. Select a value + // between `10` and `7200`. + Seconds param.Opt[int64] `json:"seconds,omitzero"` + // The anchor point for the ephemeral token expiration. Only `created_at` is + // currently supported. + // + // Any of "created_at". + Anchor string `json:"anchor,omitzero"` + paramObj +} + +func (r ClientSecretNewParamsExpiresAfter) MarshalJSON() (data []byte, err error) { + type shadow ClientSecretNewParamsExpiresAfter + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ClientSecretNewParamsExpiresAfter) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[ClientSecretNewParamsExpiresAfter]( + "anchor", "created_at", + ) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ClientSecretNewParamsSessionUnion struct { + OfRealtime *RealtimeSessionCreateRequestParam `json:",omitzero,inline"` + OfTranscription *RealtimeTranscriptionSessionCreateRequestParam `json:",omitzero,inline"` + paramUnion +} + +func (u ClientSecretNewParamsSessionUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRealtime, u.OfTranscription) +} +func (u *ClientSecretNewParamsSessionUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *ClientSecretNewParamsSessionUnion) asAny() any { + if !param.IsOmitted(u.OfRealtime) { + return u.OfRealtime + } else if !param.IsOmitted(u.OfTranscription) { + return u.OfTranscription + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetAudio() *RealtimeAudioConfigParam { + if vt := u.OfRealtime; vt != nil { + return &vt.Audio + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetClientSecret() *RealtimeClientSecretConfigParam { + if vt := u.OfRealtime; vt != nil { + return &vt.ClientSecret + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetInstructions() *string { + if vt := u.OfRealtime; vt != nil && vt.Instructions.Valid() { + return &vt.Instructions.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetMaxOutputTokens() *RealtimeSessionCreateRequestMaxOutputTokensUnionParam { + if vt := u.OfRealtime; vt != nil { + return &vt.MaxOutputTokens + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetOutputModalities() []string { + if vt := u.OfRealtime; vt != nil { + return vt.OutputModalities + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetPrompt() *responses.ResponsePromptParam { + if vt := u.OfRealtime; vt != nil { + return &vt.Prompt + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetTemperature() *float64 { + if vt := u.OfRealtime; vt != nil && vt.Temperature.Valid() { + return &vt.Temperature.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetToolChoice() *RealtimeToolChoiceConfigUnionParam { + if vt := u.OfRealtime; vt != nil { + return &vt.ToolChoice + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetTools() RealtimeToolsConfigParam { + if vt := u.OfRealtime; vt != nil { + return vt.Tools + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetTracing() *RealtimeTracingConfigUnionParam { + if vt := u.OfRealtime; vt != nil { + return &vt.Tracing + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetTruncation() *RealtimeTruncationUnionParam { + if vt := u.OfRealtime; vt != nil { + return &vt.Truncation + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetInputAudioFormat() *string { + if vt := u.OfTranscription; vt != nil { + return (*string)(&vt.InputAudioFormat) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetInputAudioNoiseReduction() *RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam { + if vt := u.OfTranscription; vt != nil { + return &vt.InputAudioNoiseReduction + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetInputAudioTranscription() *RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam { + if vt := u.OfTranscription; vt != nil { + return &vt.InputAudioTranscription + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetTurnDetection() *RealtimeTranscriptionSessionCreateRequestTurnDetectionParam { + if vt := u.OfTranscription; vt != nil { + return &vt.TurnDetection + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ClientSecretNewParamsSessionUnion) GetType() *string { + if vt := u.OfRealtime; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTranscription; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ClientSecretNewParamsSessionUnion) GetModel() (res clientSecretNewParamsSessionUnionModel) { + if vt := u.OfRealtime; vt != nil { + res.any = &vt.Model + } else if vt := u.OfTranscription; vt != nil { + res.any = &vt.Model + } + return +} + +// Can have the runtime types [*RealtimeSessionCreateRequestModel], +// [*RealtimeTranscriptionSessionCreateRequestModel] +type clientSecretNewParamsSessionUnionModel struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *realtime.RealtimeSessionCreateRequestModel: +// case *realtime.RealtimeTranscriptionSessionCreateRequestModel: +// default: +// fmt.Errorf("not present") +// } +func (u clientSecretNewParamsSessionUnionModel) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's Include property, if present. +func (u ClientSecretNewParamsSessionUnion) GetInclude() []string { + if vt := u.OfRealtime; vt != nil { + return vt.Include + } else if vt := u.OfTranscription; vt != nil { + return vt.Include + } + return nil +} + +func init() { + apijson.RegisterUnion[ClientSecretNewParamsSessionUnion]( + "type", + apijson.Discriminator[RealtimeSessionCreateRequestParam]("realtime"), + apijson.Discriminator[RealtimeTranscriptionSessionCreateRequestParam]("transcription"), + ) +} diff --git a/realtime/clientsecret_test.go b/realtime/clientsecret_test.go new file mode 100644 index 00000000..b4a4f629 --- /dev/null +++ b/realtime/clientsecret_test.go @@ -0,0 +1,116 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package realtime_test + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/openai/openai-go/v2" + "github.com/openai/openai-go/v2/internal/testutil" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/realtime" + "github.com/openai/openai-go/v2/responses" + "github.com/openai/openai-go/v2/shared/constant" +) + +func TestClientSecretNewWithOptionalParams(t *testing.T) { + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := openai.NewClient( + option.WithBaseURL(baseURL), + option.WithAPIKey("My API Key"), + ) + _, err := client.Realtime.ClientSecrets.New(context.TODO(), realtime.ClientSecretNewParams{ + ExpiresAfter: realtime.ClientSecretNewParamsExpiresAfter{ + Anchor: "created_at", + Seconds: openai.Int(10), + }, + Session: realtime.ClientSecretNewParamsSessionUnion{ + OfRealtime: &realtime.RealtimeSessionCreateRequestParam{ + Model: realtime.RealtimeSessionCreateRequestModelGPT4oRealtime, + Audio: realtime.RealtimeAudioConfigParam{ + Input: realtime.RealtimeAudioConfigInputParam{ + Format: "pcm16", + NoiseReduction: realtime.RealtimeAudioConfigInputNoiseReductionParam{ + Type: "near_field", + }, + Transcription: realtime.RealtimeAudioConfigInputTranscriptionParam{ + Language: openai.String("language"), + Model: "whisper-1", + Prompt: openai.String("prompt"), + }, + TurnDetection: realtime.RealtimeAudioConfigInputTurnDetectionParam{ + CreateResponse: openai.Bool(true), + Eagerness: "low", + IdleTimeoutMs: openai.Int(0), + InterruptResponse: openai.Bool(true), + PrefixPaddingMs: openai.Int(0), + SilenceDurationMs: openai.Int(0), + Threshold: openai.Float(0), + Type: "server_vad", + }, + }, + Output: realtime.RealtimeAudioConfigOutputParam{ + Format: "pcm16", + Speed: openai.Float(0.25), + Voice: "alloy", + }, + }, + ClientSecret: realtime.RealtimeClientSecretConfigParam{ + ExpiresAfter: realtime.RealtimeClientSecretConfigExpiresAfterParam{ + Anchor: "created_at", + Seconds: openai.Int(0), + }, + }, + Include: []string{"item.input_audio_transcription.logprobs"}, + Instructions: openai.String("instructions"), + MaxOutputTokens: realtime.RealtimeSessionCreateRequestMaxOutputTokensUnionParam{ + OfInt: openai.Int(0), + }, + OutputModalities: []string{"text"}, + Prompt: responses.ResponsePromptParam{ + ID: "id", + Variables: map[string]responses.ResponsePromptVariableUnionParam{ + "foo": { + OfString: openai.String("string"), + }, + }, + Version: openai.String("version"), + }, + Temperature: openai.Float(0), + ToolChoice: realtime.RealtimeToolChoiceConfigUnionParam{ + OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsNone), + }, + Tools: realtime.RealtimeToolsConfigParam{realtime.RealtimeToolsConfigUnionParam{ + OfFunction: &realtime.RealtimeToolsConfigUnionFunctionParam{ + Description: openai.String("description"), + Name: openai.String("name"), + Parameters: map[string]interface{}{}, + Type: "function", + }, + }}, + Tracing: realtime.RealtimeTracingConfigUnionParam{ + OfAuto: constant.ValueOf[constant.Auto](), + }, + Truncation: realtime.RealtimeTruncationUnionParam{ + OfRealtimeTruncationStrategy: openai.String("auto"), + }, + }, + }, + }) + if err != nil { + var apierr *openai.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} diff --git a/realtime/realtime.go b/realtime/realtime.go new file mode 100644 index 00000000..d093eb26 --- /dev/null +++ b/realtime/realtime.go @@ -0,0 +1,1153 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package realtime + +import ( + "github.com/openai/openai-go/v2/internal/apijson" + "github.com/openai/openai-go/v2/option" + "github.com/openai/openai-go/v2/packages/param" + "github.com/openai/openai-go/v2/responses" + "github.com/openai/openai-go/v2/shared/constant" +) + +// RealtimeService contains methods and other services that help with interacting +// with the openai API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewRealtimeService] method instead. +type RealtimeService struct { + Options []option.RequestOption + ClientSecrets ClientSecretService +} + +// NewRealtimeService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewRealtimeService(opts ...option.RequestOption) (r RealtimeService) { + r = RealtimeService{} + r.Options = opts + r.ClientSecrets = NewClientSecretService(opts...) + return +} + +// Configuration for input and output audio. +type RealtimeAudioConfigParam struct { + Input RealtimeAudioConfigInputParam `json:"input,omitzero"` + Output RealtimeAudioConfigOutputParam `json:"output,omitzero"` + paramObj +} + +func (r RealtimeAudioConfigParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeAudioConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeAudioConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type RealtimeAudioConfigInputParam struct { + // The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + // `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + // (mono), and little-endian byte order. + // + // Any of "pcm16", "g711_ulaw", "g711_alaw". + Format string `json:"format,omitzero"` + // Configuration for input audio noise reduction. This can be set to `null` to turn + // off. Noise reduction filters audio added to the input audio buffer before it is + // sent to VAD and the model. Filtering the audio can improve VAD and turn + // detection accuracy (reducing false positives) and model performance by improving + // perception of the input audio. + NoiseReduction RealtimeAudioConfigInputNoiseReductionParam `json:"noise_reduction,omitzero"` + // Configuration for input audio transcription, defaults to off and can be set to + // `null` to turn off once on. Input audio transcription is not native to the + // model, since the model consumes audio directly. Transcription runs + // asynchronously through + // [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + // and should be treated as guidance of input audio content rather than precisely + // what the model heard. The client can optionally set the language and prompt for + // transcription, these offer additional guidance to the transcription service. + Transcription RealtimeAudioConfigInputTranscriptionParam `json:"transcription,omitzero"` + // Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + // set to `null` to turn off, in which case the client must manually trigger model + // response. Server VAD means that the model will detect the start and end of + // speech based on audio volume and respond at the end of user speech. Semantic VAD + // is more advanced and uses a turn detection model (in conjunction with VAD) to + // semantically estimate whether the user has finished speaking, then dynamically + // sets a timeout based on this probability. For example, if user audio trails off + // with "uhhm", the model will score a low probability of turn end and wait longer + // for the user to continue speaking. This can be useful for more natural + // conversations, but may have a higher latency. + TurnDetection RealtimeAudioConfigInputTurnDetectionParam `json:"turn_detection,omitzero"` + paramObj +} + +func (r RealtimeAudioConfigInputParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeAudioConfigInputParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeAudioConfigInputParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeAudioConfigInputParam]( + "format", "pcm16", "g711_ulaw", "g711_alaw", + ) +} + +// Configuration for input audio noise reduction. This can be set to `null` to turn +// off. Noise reduction filters audio added to the input audio buffer before it is +// sent to VAD and the model. Filtering the audio can improve VAD and turn +// detection accuracy (reducing false positives) and model performance by improving +// perception of the input audio. +type RealtimeAudioConfigInputNoiseReductionParam struct { + // Type of noise reduction. `near_field` is for close-talking microphones such as + // headphones, `far_field` is for far-field microphones such as laptop or + // conference room microphones. + // + // Any of "near_field", "far_field". + Type string `json:"type,omitzero"` + paramObj +} + +func (r RealtimeAudioConfigInputNoiseReductionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeAudioConfigInputNoiseReductionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeAudioConfigInputNoiseReductionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeAudioConfigInputNoiseReductionParam]( + "type", "near_field", "far_field", + ) +} + +// Configuration for input audio transcription, defaults to off and can be set to +// `null` to turn off once on. Input audio transcription is not native to the +// model, since the model consumes audio directly. Transcription runs +// asynchronously through +// [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) +// and should be treated as guidance of input audio content rather than precisely +// what the model heard. The client can optionally set the language and prompt for +// transcription, these offer additional guidance to the transcription service. +type RealtimeAudioConfigInputTranscriptionParam struct { + // The language of the input audio. Supplying the input language in + // [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + // format will improve accuracy and latency. + Language param.Opt[string] `json:"language,omitzero"` + // An optional text to guide the model's style or continue a previous audio + // segment. For `whisper-1`, the + // [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + // For `gpt-4o-transcribe` models, the prompt is a free text string, for example + // "expect words related to technology". + Prompt param.Opt[string] `json:"prompt,omitzero"` + // The model to use for transcription. Current options are `whisper-1`, + // `gpt-4o-transcribe-latest`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, and + // `gpt-4o-transcribe-diarize`. + // + // Any of "whisper-1", "gpt-4o-transcribe-latest", "gpt-4o-mini-transcribe", + // "gpt-4o-transcribe", "gpt-4o-transcribe-diarize". + Model string `json:"model,omitzero"` + paramObj +} + +func (r RealtimeAudioConfigInputTranscriptionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeAudioConfigInputTranscriptionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeAudioConfigInputTranscriptionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeAudioConfigInputTranscriptionParam]( + "model", "whisper-1", "gpt-4o-transcribe-latest", "gpt-4o-mini-transcribe", "gpt-4o-transcribe", "gpt-4o-transcribe-diarize", + ) +} + +// Configuration for turn detection, ether Server VAD or Semantic VAD. This can be +// set to `null` to turn off, in which case the client must manually trigger model +// response. Server VAD means that the model will detect the start and end of +// speech based on audio volume and respond at the end of user speech. Semantic VAD +// is more advanced and uses a turn detection model (in conjunction with VAD) to +// semantically estimate whether the user has finished speaking, then dynamically +// sets a timeout based on this probability. For example, if user audio trails off +// with "uhhm", the model will score a low probability of turn end and wait longer +// for the user to continue speaking. This can be useful for more natural +// conversations, but may have a higher latency. +type RealtimeAudioConfigInputTurnDetectionParam struct { + // Optional idle timeout after which turn detection will auto-timeout when no + // additional audio is received. + IdleTimeoutMs param.Opt[int64] `json:"idle_timeout_ms,omitzero"` + // Whether or not to automatically generate a response when a VAD stop event + // occurs. + CreateResponse param.Opt[bool] `json:"create_response,omitzero"` + // Whether or not to automatically interrupt any ongoing response with output to + // the default conversation (i.e. `conversation` of `auto`) when a VAD start event + // occurs. + InterruptResponse param.Opt[bool] `json:"interrupt_response,omitzero"` + // Used only for `server_vad` mode. Amount of audio to include before the VAD + // detected speech (in milliseconds). Defaults to 300ms. + PrefixPaddingMs param.Opt[int64] `json:"prefix_padding_ms,omitzero"` + // Used only for `server_vad` mode. Duration of silence to detect speech stop (in + // milliseconds). Defaults to 500ms. With shorter values the model will respond + // more quickly, but may jump in on short pauses from the user. + SilenceDurationMs param.Opt[int64] `json:"silence_duration_ms,omitzero"` + // Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this + // defaults to 0.5. A higher threshold will require louder audio to activate the + // model, and thus might perform better in noisy environments. + Threshold param.Opt[float64] `json:"threshold,omitzero"` + // Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` + // will wait longer for the user to continue speaking, `high` will respond more + // quickly. `auto` is the default and is equivalent to `medium`. + // + // Any of "low", "medium", "high", "auto". + Eagerness string `json:"eagerness,omitzero"` + // Type of turn detection. + // + // Any of "server_vad", "semantic_vad". + Type string `json:"type,omitzero"` + paramObj +} + +func (r RealtimeAudioConfigInputTurnDetectionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeAudioConfigInputTurnDetectionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeAudioConfigInputTurnDetectionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeAudioConfigInputTurnDetectionParam]( + "eagerness", "low", "medium", "high", "auto", + ) + apijson.RegisterFieldValidator[RealtimeAudioConfigInputTurnDetectionParam]( + "type", "server_vad", "semantic_vad", + ) +} + +type RealtimeAudioConfigOutputParam struct { + // The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the + // minimum speed. 1.5 is the maximum speed. This value can only be changed in + // between model turns, not while a response is in progress. + Speed param.Opt[float64] `json:"speed,omitzero"` + // The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + // For `pcm16`, output audio is sampled at a rate of 24kHz. + // + // Any of "pcm16", "g711_ulaw", "g711_alaw". + Format string `json:"format,omitzero"` + // The voice the model uses to respond. Voice cannot be changed during the session + // once the model has responded with audio at least once. Current voice options are + // `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`, `marin`, + // and `cedar`. + Voice string `json:"voice,omitzero"` + paramObj +} + +func (r RealtimeAudioConfigOutputParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeAudioConfigOutputParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeAudioConfigOutputParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeAudioConfigOutputParam]( + "format", "pcm16", "g711_ulaw", "g711_alaw", + ) +} + +// Configuration options for the generated client secret. +type RealtimeClientSecretConfigParam struct { + // Configuration for the ephemeral token expiration. + ExpiresAfter RealtimeClientSecretConfigExpiresAfterParam `json:"expires_after,omitzero"` + paramObj +} + +func (r RealtimeClientSecretConfigParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeClientSecretConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeClientSecretConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for the ephemeral token expiration. +// +// The property Anchor is required. +type RealtimeClientSecretConfigExpiresAfterParam struct { + // The anchor point for the ephemeral token expiration. Only `created_at` is + // currently supported. + // + // Any of "created_at". + Anchor string `json:"anchor,omitzero,required"` + // The number of seconds from the anchor point to the expiration. Select a value + // between `10` and `7200`. + Seconds param.Opt[int64] `json:"seconds,omitzero"` + paramObj +} + +func (r RealtimeClientSecretConfigExpiresAfterParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeClientSecretConfigExpiresAfterParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeClientSecretConfigExpiresAfterParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeClientSecretConfigExpiresAfterParam]( + "anchor", "created_at", + ) +} + +// Realtime session object configuration. +// +// The properties Model, Type are required. +type RealtimeSessionCreateRequestParam struct { + // The Realtime model used for this session. + Model RealtimeSessionCreateRequestModel `json:"model,omitzero,required"` + // The default system instructions (i.e. system message) prepended to model calls. + // This field allows the client to guide the model on desired responses. The model + // can be instructed on response content and format, (e.g. "be extremely succinct", + // "act friendly", "here are examples of good responses") and on audio behavior + // (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + // instructions are not guaranteed to be followed by the model, but they provide + // guidance to the model on the desired behavior. + // + // Note that the server sets default instructions which will be used if this field + // is not set and are visible in the `session.created` event at the start of the + // session. + Instructions param.Opt[string] `json:"instructions,omitzero"` + // Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a + // temperature of 0.8 is highly recommended for best performance. + Temperature param.Opt[float64] `json:"temperature,omitzero"` + // Reference to a prompt template and its variables. + // [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). + Prompt responses.ResponsePromptParam `json:"prompt,omitzero"` + // Configuration options for tracing. Set to null to disable tracing. Once tracing + // is enabled for a session, the configuration cannot be modified. + // + // `auto` will create a trace for the session with default values for the workflow + // name, group id, and metadata. + Tracing RealtimeTracingConfigUnionParam `json:"tracing,omitzero"` + // Configuration for input and output audio. + Audio RealtimeAudioConfigParam `json:"audio,omitzero"` + // Configuration options for the generated client secret. + ClientSecret RealtimeClientSecretConfigParam `json:"client_secret,omitzero"` + // Additional fields to include in server outputs. + // + // - `item.input_audio_transcription.logprobs`: Include logprobs for input audio + // transcription. + // + // Any of "item.input_audio_transcription.logprobs". + Include []string `json:"include,omitzero"` + // Maximum number of output tokens for a single assistant response, inclusive of + // tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + // `inf` for the maximum available tokens for a given model. Defaults to `inf`. + MaxOutputTokens RealtimeSessionCreateRequestMaxOutputTokensUnionParam `json:"max_output_tokens,omitzero"` + // The set of modalities the model can respond with. To disable audio, set this to + // ["text"]. + // + // Any of "text", "audio". + OutputModalities []string `json:"output_modalities,omitzero"` + // How the model chooses tools. Provide one of the string modes or force a specific + // function/MCP tool. + ToolChoice RealtimeToolChoiceConfigUnionParam `json:"tool_choice,omitzero"` + // Tools available to the model. + Tools RealtimeToolsConfigParam `json:"tools,omitzero"` + // Controls how the realtime conversation is truncated prior to model inference. + // The default is `auto`. When set to `retention_ratio`, the server retains a + // fraction of the conversation tokens prior to the instructions. + Truncation RealtimeTruncationUnionParam `json:"truncation,omitzero"` + // The type of session to create. Always `realtime` for the Realtime API. + // + // This field can be elided, and will marshal its zero value as "realtime". + Type constant.Realtime `json:"type,required"` + paramObj +} + +func (r RealtimeSessionCreateRequestParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeSessionCreateRequestParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeSessionCreateRequestParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The Realtime model used for this session. +type RealtimeSessionCreateRequestModel = string + +const ( + RealtimeSessionCreateRequestModelGPT4oRealtime RealtimeSessionCreateRequestModel = "gpt-4o-realtime" + RealtimeSessionCreateRequestModelGPT4oMiniRealtime RealtimeSessionCreateRequestModel = "gpt-4o-mini-realtime" + RealtimeSessionCreateRequestModelGPT4oRealtimePreview RealtimeSessionCreateRequestModel = "gpt-4o-realtime-preview" + RealtimeSessionCreateRequestModelGPT4oRealtimePreview2024_10_01 RealtimeSessionCreateRequestModel = "gpt-4o-realtime-preview-2024-10-01" + RealtimeSessionCreateRequestModelGPT4oRealtimePreview2024_12_17 RealtimeSessionCreateRequestModel = "gpt-4o-realtime-preview-2024-12-17" + RealtimeSessionCreateRequestModelGPT4oRealtimePreview2025_06_03 RealtimeSessionCreateRequestModel = "gpt-4o-realtime-preview-2025-06-03" + RealtimeSessionCreateRequestModelGPT4oMiniRealtimePreview RealtimeSessionCreateRequestModel = "gpt-4o-mini-realtime-preview" + RealtimeSessionCreateRequestModelGPT4oMiniRealtimePreview2024_12_17 RealtimeSessionCreateRequestModel = "gpt-4o-mini-realtime-preview-2024-12-17" +) + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeSessionCreateRequestMaxOutputTokensUnionParam struct { + OfInt param.Opt[int64] `json:",omitzero,inline"` + // Construct this variant with constant.ValueOf[constant.Inf]() + OfInf constant.Inf `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeSessionCreateRequestMaxOutputTokensUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfInt, u.OfInf) +} +func (u *RealtimeSessionCreateRequestMaxOutputTokensUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeSessionCreateRequestMaxOutputTokensUnionParam) asAny() any { + if !param.IsOmitted(u.OfInt) { + return &u.OfInt.Value + } else if !param.IsOmitted(u.OfInf) { + return &u.OfInf + } + return nil +} + +func RealtimeToolChoiceConfigParamOfFunctionTool(name string) RealtimeToolChoiceConfigUnionParam { + var variant responses.ToolChoiceFunctionParam + variant.Name = name + return RealtimeToolChoiceConfigUnionParam{OfFunctionTool: &variant} +} + +func RealtimeToolChoiceConfigParamOfMcpTool(serverLabel string) RealtimeToolChoiceConfigUnionParam { + var variant responses.ToolChoiceMcpParam + variant.ServerLabel = serverLabel + return RealtimeToolChoiceConfigUnionParam{OfMcpTool: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeToolChoiceConfigUnionParam struct { + // Check if union is this variant with !param.IsOmitted(union.OfToolChoiceMode) + OfToolChoiceMode param.Opt[responses.ToolChoiceOptions] `json:",omitzero,inline"` + OfFunctionTool *responses.ToolChoiceFunctionParam `json:",omitzero,inline"` + OfMcpTool *responses.ToolChoiceMcpParam `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeToolChoiceConfigUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfToolChoiceMode, u.OfFunctionTool, u.OfMcpTool) +} +func (u *RealtimeToolChoiceConfigUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeToolChoiceConfigUnionParam) asAny() any { + if !param.IsOmitted(u.OfToolChoiceMode) { + return &u.OfToolChoiceMode + } else if !param.IsOmitted(u.OfFunctionTool) { + return u.OfFunctionTool + } else if !param.IsOmitted(u.OfMcpTool) { + return u.OfMcpTool + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolChoiceConfigUnionParam) GetServerLabel() *string { + if vt := u.OfMcpTool; vt != nil { + return &vt.ServerLabel + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolChoiceConfigUnionParam) GetName() *string { + if vt := u.OfFunctionTool; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMcpTool; vt != nil && vt.Name.Valid() { + return &vt.Name.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolChoiceConfigUnionParam) GetType() *string { + if vt := u.OfFunctionTool; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMcpTool; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +type RealtimeToolsConfigParam []RealtimeToolsConfigUnionParam + +func RealtimeToolsConfigUnionParamOfMcp(serverLabel string) RealtimeToolsConfigUnionParam { + var mcp RealtimeToolsConfigUnionMcpParam + mcp.ServerLabel = serverLabel + return RealtimeToolsConfigUnionParam{OfMcp: &mcp} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeToolsConfigUnionParam struct { + OfFunction *RealtimeToolsConfigUnionFunctionParam `json:",omitzero,inline"` + OfMcp *RealtimeToolsConfigUnionMcpParam `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeToolsConfigUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfFunction, u.OfMcp) +} +func (u *RealtimeToolsConfigUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeToolsConfigUnionParam) asAny() any { + if !param.IsOmitted(u.OfFunction) { + return u.OfFunction + } else if !param.IsOmitted(u.OfMcp) { + return u.OfMcp + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetDescription() *string { + if vt := u.OfFunction; vt != nil && vt.Description.Valid() { + return &vt.Description.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetName() *string { + if vt := u.OfFunction; vt != nil && vt.Name.Valid() { + return &vt.Name.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetParameters() *any { + if vt := u.OfFunction; vt != nil { + return &vt.Parameters + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetServerLabel() *string { + if vt := u.OfMcp; vt != nil { + return &vt.ServerLabel + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetAllowedTools() *RealtimeToolsConfigUnionMcpAllowedToolsParam { + if vt := u.OfMcp; vt != nil { + return &vt.AllowedTools + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetAuthorization() *string { + if vt := u.OfMcp; vt != nil && vt.Authorization.Valid() { + return &vt.Authorization.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetConnectorID() *string { + if vt := u.OfMcp; vt != nil { + return &vt.ConnectorID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetHeaders() map[string]string { + if vt := u.OfMcp; vt != nil { + return vt.Headers + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetRequireApproval() *RealtimeToolsConfigUnionMcpRequireApprovalParam { + if vt := u.OfMcp; vt != nil { + return &vt.RequireApproval + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetServerDescription() *string { + if vt := u.OfMcp; vt != nil && vt.ServerDescription.Valid() { + return &vt.ServerDescription.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetServerURL() *string { + if vt := u.OfMcp; vt != nil && vt.ServerURL.Valid() { + return &vt.ServerURL.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u RealtimeToolsConfigUnionParam) GetType() *string { + if vt := u.OfFunction; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMcp; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[RealtimeToolsConfigUnionParam]( + "type", + apijson.Discriminator[RealtimeToolsConfigUnionFunctionParam]("function"), + apijson.Discriminator[RealtimeToolsConfigUnionMcpParam]("mcp"), + ) +} + +type RealtimeToolsConfigUnionFunctionParam struct { + // The description of the function, including guidance on when and how to call it, + // and guidance about what to tell the user when calling (if anything). + Description param.Opt[string] `json:"description,omitzero"` + // The name of the function. + Name param.Opt[string] `json:"name,omitzero"` + // Parameters of the function in JSON Schema. + Parameters any `json:"parameters,omitzero"` + // The type of the tool, i.e. `function`. + // + // Any of "function". + Type string `json:"type,omitzero"` + paramObj +} + +func (r RealtimeToolsConfigUnionFunctionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeToolsConfigUnionFunctionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeToolsConfigUnionFunctionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeToolsConfigUnionFunctionParam]( + "type", "function", + ) +} + +// Give the model access to additional tools via remote Model Context Protocol +// (MCP) servers. +// [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). +// +// The properties ServerLabel, Type are required. +type RealtimeToolsConfigUnionMcpParam struct { + // A label for this MCP server, used to identify it in tool calls. + ServerLabel string `json:"server_label,required"` + // An OAuth access token that can be used with a remote MCP server, either with a + // custom MCP server URL or a service connector. Your application must handle the + // OAuth authorization flow and provide the token here. + Authorization param.Opt[string] `json:"authorization,omitzero"` + // Optional description of the MCP server, used to provide more context. + ServerDescription param.Opt[string] `json:"server_description,omitzero"` + // The URL for the MCP server. One of `server_url` or `connector_id` must be + // provided. + ServerURL param.Opt[string] `json:"server_url,omitzero"` + // List of allowed tool names or a filter object. + AllowedTools RealtimeToolsConfigUnionMcpAllowedToolsParam `json:"allowed_tools,omitzero"` + // Optional HTTP headers to send to the MCP server. Use for authentication or other + // purposes. + Headers map[string]string `json:"headers,omitzero"` + // Specify which of the MCP server's tools require approval. + RequireApproval RealtimeToolsConfigUnionMcpRequireApprovalParam `json:"require_approval,omitzero"` + // Identifier for service connectors, like those available in ChatGPT. One of + // `server_url` or `connector_id` must be provided. Learn more about service + // connectors + // [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors). + // + // Currently supported `connector_id` values are: + // + // - Dropbox: `connector_dropbox` + // - Gmail: `connector_gmail` + // - Google Calendar: `connector_googlecalendar` + // - Google Drive: `connector_googledrive` + // - Microsoft Teams: `connector_microsoftteams` + // - Outlook Calendar: `connector_outlookcalendar` + // - Outlook Email: `connector_outlookemail` + // - SharePoint: `connector_sharepoint` + // + // Any of "connector_dropbox", "connector_gmail", "connector_googlecalendar", + // "connector_googledrive", "connector_microsoftteams", + // "connector_outlookcalendar", "connector_outlookemail", "connector_sharepoint". + ConnectorID string `json:"connector_id,omitzero"` + // The type of the MCP tool. Always `mcp`. + // + // This field can be elided, and will marshal its zero value as "mcp". + Type constant.Mcp `json:"type,required"` + paramObj +} + +func (r RealtimeToolsConfigUnionMcpParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeToolsConfigUnionMcpParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeToolsConfigUnionMcpParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeToolsConfigUnionMcpParam]( + "connector_id", "connector_dropbox", "connector_gmail", "connector_googlecalendar", "connector_googledrive", "connector_microsoftteams", "connector_outlookcalendar", "connector_outlookemail", "connector_sharepoint", + ) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeToolsConfigUnionMcpAllowedToolsParam struct { + OfMcpAllowedTools []string `json:",omitzero,inline"` + OfMcpToolFilter *RealtimeToolsConfigUnionMcpAllowedToolsMcpToolFilterParam `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeToolsConfigUnionMcpAllowedToolsParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfMcpAllowedTools, u.OfMcpToolFilter) +} +func (u *RealtimeToolsConfigUnionMcpAllowedToolsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeToolsConfigUnionMcpAllowedToolsParam) asAny() any { + if !param.IsOmitted(u.OfMcpAllowedTools) { + return &u.OfMcpAllowedTools + } else if !param.IsOmitted(u.OfMcpToolFilter) { + return u.OfMcpToolFilter + } + return nil +} + +// A filter object to specify which tools are allowed. +type RealtimeToolsConfigUnionMcpAllowedToolsMcpToolFilterParam struct { + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly param.Opt[bool] `json:"read_only,omitzero"` + // List of allowed tool names. + ToolNames []string `json:"tool_names,omitzero"` + paramObj +} + +func (r RealtimeToolsConfigUnionMcpAllowedToolsMcpToolFilterParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeToolsConfigUnionMcpAllowedToolsMcpToolFilterParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeToolsConfigUnionMcpAllowedToolsMcpToolFilterParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeToolsConfigUnionMcpRequireApprovalParam struct { + OfMcpToolApprovalFilter *RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterParam `json:",omitzero,inline"` + // Check if union is this variant with + // !param.IsOmitted(union.OfMcpToolApprovalSetting) + OfMcpToolApprovalSetting param.Opt[string] `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeToolsConfigUnionMcpRequireApprovalParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfMcpToolApprovalFilter, u.OfMcpToolApprovalSetting) +} +func (u *RealtimeToolsConfigUnionMcpRequireApprovalParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeToolsConfigUnionMcpRequireApprovalParam) asAny() any { + if !param.IsOmitted(u.OfMcpToolApprovalFilter) { + return u.OfMcpToolApprovalFilter + } else if !param.IsOmitted(u.OfMcpToolApprovalSetting) { + return &u.OfMcpToolApprovalSetting + } + return nil +} + +// Specify which of the MCP server's tools require approval. Can be `always`, +// `never`, or a filter object associated with tools that require approval. +type RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterParam struct { + // A filter object to specify which tools are allowed. + Always RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterAlwaysParam `json:"always,omitzero"` + // A filter object to specify which tools are allowed. + Never RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterNeverParam `json:"never,omitzero"` + paramObj +} + +func (r RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A filter object to specify which tools are allowed. +type RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterAlwaysParam struct { + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly param.Opt[bool] `json:"read_only,omitzero"` + // List of allowed tool names. + ToolNames []string `json:"tool_names,omitzero"` + paramObj +} + +func (r RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterAlwaysParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterAlwaysParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterAlwaysParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A filter object to specify which tools are allowed. +type RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterNeverParam struct { + // Indicates whether or not a tool modifies data or is read-only. If an MCP server + // is + // [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + // it will match this filter. + ReadOnly param.Opt[bool] `json:"read_only,omitzero"` + // List of allowed tool names. + ToolNames []string `json:"tool_names,omitzero"` + paramObj +} + +func (r RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterNeverParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterNeverParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalFilterNeverParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Specify a single approval policy for all tools. One of `always` or `never`. When +// set to `always`, all tools will require approval. When set to `never`, all tools +// will not require approval. +type RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalSetting string + +const ( + RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalSettingAlways RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalSetting = "always" + RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalSettingNever RealtimeToolsConfigUnionMcpRequireApprovalMcpToolApprovalSetting = "never" +) + +func RealtimeTracingConfigParamOfAuto() RealtimeTracingConfigUnionParam { + return RealtimeTracingConfigUnionParam{OfAuto: constant.ValueOf[constant.Auto]()} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeTracingConfigUnionParam struct { + // Construct this variant with constant.ValueOf[constant.Auto]() + OfAuto constant.Auto `json:",omitzero,inline"` + OfTracingConfiguration *RealtimeTracingConfigTracingConfigurationParam `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeTracingConfigUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAuto, u.OfTracingConfiguration) +} +func (u *RealtimeTracingConfigUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeTracingConfigUnionParam) asAny() any { + if !param.IsOmitted(u.OfAuto) { + return &u.OfAuto + } else if !param.IsOmitted(u.OfTracingConfiguration) { + return u.OfTracingConfiguration + } + return nil +} + +// Granular configuration for tracing. +type RealtimeTracingConfigTracingConfigurationParam struct { + // The group id to attach to this trace to enable filtering and grouping in the + // traces dashboard. + GroupID param.Opt[string] `json:"group_id,omitzero"` + // The name of the workflow to attach to this trace. This is used to name the trace + // in the traces dashboard. + WorkflowName param.Opt[string] `json:"workflow_name,omitzero"` + // The arbitrary metadata to attach to this trace to enable filtering in the traces + // dashboard. + Metadata any `json:"metadata,omitzero"` + paramObj +} + +func (r RealtimeTracingConfigTracingConfigurationParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeTracingConfigTracingConfigurationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeTracingConfigTracingConfigurationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Realtime transcription session object configuration. +// +// The properties Model, Type are required. +type RealtimeTranscriptionSessionCreateRequestParam struct { + // ID of the model to use. The options are `gpt-4o-transcribe`, + // `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source + // Whisper V2 model). + Model RealtimeTranscriptionSessionCreateRequestModel `json:"model,omitzero,required"` + // The set of items to include in the transcription. Current available items are: + // + // - `item.input_audio_transcription.logprobs` + // + // Any of "item.input_audio_transcription.logprobs". + Include []string `json:"include,omitzero"` + // The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + // `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + // (mono), and little-endian byte order. + // + // Any of "pcm16", "g711_ulaw", "g711_alaw". + InputAudioFormat RealtimeTranscriptionSessionCreateRequestInputAudioFormat `json:"input_audio_format,omitzero"` + // Configuration for input audio noise reduction. This can be set to `null` to turn + // off. Noise reduction filters audio added to the input audio buffer before it is + // sent to VAD and the model. Filtering the audio can improve VAD and turn + // detection accuracy (reducing false positives) and model performance by improving + // perception of the input audio. + InputAudioNoiseReduction RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam `json:"input_audio_noise_reduction,omitzero"` + // Configuration for input audio transcription. The client can optionally set the + // language and prompt for transcription, these offer additional guidance to the + // transcription service. + InputAudioTranscription RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam `json:"input_audio_transcription,omitzero"` + // Configuration for turn detection. Can be set to `null` to turn off. Server VAD + // means that the model will detect the start and end of speech based on audio + // volume and respond at the end of user speech. + TurnDetection RealtimeTranscriptionSessionCreateRequestTurnDetectionParam `json:"turn_detection,omitzero"` + // The type of session to create. Always `transcription` for transcription + // sessions. + // + // This field can be elided, and will marshal its zero value as "transcription". + Type constant.Transcription `json:"type,required"` + paramObj +} + +func (r RealtimeTranscriptionSessionCreateRequestParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeTranscriptionSessionCreateRequestParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeTranscriptionSessionCreateRequestParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ID of the model to use. The options are `gpt-4o-transcribe`, +// `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source +// Whisper V2 model). +type RealtimeTranscriptionSessionCreateRequestModel = string + +const ( + RealtimeTranscriptionSessionCreateRequestModelWhisper1 RealtimeTranscriptionSessionCreateRequestModel = "whisper-1" + RealtimeTranscriptionSessionCreateRequestModelGPT4oTranscribe RealtimeTranscriptionSessionCreateRequestModel = "gpt-4o-transcribe" + RealtimeTranscriptionSessionCreateRequestModelGPT4oMiniTranscribe RealtimeTranscriptionSessionCreateRequestModel = "gpt-4o-mini-transcribe" +) + +// The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For +// `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel +// (mono), and little-endian byte order. +type RealtimeTranscriptionSessionCreateRequestInputAudioFormat string + +const ( + RealtimeTranscriptionSessionCreateRequestInputAudioFormatPcm16 RealtimeTranscriptionSessionCreateRequestInputAudioFormat = "pcm16" + RealtimeTranscriptionSessionCreateRequestInputAudioFormatG711Ulaw RealtimeTranscriptionSessionCreateRequestInputAudioFormat = "g711_ulaw" + RealtimeTranscriptionSessionCreateRequestInputAudioFormatG711Alaw RealtimeTranscriptionSessionCreateRequestInputAudioFormat = "g711_alaw" +) + +// Configuration for input audio noise reduction. This can be set to `null` to turn +// off. Noise reduction filters audio added to the input audio buffer before it is +// sent to VAD and the model. Filtering the audio can improve VAD and turn +// detection accuracy (reducing false positives) and model performance by improving +// perception of the input audio. +type RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam struct { + // Type of noise reduction. `near_field` is for close-talking microphones such as + // headphones, `far_field` is for far-field microphones such as laptop or + // conference room microphones. + // + // Any of "near_field", "far_field". + Type string `json:"type,omitzero"` + paramObj +} + +func (r RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeTranscriptionSessionCreateRequestInputAudioNoiseReductionParam]( + "type", "near_field", "far_field", + ) +} + +// Configuration for input audio transcription. The client can optionally set the +// language and prompt for transcription, these offer additional guidance to the +// transcription service. +type RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam struct { + // The language of the input audio. Supplying the input language in + // [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + // format will improve accuracy and latency. + Language param.Opt[string] `json:"language,omitzero"` + // An optional text to guide the model's style or continue a previous audio + // segment. For `whisper-1`, the + // [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + // For `gpt-4o-transcribe` models, the prompt is a free text string, for example + // "expect words related to technology". + Prompt param.Opt[string] `json:"prompt,omitzero"` + // The model to use for transcription, current options are `gpt-4o-transcribe`, + // `gpt-4o-mini-transcribe`, and `whisper-1`. + // + // Any of "gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1". + Model string `json:"model,omitzero"` + paramObj +} + +func (r RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeTranscriptionSessionCreateRequestInputAudioTranscriptionParam]( + "model", "gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1", + ) +} + +// Configuration for turn detection. Can be set to `null` to turn off. Server VAD +// means that the model will detect the start and end of speech based on audio +// volume and respond at the end of user speech. +type RealtimeTranscriptionSessionCreateRequestTurnDetectionParam struct { + // Amount of audio to include before the VAD detected speech (in milliseconds). + // Defaults to 300ms. + PrefixPaddingMs param.Opt[int64] `json:"prefix_padding_ms,omitzero"` + // Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + // With shorter values the model will respond more quickly, but may jump in on + // short pauses from the user. + SilenceDurationMs param.Opt[int64] `json:"silence_duration_ms,omitzero"` + // Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + // threshold will require louder audio to activate the model, and thus might + // perform better in noisy environments. + Threshold param.Opt[float64] `json:"threshold,omitzero"` + // Type of turn detection. Only `server_vad` is currently supported for + // transcription sessions. + // + // Any of "server_vad". + Type string `json:"type,omitzero"` + paramObj +} + +func (r RealtimeTranscriptionSessionCreateRequestTurnDetectionParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeTranscriptionSessionCreateRequestTurnDetectionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeTranscriptionSessionCreateRequestTurnDetectionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func init() { + apijson.RegisterFieldValidator[RealtimeTranscriptionSessionCreateRequestTurnDetectionParam]( + "type", "server_vad", + ) +} + +func RealtimeTruncationParamOfRetentionRatioTruncation(retentionRatio float64) RealtimeTruncationUnionParam { + var variant RealtimeTruncationRetentionRatioTruncationParam + variant.RetentionRatio = retentionRatio + return RealtimeTruncationUnionParam{OfRetentionRatioTruncation: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type RealtimeTruncationUnionParam struct { + // Check if union is this variant with + // !param.IsOmitted(union.OfRealtimeTruncationStrategy) + OfRealtimeTruncationStrategy param.Opt[string] `json:",omitzero,inline"` + OfRetentionRatioTruncation *RealtimeTruncationRetentionRatioTruncationParam `json:",omitzero,inline"` + paramUnion +} + +func (u RealtimeTruncationUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRealtimeTruncationStrategy, u.OfRetentionRatioTruncation) +} +func (u *RealtimeTruncationUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *RealtimeTruncationUnionParam) asAny() any { + if !param.IsOmitted(u.OfRealtimeTruncationStrategy) { + return &u.OfRealtimeTruncationStrategy + } else if !param.IsOmitted(u.OfRetentionRatioTruncation) { + return u.OfRetentionRatioTruncation + } + return nil +} + +// The truncation strategy to use for the session. +type RealtimeTruncationRealtimeTruncationStrategy string + +const ( + RealtimeTruncationRealtimeTruncationStrategyAuto RealtimeTruncationRealtimeTruncationStrategy = "auto" + RealtimeTruncationRealtimeTruncationStrategyDisabled RealtimeTruncationRealtimeTruncationStrategy = "disabled" +) + +// Retain a fraction of the conversation tokens. +// +// The properties RetentionRatio, Type are required. +type RealtimeTruncationRetentionRatioTruncationParam struct { + // Fraction of pre-instruction conversation tokens to retain (0.0 - 1.0). + RetentionRatio float64 `json:"retention_ratio,required"` + // Optional cap on tokens allowed after the instructions. + PostInstructionsTokenLimit param.Opt[int64] `json:"post_instructions_token_limit,omitzero"` + // Use retention ratio truncation. + // + // This field can be elided, and will marshal its zero value as "retention_ratio". + Type constant.RetentionRatio `json:"type,required"` + paramObj +} + +func (r RealtimeTruncationRetentionRatioTruncationParam) MarshalJSON() (data []byte, err error) { + type shadow RealtimeTruncationRetentionRatioTruncationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RealtimeTruncationRetentionRatioTruncationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} diff --git a/responses/response.go b/responses/response.go index e97edb38..421062c4 100644 --- a/responses/response.go +++ b/responses/response.go @@ -782,7 +782,7 @@ type Response struct { // An array of tools the model may call while generating a response. You can // specify which tool to use by setting the `tool_choice` parameter. // - // The two categories of tools you can provide the model are: + // We support the following categories of tools: // // - **Built-in tools**: Tools that are provided by OpenAI that extend the model's // capabilities, like @@ -790,6 +790,9 @@ type Response struct { // [file search](https://platform.openai.com/docs/guides/tools-file-search). // Learn more about // [built-in tools](https://platform.openai.com/docs/guides/tools). + // - **MCP Tools**: Integrations with third-party systems via custom MCP servers or + // predefined connectors such as Google Drive and Notion. Learn more about + // [MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp). // - **Function calls (custom tools)**: Functions that are defined by you, enabling // the model to call your own code with strongly typed arguments and outputs. // Learn more about @@ -11685,9 +11688,9 @@ func (r *ResponseWebSearchCallSearchingEvent) UnmarshalJSON(data []byte) error { } // ToolUnion contains all possible properties and values from [FunctionTool], -// [FileSearchTool], [ComputerTool], [ToolWebSearch], [ToolMcp], +// [FileSearchTool], [ComputerTool], [WebSearchTool], [ToolMcp], // [ToolCodeInterpreter], [ToolImageGeneration], [ToolLocalShell], [CustomTool], -// [WebSearchTool]. +// [WebSearchPreviewTool]. // // Use the [ToolUnion.AsAny] method to switch on the variant. // @@ -11704,7 +11707,7 @@ type ToolUnion struct { Description string `json:"description"` // This field is from variant [FileSearchTool]. VectorStoreIDs []string `json:"vector_store_ids"` - // This field is a union of [FileSearchToolFiltersUnion], [ToolWebSearchFilters] + // This field is a union of [FileSearchToolFiltersUnion], [WebSearchToolFilters] Filters ToolUnionFilters `json:"filters"` // This field is from variant [FileSearchTool]. MaxNumResults int64 `json:"max_num_results"` @@ -11717,8 +11720,8 @@ type ToolUnion struct { // This field is from variant [ComputerTool]. Environment ComputerToolEnvironment `json:"environment"` SearchContextSize string `json:"search_context_size"` - // This field is a union of [ToolWebSearchUserLocation], - // [WebSearchToolUserLocation] + // This field is a union of [WebSearchToolUserLocation], + // [WebSearchPreviewToolUserLocation] UserLocation ToolUnionUserLocation `json:"user_location"` // This field is from variant [ToolMcp]. ServerLabel string `json:"server_label"` @@ -11814,7 +11817,7 @@ func (u ToolUnion) AsComputerUsePreview() (v ComputerTool) { return } -func (u ToolUnion) AsWebSearch() (v ToolWebSearch) { +func (u ToolUnion) AsWebSearch() (v WebSearchTool) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } @@ -11844,7 +11847,7 @@ func (u ToolUnion) AsCustom() (v CustomTool) { return } -func (u ToolUnion) AsWebSearchPreview() (v WebSearchTool) { +func (u ToolUnion) AsWebSearchPreview() (v WebSearchPreviewTool) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } @@ -11868,7 +11871,7 @@ type ToolUnionFilters struct { Value shared.ComparisonFilterValueUnion `json:"value"` // This field is from variant [FileSearchToolFiltersUnion]. Filters []shared.ComparisonFilter `json:"filters"` - // This field is from variant [ToolWebSearchFilters]. + // This field is from variant [WebSearchToolFilters]. AllowedDomains []string `json:"allowed_domains"` JSON struct { Key respjson.Field @@ -11918,94 +11921,6 @@ func (r ToolUnion) ToParam() ToolUnionParam { return param.Override[ToolUnionParam](json.RawMessage(r.RawJSON())) } -// Search the Internet for sources related to the prompt. Learn more about the -// [web search tool](https://platform.openai.com/docs/guides/tools-web-search). -type ToolWebSearch struct { - // The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. - // - // Any of "web_search", "web_search_2025_08_26". - Type string `json:"type,required"` - // Filters for the search. - Filters ToolWebSearchFilters `json:"filters,nullable"` - // High level guidance for the amount of context window space to use for the - // search. One of `low`, `medium`, or `high`. `medium` is the default. - // - // Any of "low", "medium", "high". - SearchContextSize string `json:"search_context_size"` - // The approximate location of the user. - UserLocation ToolWebSearchUserLocation `json:"user_location,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - Filters respjson.Field - SearchContextSize respjson.Field - UserLocation respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ToolWebSearch) RawJSON() string { return r.JSON.raw } -func (r *ToolWebSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Filters for the search. -type ToolWebSearchFilters struct { - // Allowed domains for the search. If not provided, all domains are allowed. - // Subdomains of the provided domains are allowed as well. - // - // Example: `["pubmed.ncbi.nlm.nih.gov"]` - AllowedDomains []string `json:"allowed_domains,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - AllowedDomains respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ToolWebSearchFilters) RawJSON() string { return r.JSON.raw } -func (r *ToolWebSearchFilters) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The approximate location of the user. -type ToolWebSearchUserLocation struct { - // Free text input for the city of the user, e.g. `San Francisco`. - City string `json:"city,nullable"` - // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of - // the user, e.g. `US`. - Country string `json:"country,nullable"` - // Free text input for the region of the user, e.g. `California`. - Region string `json:"region,nullable"` - // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the - // user, e.g. `America/Los_Angeles`. - Timezone string `json:"timezone,nullable"` - // The type of location approximation. Always `approximate`. - // - // Any of "approximate". - Type string `json:"type"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - City respjson.Field - Country respjson.Field - Region respjson.Field - Timezone respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ToolWebSearchUserLocation) RawJSON() string { return r.JSON.raw } -func (r *ToolWebSearchUserLocation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - // Give the model access to additional tools via remote Model Context Protocol // (MCP) servers. // [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). @@ -12471,8 +12386,8 @@ func ToolParamOfComputerUsePreview(displayHeight int64, displayWidth int64, envi return ToolUnionParam{OfComputerUsePreview: &computerUsePreview} } -func ToolParamOfWebSearch(type_ string) ToolUnionParam { - var variant ToolWebSearchParam +func ToolParamOfWebSearch(type_ WebSearchToolType) ToolUnionParam { + var variant WebSearchToolParam variant.Type = type_ return ToolUnionParam{OfWebSearch: &variant} } @@ -12502,8 +12417,8 @@ func ToolParamOfCustom(name string) ToolUnionParam { return ToolUnionParam{OfCustom: &custom} } -func ToolParamOfWebSearchPreview(type_ WebSearchToolType) ToolUnionParam { - var variant WebSearchToolParam +func ToolParamOfWebSearchPreview(type_ WebSearchPreviewToolType) ToolUnionParam { + var variant WebSearchPreviewToolParam variant.Type = type_ return ToolUnionParam{OfWebSearchPreview: &variant} } @@ -12512,16 +12427,16 @@ func ToolParamOfWebSearchPreview(type_ WebSearchToolType) ToolUnionParam { // // Use [param.IsOmitted] to confirm if a field is set. type ToolUnionParam struct { - OfFunction *FunctionToolParam `json:",omitzero,inline"` - OfFileSearch *FileSearchToolParam `json:",omitzero,inline"` - OfComputerUsePreview *ComputerToolParam `json:",omitzero,inline"` - OfWebSearch *ToolWebSearchParam `json:",omitzero,inline"` - OfMcp *ToolMcpParam `json:",omitzero,inline"` - OfCodeInterpreter *ToolCodeInterpreterParam `json:",omitzero,inline"` - OfImageGeneration *ToolImageGenerationParam `json:",omitzero,inline"` - OfLocalShell *ToolLocalShellParam `json:",omitzero,inline"` - OfCustom *CustomToolParam `json:",omitzero,inline"` - OfWebSearchPreview *WebSearchToolParam `json:",omitzero,inline"` + OfFunction *FunctionToolParam `json:",omitzero,inline"` + OfFileSearch *FileSearchToolParam `json:",omitzero,inline"` + OfComputerUsePreview *ComputerToolParam `json:",omitzero,inline"` + OfWebSearch *WebSearchToolParam `json:",omitzero,inline"` + OfMcp *ToolMcpParam `json:",omitzero,inline"` + OfCodeInterpreter *ToolCodeInterpreterParam `json:",omitzero,inline"` + OfImageGeneration *ToolImageGenerationParam `json:",omitzero,inline"` + OfLocalShell *ToolLocalShellParam `json:",omitzero,inline"` + OfCustom *CustomToolParam `json:",omitzero,inline"` + OfWebSearchPreview *WebSearchPreviewToolParam `json:",omitzero,inline"` paramUnion } @@ -12859,7 +12774,7 @@ func (u ToolUnionParam) GetFilters() (res toolUnionParamFilters) { } // Can have the runtime types [*shared.ComparisonFilterParam], -// [*shared.CompoundFilterParam], [*ToolWebSearchFiltersParam] +// [*shared.CompoundFilterParam], [*WebSearchToolFiltersParam] type toolUnionParamFilters struct{ any } // Use the following switch statement to get the type of the union: @@ -12867,7 +12782,7 @@ type toolUnionParamFilters struct{ any } // switch u.AsAny().(type) { // case *shared.ComparisonFilterParam: // case *shared.CompoundFilterParam: -// case *responses.ToolWebSearchFiltersParam: +// case *responses.WebSearchToolFiltersParam: // default: // fmt.Errorf("not present") // } @@ -12903,7 +12818,7 @@ func (u toolUnionParamFilters) GetFilters() []shared.ComparisonFilterParam { // Returns a pointer to the underlying variant's property, if present. func (u toolUnionParamFilters) GetAllowedDomains() []string { switch vt := u.any.(type) { - case *ToolWebSearchFiltersParam: + case *WebSearchToolFiltersParam: return vt.AllowedDomains } return nil @@ -12930,15 +12845,15 @@ func (u ToolUnionParam) GetUserLocation() (res toolUnionParamUserLocation) { return } -// Can have the runtime types [*ToolWebSearchUserLocationParam], -// [*WebSearchToolUserLocationParam] +// Can have the runtime types [*WebSearchToolUserLocationParam], +// [*WebSearchPreviewToolUserLocationParam] type toolUnionParamUserLocation struct{ any } // Use the following switch statement to get the type of the union: // // switch u.AsAny().(type) { -// case *responses.ToolWebSearchUserLocationParam: // case *responses.WebSearchToolUserLocationParam: +// case *responses.WebSearchPreviewToolUserLocationParam: // default: // fmt.Errorf("not present") // } @@ -12947,10 +12862,10 @@ func (u toolUnionParamUserLocation) AsAny() any { return u.any } // Returns a pointer to the underlying variant's property, if present. func (u toolUnionParamUserLocation) GetCity() *string { switch vt := u.any.(type) { - case *ToolWebSearchUserLocationParam: - return paramutil.AddrIfPresent(vt.City) case *WebSearchToolUserLocationParam: return paramutil.AddrIfPresent(vt.City) + case *WebSearchPreviewToolUserLocationParam: + return paramutil.AddrIfPresent(vt.City) } return nil } @@ -12958,10 +12873,10 @@ func (u toolUnionParamUserLocation) GetCity() *string { // Returns a pointer to the underlying variant's property, if present. func (u toolUnionParamUserLocation) GetCountry() *string { switch vt := u.any.(type) { - case *ToolWebSearchUserLocationParam: - return paramutil.AddrIfPresent(vt.Country) case *WebSearchToolUserLocationParam: return paramutil.AddrIfPresent(vt.Country) + case *WebSearchPreviewToolUserLocationParam: + return paramutil.AddrIfPresent(vt.Country) } return nil } @@ -12969,10 +12884,10 @@ func (u toolUnionParamUserLocation) GetCountry() *string { // Returns a pointer to the underlying variant's property, if present. func (u toolUnionParamUserLocation) GetRegion() *string { switch vt := u.any.(type) { - case *ToolWebSearchUserLocationParam: - return paramutil.AddrIfPresent(vt.Region) case *WebSearchToolUserLocationParam: return paramutil.AddrIfPresent(vt.Region) + case *WebSearchPreviewToolUserLocationParam: + return paramutil.AddrIfPresent(vt.Region) } return nil } @@ -12980,10 +12895,10 @@ func (u toolUnionParamUserLocation) GetRegion() *string { // Returns a pointer to the underlying variant's property, if present. func (u toolUnionParamUserLocation) GetTimezone() *string { switch vt := u.any.(type) { - case *ToolWebSearchUserLocationParam: - return paramutil.AddrIfPresent(vt.Timezone) case *WebSearchToolUserLocationParam: return paramutil.AddrIfPresent(vt.Timezone) + case *WebSearchPreviewToolUserLocationParam: + return paramutil.AddrIfPresent(vt.Timezone) } return nil } @@ -12991,10 +12906,10 @@ func (u toolUnionParamUserLocation) GetTimezone() *string { // Returns a pointer to the underlying variant's property, if present. func (u toolUnionParamUserLocation) GetType() *string { switch vt := u.any.(type) { - case *ToolWebSearchUserLocationParam: - return (*string)(&vt.Type) case *WebSearchToolUserLocationParam: return (*string)(&vt.Type) + case *WebSearchPreviewToolUserLocationParam: + return (*string)(&vt.Type) } return nil } @@ -13005,104 +12920,15 @@ func init() { apijson.Discriminator[FunctionToolParam]("function"), apijson.Discriminator[FileSearchToolParam]("file_search"), apijson.Discriminator[ComputerToolParam]("computer_use_preview"), - apijson.Discriminator[ToolWebSearchParam]("web_search"), - apijson.Discriminator[ToolWebSearchParam]("web_search_2025_08_26"), + apijson.Discriminator[WebSearchToolParam]("web_search"), + apijson.Discriminator[WebSearchToolParam]("web_search_2025_08_26"), apijson.Discriminator[ToolMcpParam]("mcp"), apijson.Discriminator[ToolCodeInterpreterParam]("code_interpreter"), apijson.Discriminator[ToolImageGenerationParam]("image_generation"), apijson.Discriminator[ToolLocalShellParam]("local_shell"), apijson.Discriminator[CustomToolParam]("custom"), - apijson.Discriminator[WebSearchToolParam]("web_search_preview"), - apijson.Discriminator[WebSearchToolParam]("web_search_preview_2025_03_11"), - ) -} - -// Search the Internet for sources related to the prompt. Learn more about the -// [web search tool](https://platform.openai.com/docs/guides/tools-web-search). -// -// The property Type is required. -type ToolWebSearchParam struct { - // The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. - // - // Any of "web_search", "web_search_2025_08_26". - Type string `json:"type,omitzero,required"` - // Filters for the search. - Filters ToolWebSearchFiltersParam `json:"filters,omitzero"` - // The approximate location of the user. - UserLocation ToolWebSearchUserLocationParam `json:"user_location,omitzero"` - // High level guidance for the amount of context window space to use for the - // search. One of `low`, `medium`, or `high`. `medium` is the default. - // - // Any of "low", "medium", "high". - SearchContextSize string `json:"search_context_size,omitzero"` - paramObj -} - -func (r ToolWebSearchParam) MarshalJSON() (data []byte, err error) { - type shadow ToolWebSearchParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolWebSearchParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ToolWebSearchParam]( - "type", "web_search", "web_search_2025_08_26", - ) - apijson.RegisterFieldValidator[ToolWebSearchParam]( - "search_context_size", "low", "medium", "high", - ) -} - -// Filters for the search. -type ToolWebSearchFiltersParam struct { - // Allowed domains for the search. If not provided, all domains are allowed. - // Subdomains of the provided domains are allowed as well. - // - // Example: `["pubmed.ncbi.nlm.nih.gov"]` - AllowedDomains []string `json:"allowed_domains,omitzero"` - paramObj -} - -func (r ToolWebSearchFiltersParam) MarshalJSON() (data []byte, err error) { - type shadow ToolWebSearchFiltersParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolWebSearchFiltersParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The approximate location of the user. -type ToolWebSearchUserLocationParam struct { - // Free text input for the city of the user, e.g. `San Francisco`. - City param.Opt[string] `json:"city,omitzero"` - // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of - // the user, e.g. `US`. - Country param.Opt[string] `json:"country,omitzero"` - // Free text input for the region of the user, e.g. `California`. - Region param.Opt[string] `json:"region,omitzero"` - // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the - // user, e.g. `America/Los_Angeles`. - Timezone param.Opt[string] `json:"timezone,omitzero"` - // The type of location approximation. Always `approximate`. - // - // Any of "approximate". - Type string `json:"type,omitzero"` - paramObj -} - -func (r ToolWebSearchUserLocationParam) MarshalJSON() (data []byte, err error) { - type shadow ToolWebSearchUserLocationParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolWebSearchUserLocationParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ToolWebSearchUserLocationParam]( - "type", "approximate", + apijson.Discriminator[WebSearchPreviewToolParam]("web_search_preview"), + apijson.Discriminator[WebSearchPreviewToolParam]("web_search_preview_2025_03_11"), ) } @@ -13873,22 +13699,173 @@ func (r *ToolChoiceTypesParam) UnmarshalJSON(data []byte) error { // This tool searches the web for relevant results to use in a response. Learn more // about the // [web search tool](https://platform.openai.com/docs/guides/tools-web-search). -type WebSearchTool struct { +type WebSearchPreviewTool struct { + // The type of the web search tool. One of `web_search_preview` or + // `web_search_preview_2025_03_11`. + // + // Any of "web_search_preview", "web_search_preview_2025_03_11". + Type WebSearchPreviewToolType `json:"type,required"` + // High level guidance for the amount of context window space to use for the + // search. One of `low`, `medium`, or `high`. `medium` is the default. + // + // Any of "low", "medium", "high". + SearchContextSize WebSearchPreviewToolSearchContextSize `json:"search_context_size"` + // The user's location. + UserLocation WebSearchPreviewToolUserLocation `json:"user_location,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + SearchContextSize respjson.Field + UserLocation respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r WebSearchPreviewTool) RawJSON() string { return r.JSON.raw } +func (r *WebSearchPreviewTool) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this WebSearchPreviewTool to a WebSearchPreviewToolParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// WebSearchPreviewToolParam.Overrides() +func (r WebSearchPreviewTool) ToParam() WebSearchPreviewToolParam { + return param.Override[WebSearchPreviewToolParam](json.RawMessage(r.RawJSON())) +} + +// The type of the web search tool. One of `web_search_preview` or +// `web_search_preview_2025_03_11`. +type WebSearchPreviewToolType string + +const ( + WebSearchPreviewToolTypeWebSearchPreview WebSearchPreviewToolType = "web_search_preview" + WebSearchPreviewToolTypeWebSearchPreview2025_03_11 WebSearchPreviewToolType = "web_search_preview_2025_03_11" +) + +// High level guidance for the amount of context window space to use for the +// search. One of `low`, `medium`, or `high`. `medium` is the default. +type WebSearchPreviewToolSearchContextSize string + +const ( + WebSearchPreviewToolSearchContextSizeLow WebSearchPreviewToolSearchContextSize = "low" + WebSearchPreviewToolSearchContextSizeMedium WebSearchPreviewToolSearchContextSize = "medium" + WebSearchPreviewToolSearchContextSizeHigh WebSearchPreviewToolSearchContextSize = "high" +) + +// The user's location. +type WebSearchPreviewToolUserLocation struct { + // The type of location approximation. Always `approximate`. + Type constant.Approximate `json:"type,required"` + // Free text input for the city of the user, e.g. `San Francisco`. + City string `json:"city,nullable"` + // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + // the user, e.g. `US`. + Country string `json:"country,nullable"` + // Free text input for the region of the user, e.g. `California`. + Region string `json:"region,nullable"` + // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + // user, e.g. `America/Los_Angeles`. + Timezone string `json:"timezone,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + City respjson.Field + Country respjson.Field + Region respjson.Field + Timezone respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r WebSearchPreviewToolUserLocation) RawJSON() string { return r.JSON.raw } +func (r *WebSearchPreviewToolUserLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// This tool searches the web for relevant results to use in a response. Learn more +// about the +// [web search tool](https://platform.openai.com/docs/guides/tools-web-search). +// +// The property Type is required. +type WebSearchPreviewToolParam struct { // The type of the web search tool. One of `web_search_preview` or // `web_search_preview_2025_03_11`. // // Any of "web_search_preview", "web_search_preview_2025_03_11". + Type WebSearchPreviewToolType `json:"type,omitzero,required"` + // The user's location. + UserLocation WebSearchPreviewToolUserLocationParam `json:"user_location,omitzero"` + // High level guidance for the amount of context window space to use for the + // search. One of `low`, `medium`, or `high`. `medium` is the default. + // + // Any of "low", "medium", "high". + SearchContextSize WebSearchPreviewToolSearchContextSize `json:"search_context_size,omitzero"` + paramObj +} + +func (r WebSearchPreviewToolParam) MarshalJSON() (data []byte, err error) { + type shadow WebSearchPreviewToolParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *WebSearchPreviewToolParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The user's location. +// +// The property Type is required. +type WebSearchPreviewToolUserLocationParam struct { + // Free text input for the city of the user, e.g. `San Francisco`. + City param.Opt[string] `json:"city,omitzero"` + // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + // the user, e.g. `US`. + Country param.Opt[string] `json:"country,omitzero"` + // Free text input for the region of the user, e.g. `California`. + Region param.Opt[string] `json:"region,omitzero"` + // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + // user, e.g. `America/Los_Angeles`. + Timezone param.Opt[string] `json:"timezone,omitzero"` + // The type of location approximation. Always `approximate`. + // + // This field can be elided, and will marshal its zero value as "approximate". + Type constant.Approximate `json:"type,required"` + paramObj +} + +func (r WebSearchPreviewToolUserLocationParam) MarshalJSON() (data []byte, err error) { + type shadow WebSearchPreviewToolUserLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *WebSearchPreviewToolUserLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Search the Internet for sources related to the prompt. Learn more about the +// [web search tool](https://platform.openai.com/docs/guides/tools-web-search). +type WebSearchTool struct { + // The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + // + // Any of "web_search", "web_search_2025_08_26". Type WebSearchToolType `json:"type,required"` + // Filters for the search. + Filters WebSearchToolFilters `json:"filters,nullable"` // High level guidance for the amount of context window space to use for the // search. One of `low`, `medium`, or `high`. `medium` is the default. // // Any of "low", "medium", "high". SearchContextSize WebSearchToolSearchContextSize `json:"search_context_size"` - // The user's location. + // The approximate location of the user. UserLocation WebSearchToolUserLocation `json:"user_location,nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Type respjson.Field + Filters respjson.Field SearchContextSize respjson.Field UserLocation respjson.Field ExtraFields map[string]respjson.Field @@ -13911,15 +13888,35 @@ func (r WebSearchTool) ToParam() WebSearchToolParam { return param.Override[WebSearchToolParam](json.RawMessage(r.RawJSON())) } -// The type of the web search tool. One of `web_search_preview` or -// `web_search_preview_2025_03_11`. +// The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. type WebSearchToolType string const ( - WebSearchToolTypeWebSearchPreview WebSearchToolType = "web_search_preview" - WebSearchToolTypeWebSearchPreview2025_03_11 WebSearchToolType = "web_search_preview_2025_03_11" + WebSearchToolTypeWebSearch WebSearchToolType = "web_search" + WebSearchToolTypeWebSearch2025_08_26 WebSearchToolType = "web_search_2025_08_26" ) +// Filters for the search. +type WebSearchToolFilters struct { + // Allowed domains for the search. If not provided, all domains are allowed. + // Subdomains of the provided domains are allowed as well. + // + // Example: `["pubmed.ncbi.nlm.nih.gov"]` + AllowedDomains []string `json:"allowed_domains,nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + AllowedDomains respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r WebSearchToolFilters) RawJSON() string { return r.JSON.raw } +func (r *WebSearchToolFilters) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // High level guidance for the amount of context window space to use for the // search. One of `low`, `medium`, or `high`. `medium` is the default. type WebSearchToolSearchContextSize string @@ -13930,10 +13927,8 @@ const ( WebSearchToolSearchContextSizeHigh WebSearchToolSearchContextSize = "high" ) -// The user's location. +// The approximate location of the user. type WebSearchToolUserLocation struct { - // The type of location approximation. Always `approximate`. - Type constant.Approximate `json:"type,required"` // Free text input for the city of the user, e.g. `San Francisco`. City string `json:"city,nullable"` // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of @@ -13944,13 +13939,17 @@ type WebSearchToolUserLocation struct { // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the // user, e.g. `America/Los_Angeles`. Timezone string `json:"timezone,nullable"` + // The type of location approximation. Always `approximate`. + // + // Any of "approximate". + Type string `json:"type"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Type respjson.Field City respjson.Field Country respjson.Field Region respjson.Field Timezone respjson.Field + Type respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -13962,18 +13961,18 @@ func (r *WebSearchToolUserLocation) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// This tool searches the web for relevant results to use in a response. Learn more -// about the +// Search the Internet for sources related to the prompt. Learn more about the // [web search tool](https://platform.openai.com/docs/guides/tools-web-search). // // The property Type is required. type WebSearchToolParam struct { - // The type of the web search tool. One of `web_search_preview` or - // `web_search_preview_2025_03_11`. + // The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. // - // Any of "web_search_preview", "web_search_preview_2025_03_11". + // Any of "web_search", "web_search_2025_08_26". Type WebSearchToolType `json:"type,omitzero,required"` - // The user's location. + // Filters for the search. + Filters WebSearchToolFiltersParam `json:"filters,omitzero"` + // The approximate location of the user. UserLocation WebSearchToolUserLocationParam `json:"user_location,omitzero"` // High level guidance for the amount of context window space to use for the // search. One of `low`, `medium`, or `high`. `medium` is the default. @@ -13991,9 +13990,25 @@ func (r *WebSearchToolParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The user's location. -// -// The property Type is required. +// Filters for the search. +type WebSearchToolFiltersParam struct { + // Allowed domains for the search. If not provided, all domains are allowed. + // Subdomains of the provided domains are allowed as well. + // + // Example: `["pubmed.ncbi.nlm.nih.gov"]` + AllowedDomains []string `json:"allowed_domains,omitzero"` + paramObj +} + +func (r WebSearchToolFiltersParam) MarshalJSON() (data []byte, err error) { + type shadow WebSearchToolFiltersParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *WebSearchToolFiltersParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The approximate location of the user. type WebSearchToolUserLocationParam struct { // Free text input for the city of the user, e.g. `San Francisco`. City param.Opt[string] `json:"city,omitzero"` @@ -14007,8 +14022,8 @@ type WebSearchToolUserLocationParam struct { Timezone param.Opt[string] `json:"timezone,omitzero"` // The type of location approximation. Always `approximate`. // - // This field can be elided, and will marshal its zero value as "approximate". - Type constant.Approximate `json:"type,required"` + // Any of "approximate". + Type string `json:"type,omitzero"` paramObj } @@ -14020,6 +14035,12 @@ func (r *WebSearchToolUserLocationParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func init() { + apijson.RegisterFieldValidator[WebSearchToolUserLocationParam]( + "type", "approximate", + ) +} + type ResponseNewParams struct { // Whether to run the model response in the background. // [Learn more](https://platform.openai.com/docs/guides/background). @@ -14177,7 +14198,7 @@ type ResponseNewParams struct { // An array of tools the model may call while generating a response. You can // specify which tool to use by setting the `tool_choice` parameter. // - // The two categories of tools you can provide the model are: + // We support the following categories of tools: // // - **Built-in tools**: Tools that are provided by OpenAI that extend the model's // capabilities, like @@ -14185,6 +14206,9 @@ type ResponseNewParams struct { // [file search](https://platform.openai.com/docs/guides/tools-file-search). // Learn more about // [built-in tools](https://platform.openai.com/docs/guides/tools). + // - **MCP Tools**: Integrations with third-party systems via custom MCP servers or + // predefined connectors such as Google Drive and Notion. Learn more about + // [MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp). // - **Function calls (custom tools)**: Functions that are defined by you, enabling // the model to call your own code with strongly typed arguments and outputs. // Learn more about diff --git a/scripts/detect-breaking-changes b/scripts/detect-breaking-changes index 591075c8..71911e61 100755 --- a/scripts/detect-breaking-changes +++ b/scripts/detect-breaking-changes @@ -37,6 +37,7 @@ TEST_PATHS=( uploadpart_test.go responses/response_test.go responses/inputitem_test.go + realtime/clientsecret_test.go conversations/conversation_test.go conversations/item_test.go container_test.go diff --git a/shared/constant/constants.go b/shared/constant/constants.go index 65061525..600d765e 100644 --- a/shared/constant/constants.go +++ b/shared/constant/constants.go @@ -18,218 +18,271 @@ func ValueOf[T Constant[T]]() T { return t.Default() } -type AllowedTools string // Always "allowed_tools" -type Approximate string // Always "approximate" -type Assistant string // Always "assistant" -type AssistantDeleted string // Always "assistant.deleted" -type Auto string // Always "auto" -type Batch string // Always "batch" -type BatchCancelled string // Always "batch.cancelled" -type BatchCompleted string // Always "batch.completed" -type BatchExpired string // Always "batch.expired" -type BatchFailed string // Always "batch.failed" -type ChatCompletion string // Always "chat.completion" -type ChatCompletionChunk string // Always "chat.completion.chunk" -type ChatCompletionDeleted string // Always "chat.completion.deleted" -type CheckpointPermission string // Always "checkpoint.permission" -type Click string // Always "click" -type CodeInterpreter string // Always "code_interpreter" -type CodeInterpreterCall string // Always "code_interpreter_call" -type ComputerCallOutput string // Always "computer_call_output" -type ComputerScreenshot string // Always "computer_screenshot" -type ComputerUsePreview string // Always "computer_use_preview" -type ContainerFileCitation string // Always "container_file_citation" -type ContainerFile string // Always "container.file" -type Content string // Always "content" -type Conversation string // Always "conversation" -type ConversationDeleted string // Always "conversation.deleted" -type CreatedAt string // Always "created_at" -type Custom string // Always "custom" -type CustomToolCall string // Always "custom_tool_call" -type CustomToolCallOutput string // Always "custom_tool_call_output" -type Developer string // Always "developer" -type DoubleClick string // Always "double_click" -type Drag string // Always "drag" -type Duration string // Always "duration" -type Embedding string // Always "embedding" -type Error string // Always "error" -type EvalRunCanceled string // Always "eval.run.canceled" -type EvalRunFailed string // Always "eval.run.failed" -type EvalRunSucceeded string // Always "eval.run.succeeded" -type Exec string // Always "exec" -type File string // Always "file" -type FileCitation string // Always "file_citation" -type FilePath string // Always "file_path" -type FileSearch string // Always "file_search" -type FileSearchCall string // Always "file_search_call" -type Find string // Always "find" -type FineTuningJob string // Always "fine_tuning.job" -type FineTuningJobCancelled string // Always "fine_tuning.job.cancelled" -type FineTuningJobCheckpoint string // Always "fine_tuning.job.checkpoint" -type FineTuningJobEvent string // Always "fine_tuning.job.event" -type FineTuningJobFailed string // Always "fine_tuning.job.failed" -type FineTuningJobSucceeded string // Always "fine_tuning.job.succeeded" -type Function string // Always "function" -type FunctionCall string // Always "function_call" -type FunctionCallOutput string // Always "function_call_output" -type Grammar string // Always "grammar" -type Image string // Always "image" -type ImageEditCompleted string // Always "image_edit.completed" -type ImageEditPartialImage string // Always "image_edit.partial_image" -type ImageFile string // Always "image_file" -type ImageGeneration string // Always "image_generation" -type ImageGenerationCall string // Always "image_generation_call" -type ImageGenerationCompleted string // Always "image_generation.completed" -type ImageGenerationPartialImage string // Always "image_generation.partial_image" -type ImageURL string // Always "image_url" -type InputAudio string // Always "input_audio" -type InputFile string // Always "input_file" -type InputImage string // Always "input_image" -type InputText string // Always "input_text" -type JSONObject string // Always "json_object" -type JSONSchema string // Always "json_schema" -type Keypress string // Always "keypress" -type LabelModel string // Always "label_model" -type LastActiveAt string // Always "last_active_at" -type List string // Always "list" -type LocalShell string // Always "local_shell" -type LocalShellCall string // Always "local_shell_call" -type LocalShellCallOutput string // Always "local_shell_call_output" -type Logs string // Always "logs" -type Mcp string // Always "mcp" -type McpApprovalRequest string // Always "mcp_approval_request" -type McpApprovalResponse string // Always "mcp_approval_response" -type McpCall string // Always "mcp_call" -type McpListTools string // Always "mcp_list_tools" -type Message string // Always "message" -type MessageCreation string // Always "message_creation" -type Model string // Always "model" -type Move string // Always "move" -type Multi string // Always "multi" -type OpenPage string // Always "open_page" -type Other string // Always "other" -type OutputAudio string // Always "output_audio" -type OutputText string // Always "output_text" -type Python string // Always "python" -type Reasoning string // Always "reasoning" -type ReasoningText string // Always "reasoning_text" -type Refusal string // Always "refusal" -type Response string // Always "response" -type ResponseAudioDelta string // Always "response.audio.delta" -type ResponseAudioDone string // Always "response.audio.done" -type ResponseAudioTranscriptDelta string // Always "response.audio.transcript.delta" -type ResponseAudioTranscriptDone string // Always "response.audio.transcript.done" -type ResponseCancelled string // Always "response.cancelled" -type ResponseCodeInterpreterCallCodeDelta string // Always "response.code_interpreter_call_code.delta" -type ResponseCodeInterpreterCallCodeDone string // Always "response.code_interpreter_call_code.done" -type ResponseCodeInterpreterCallCompleted string // Always "response.code_interpreter_call.completed" -type ResponseCodeInterpreterCallInProgress string // Always "response.code_interpreter_call.in_progress" -type ResponseCodeInterpreterCallInterpreting string // Always "response.code_interpreter_call.interpreting" -type ResponseCompleted string // Always "response.completed" -type ResponseContentPartAdded string // Always "response.content_part.added" -type ResponseContentPartDone string // Always "response.content_part.done" -type ResponseCreated string // Always "response.created" -type ResponseCustomToolCallInputDelta string // Always "response.custom_tool_call_input.delta" -type ResponseCustomToolCallInputDone string // Always "response.custom_tool_call_input.done" -type ResponseFailed string // Always "response.failed" -type ResponseFileSearchCallCompleted string // Always "response.file_search_call.completed" -type ResponseFileSearchCallInProgress string // Always "response.file_search_call.in_progress" -type ResponseFileSearchCallSearching string // Always "response.file_search_call.searching" -type ResponseFunctionCallArgumentsDelta string // Always "response.function_call_arguments.delta" -type ResponseFunctionCallArgumentsDone string // Always "response.function_call_arguments.done" -type ResponseImageGenerationCallCompleted string // Always "response.image_generation_call.completed" -type ResponseImageGenerationCallGenerating string // Always "response.image_generation_call.generating" -type ResponseImageGenerationCallInProgress string // Always "response.image_generation_call.in_progress" -type ResponseImageGenerationCallPartialImage string // Always "response.image_generation_call.partial_image" -type ResponseInProgress string // Always "response.in_progress" -type ResponseIncomplete string // Always "response.incomplete" -type ResponseMcpCallArgumentsDelta string // Always "response.mcp_call_arguments.delta" -type ResponseMcpCallArgumentsDone string // Always "response.mcp_call_arguments.done" -type ResponseMcpCallCompleted string // Always "response.mcp_call.completed" -type ResponseMcpCallFailed string // Always "response.mcp_call.failed" -type ResponseMcpCallInProgress string // Always "response.mcp_call.in_progress" -type ResponseMcpListToolsCompleted string // Always "response.mcp_list_tools.completed" -type ResponseMcpListToolsFailed string // Always "response.mcp_list_tools.failed" -type ResponseMcpListToolsInProgress string // Always "response.mcp_list_tools.in_progress" -type ResponseOutputItemAdded string // Always "response.output_item.added" -type ResponseOutputItemDone string // Always "response.output_item.done" -type ResponseOutputTextAnnotationAdded string // Always "response.output_text.annotation.added" -type ResponseOutputTextDelta string // Always "response.output_text.delta" -type ResponseOutputTextDone string // Always "response.output_text.done" -type ResponseQueued string // Always "response.queued" -type ResponseReasoningSummaryPartAdded string // Always "response.reasoning_summary_part.added" -type ResponseReasoningSummaryPartDone string // Always "response.reasoning_summary_part.done" -type ResponseReasoningSummaryTextDelta string // Always "response.reasoning_summary_text.delta" -type ResponseReasoningSummaryTextDone string // Always "response.reasoning_summary_text.done" -type ResponseReasoningTextDelta string // Always "response.reasoning_text.delta" -type ResponseReasoningTextDone string // Always "response.reasoning_text.done" -type ResponseRefusalDelta string // Always "response.refusal.delta" -type ResponseRefusalDone string // Always "response.refusal.done" -type ResponseWebSearchCallCompleted string // Always "response.web_search_call.completed" -type ResponseWebSearchCallInProgress string // Always "response.web_search_call.in_progress" -type ResponseWebSearchCallSearching string // Always "response.web_search_call.searching" -type ScoreModel string // Always "score_model" -type Screenshot string // Always "screenshot" -type Scroll string // Always "scroll" -type Search string // Always "search" -type Static string // Always "static" -type StringCheck string // Always "string_check" -type SubmitToolOutputs string // Always "submit_tool_outputs" -type SummaryText string // Always "summary_text" -type System string // Always "system" -type Text string // Always "text" -type TextCompletion string // Always "text_completion" -type TextSimilarity string // Always "text_similarity" -type Thread string // Always "thread" -type ThreadCreated string // Always "thread.created" -type ThreadDeleted string // Always "thread.deleted" -type ThreadMessage string // Always "thread.message" -type ThreadMessageCompleted string // Always "thread.message.completed" -type ThreadMessageCreated string // Always "thread.message.created" -type ThreadMessageDeleted string // Always "thread.message.deleted" -type ThreadMessageDelta string // Always "thread.message.delta" -type ThreadMessageInProgress string // Always "thread.message.in_progress" -type ThreadMessageIncomplete string // Always "thread.message.incomplete" -type ThreadRun string // Always "thread.run" -type ThreadRunCancelled string // Always "thread.run.cancelled" -type ThreadRunCancelling string // Always "thread.run.cancelling" -type ThreadRunCompleted string // Always "thread.run.completed" -type ThreadRunCreated string // Always "thread.run.created" -type ThreadRunExpired string // Always "thread.run.expired" -type ThreadRunFailed string // Always "thread.run.failed" -type ThreadRunInProgress string // Always "thread.run.in_progress" -type ThreadRunIncomplete string // Always "thread.run.incomplete" -type ThreadRunQueued string // Always "thread.run.queued" -type ThreadRunRequiresAction string // Always "thread.run.requires_action" -type ThreadRunStep string // Always "thread.run.step" -type ThreadRunStepCancelled string // Always "thread.run.step.cancelled" -type ThreadRunStepCompleted string // Always "thread.run.step.completed" -type ThreadRunStepCreated string // Always "thread.run.step.created" -type ThreadRunStepDelta string // Always "thread.run.step.delta" -type ThreadRunStepExpired string // Always "thread.run.step.expired" -type ThreadRunStepFailed string // Always "thread.run.step.failed" -type ThreadRunStepInProgress string // Always "thread.run.step.in_progress" -type Tokens string // Always "tokens" -type Tool string // Always "tool" -type ToolCalls string // Always "tool_calls" -type TranscriptTextDelta string // Always "transcript.text.delta" -type TranscriptTextDone string // Always "transcript.text.done" -type Type string // Always "type" -type Upload string // Always "upload" -type UploadPart string // Always "upload.part" -type URL string // Always "url" -type URLCitation string // Always "url_citation" -type User string // Always "user" -type VectorStore string // Always "vector_store" -type VectorStoreDeleted string // Always "vector_store.deleted" -type VectorStoreFile string // Always "vector_store.file" -type VectorStoreFileContentPage string // Always "vector_store.file_content.page" -type VectorStoreFileDeleted string // Always "vector_store.file.deleted" -type VectorStoreFilesBatch string // Always "vector_store.files_batch" -type VectorStoreSearchResultsPage string // Always "vector_store.search_results.page" -type Wait string // Always "wait" -type Wandb string // Always "wandb" -type WebSearchCall string // Always "web_search_call" +type AllowedTools string // Always "allowed_tools" +type Approximate string // Always "approximate" +type Assistant string // Always "assistant" +type AssistantDeleted string // Always "assistant.deleted" +type Auto string // Always "auto" +type Batch string // Always "batch" +type BatchCancelled string // Always "batch.cancelled" +type BatchCompleted string // Always "batch.completed" +type BatchExpired string // Always "batch.expired" +type BatchFailed string // Always "batch.failed" +type ChatCompletion string // Always "chat.completion" +type ChatCompletionChunk string // Always "chat.completion.chunk" +type ChatCompletionDeleted string // Always "chat.completion.deleted" +type CheckpointPermission string // Always "checkpoint.permission" +type Click string // Always "click" +type CodeInterpreter string // Always "code_interpreter" +type CodeInterpreterCall string // Always "code_interpreter_call" +type ComputerCallOutput string // Always "computer_call_output" +type ComputerScreenshot string // Always "computer_screenshot" +type ComputerUsePreview string // Always "computer_use_preview" +type ContainerFileCitation string // Always "container_file_citation" +type ContainerFile string // Always "container.file" +type Content string // Always "content" +type Conversation string // Always "conversation" +type ConversationCreated string // Always "conversation.created" +type ConversationDeleted string // Always "conversation.deleted" +type ConversationItemAdded string // Always "conversation.item.added" +type ConversationItemCreate string // Always "conversation.item.create" +type ConversationItemCreated string // Always "conversation.item.created" +type ConversationItemDelete string // Always "conversation.item.delete" +type ConversationItemDeleted string // Always "conversation.item.deleted" +type ConversationItemDone string // Always "conversation.item.done" +type ConversationItemInputAudioTranscriptionCompleted string // Always "conversation.item.input_audio_transcription.completed" +type ConversationItemInputAudioTranscriptionDelta string // Always "conversation.item.input_audio_transcription.delta" +type ConversationItemInputAudioTranscriptionFailed string // Always "conversation.item.input_audio_transcription.failed" +type ConversationItemInputAudioTranscriptionSegment string // Always "conversation.item.input_audio_transcription.segment" +type ConversationItemRetrieve string // Always "conversation.item.retrieve" +type ConversationItemRetrieved string // Always "conversation.item.retrieved" +type ConversationItemTruncate string // Always "conversation.item.truncate" +type ConversationItemTruncated string // Always "conversation.item.truncated" +type CreatedAt string // Always "created_at" +type Custom string // Always "custom" +type CustomToolCall string // Always "custom_tool_call" +type CustomToolCallOutput string // Always "custom_tool_call_output" +type Developer string // Always "developer" +type DoubleClick string // Always "double_click" +type Drag string // Always "drag" +type Duration string // Always "duration" +type Embedding string // Always "embedding" +type Error string // Always "error" +type EvalRunCanceled string // Always "eval.run.canceled" +type EvalRunFailed string // Always "eval.run.failed" +type EvalRunSucceeded string // Always "eval.run.succeeded" +type Exec string // Always "exec" +type File string // Always "file" +type FileCitation string // Always "file_citation" +type FilePath string // Always "file_path" +type FileSearch string // Always "file_search" +type FileSearchCall string // Always "file_search_call" +type Find string // Always "find" +type FineTuningJob string // Always "fine_tuning.job" +type FineTuningJobCancelled string // Always "fine_tuning.job.cancelled" +type FineTuningJobCheckpoint string // Always "fine_tuning.job.checkpoint" +type FineTuningJobEvent string // Always "fine_tuning.job.event" +type FineTuningJobFailed string // Always "fine_tuning.job.failed" +type FineTuningJobSucceeded string // Always "fine_tuning.job.succeeded" +type Function string // Always "function" +type FunctionCall string // Always "function_call" +type FunctionCallOutput string // Always "function_call_output" +type Grammar string // Always "grammar" +type HTTPError string // Always "http_error" +type Image string // Always "image" +type ImageEditCompleted string // Always "image_edit.completed" +type ImageEditPartialImage string // Always "image_edit.partial_image" +type ImageFile string // Always "image_file" +type ImageGeneration string // Always "image_generation" +type ImageGenerationCall string // Always "image_generation_call" +type ImageGenerationCompleted string // Always "image_generation.completed" +type ImageGenerationPartialImage string // Always "image_generation.partial_image" +type ImageURL string // Always "image_url" +type Inf string // Always "inf" +type InputAudio string // Always "input_audio" +type InputAudioBufferAppend string // Always "input_audio_buffer.append" +type InputAudioBufferClear string // Always "input_audio_buffer.clear" +type InputAudioBufferCleared string // Always "input_audio_buffer.cleared" +type InputAudioBufferCommit string // Always "input_audio_buffer.commit" +type InputAudioBufferCommitted string // Always "input_audio_buffer.committed" +type InputAudioBufferSpeechStarted string // Always "input_audio_buffer.speech_started" +type InputAudioBufferSpeechStopped string // Always "input_audio_buffer.speech_stopped" +type InputAudioBufferTimeoutTriggered string // Always "input_audio_buffer.timeout_triggered" +type InputFile string // Always "input_file" +type InputImage string // Always "input_image" +type InputText string // Always "input_text" +type JSONObject string // Always "json_object" +type JSONSchema string // Always "json_schema" +type Keypress string // Always "keypress" +type LabelModel string // Always "label_model" +type LastActiveAt string // Always "last_active_at" +type List string // Always "list" +type LocalShell string // Always "local_shell" +type LocalShellCall string // Always "local_shell_call" +type LocalShellCallOutput string // Always "local_shell_call_output" +type Logs string // Always "logs" +type Mcp string // Always "mcp" +type McpApprovalRequest string // Always "mcp_approval_request" +type McpApprovalResponse string // Always "mcp_approval_response" +type McpCall string // Always "mcp_call" +type McpListTools string // Always "mcp_list_tools" +type McpListToolsCompleted string // Always "mcp_list_tools.completed" +type McpListToolsFailed string // Always "mcp_list_tools.failed" +type McpListToolsInProgress string // Always "mcp_list_tools.in_progress" +type McpToolCall string // Always "mcp_tool_call" +type Message string // Always "message" +type MessageCreation string // Always "message_creation" +type Model string // Always "model" +type Move string // Always "move" +type Multi string // Always "multi" +type OpenPage string // Always "open_page" +type Other string // Always "other" +type OutputAudio string // Always "output_audio" +type OutputAudioBufferClear string // Always "output_audio_buffer.clear" +type OutputAudioBufferCleared string // Always "output_audio_buffer.cleared" +type OutputAudioBufferStarted string // Always "output_audio_buffer.started" +type OutputAudioBufferStopped string // Always "output_audio_buffer.stopped" +type OutputText string // Always "output_text" +type ProtocolError string // Always "protocol_error" +type Python string // Always "python" +type RateLimitsUpdated string // Always "rate_limits.updated" +type Realtime string // Always "realtime" +type RealtimeCallIncoming string // Always "realtime.call.incoming" +type Reasoning string // Always "reasoning" +type ReasoningText string // Always "reasoning_text" +type Refusal string // Always "refusal" +type Response string // Always "response" +type ResponseAudioDelta string // Always "response.audio.delta" +type ResponseAudioDone string // Always "response.audio.done" +type ResponseAudioTranscriptDelta string // Always "response.audio.transcript.delta" +type ResponseAudioTranscriptDone string // Always "response.audio.transcript.done" +type ResponseCancel string // Always "response.cancel" +type ResponseCancelled string // Always "response.cancelled" +type ResponseCodeInterpreterCallCodeDelta string // Always "response.code_interpreter_call_code.delta" +type ResponseCodeInterpreterCallCodeDone string // Always "response.code_interpreter_call_code.done" +type ResponseCodeInterpreterCallCompleted string // Always "response.code_interpreter_call.completed" +type ResponseCodeInterpreterCallInProgress string // Always "response.code_interpreter_call.in_progress" +type ResponseCodeInterpreterCallInterpreting string // Always "response.code_interpreter_call.interpreting" +type ResponseCompleted string // Always "response.completed" +type ResponseContentPartAdded string // Always "response.content_part.added" +type ResponseContentPartDone string // Always "response.content_part.done" +type ResponseCreate string // Always "response.create" +type ResponseCreated string // Always "response.created" +type ResponseCustomToolCallInputDelta string // Always "response.custom_tool_call_input.delta" +type ResponseCustomToolCallInputDone string // Always "response.custom_tool_call_input.done" +type ResponseDone string // Always "response.done" +type ResponseFailed string // Always "response.failed" +type ResponseFileSearchCallCompleted string // Always "response.file_search_call.completed" +type ResponseFileSearchCallInProgress string // Always "response.file_search_call.in_progress" +type ResponseFileSearchCallSearching string // Always "response.file_search_call.searching" +type ResponseFunctionCallArgumentsDelta string // Always "response.function_call_arguments.delta" +type ResponseFunctionCallArgumentsDone string // Always "response.function_call_arguments.done" +type ResponseImageGenerationCallCompleted string // Always "response.image_generation_call.completed" +type ResponseImageGenerationCallGenerating string // Always "response.image_generation_call.generating" +type ResponseImageGenerationCallInProgress string // Always "response.image_generation_call.in_progress" +type ResponseImageGenerationCallPartialImage string // Always "response.image_generation_call.partial_image" +type ResponseInProgress string // Always "response.in_progress" +type ResponseIncomplete string // Always "response.incomplete" +type ResponseMcpCallArgumentsDelta string // Always "response.mcp_call_arguments.delta" +type ResponseMcpCallArgumentsDone string // Always "response.mcp_call_arguments.done" +type ResponseMcpCallCompleted string // Always "response.mcp_call.completed" +type ResponseMcpCallFailed string // Always "response.mcp_call.failed" +type ResponseMcpCallInProgress string // Always "response.mcp_call.in_progress" +type ResponseMcpListToolsCompleted string // Always "response.mcp_list_tools.completed" +type ResponseMcpListToolsFailed string // Always "response.mcp_list_tools.failed" +type ResponseMcpListToolsInProgress string // Always "response.mcp_list_tools.in_progress" +type ResponseOutputAudioTranscriptDelta string // Always "response.output_audio_transcript.delta" +type ResponseOutputAudioTranscriptDone string // Always "response.output_audio_transcript.done" +type ResponseOutputAudioDelta string // Always "response.output_audio.delta" +type ResponseOutputAudioDone string // Always "response.output_audio.done" +type ResponseOutputItemAdded string // Always "response.output_item.added" +type ResponseOutputItemDone string // Always "response.output_item.done" +type ResponseOutputTextAnnotationAdded string // Always "response.output_text.annotation.added" +type ResponseOutputTextDelta string // Always "response.output_text.delta" +type ResponseOutputTextDone string // Always "response.output_text.done" +type ResponseQueued string // Always "response.queued" +type ResponseReasoningSummaryPartAdded string // Always "response.reasoning_summary_part.added" +type ResponseReasoningSummaryPartDone string // Always "response.reasoning_summary_part.done" +type ResponseReasoningSummaryTextDelta string // Always "response.reasoning_summary_text.delta" +type ResponseReasoningSummaryTextDone string // Always "response.reasoning_summary_text.done" +type ResponseReasoningTextDelta string // Always "response.reasoning_text.delta" +type ResponseReasoningTextDone string // Always "response.reasoning_text.done" +type ResponseRefusalDelta string // Always "response.refusal.delta" +type ResponseRefusalDone string // Always "response.refusal.done" +type ResponseWebSearchCallCompleted string // Always "response.web_search_call.completed" +type ResponseWebSearchCallInProgress string // Always "response.web_search_call.in_progress" +type ResponseWebSearchCallSearching string // Always "response.web_search_call.searching" +type RetentionRatio string // Always "retention_ratio" +type ScoreModel string // Always "score_model" +type Screenshot string // Always "screenshot" +type Scroll string // Always "scroll" +type Search string // Always "search" +type SessionCreated string // Always "session.created" +type SessionUpdate string // Always "session.update" +type SessionUpdated string // Always "session.updated" +type Static string // Always "static" +type StringCheck string // Always "string_check" +type SubmitToolOutputs string // Always "submit_tool_outputs" +type SummaryText string // Always "summary_text" +type System string // Always "system" +type Text string // Always "text" +type TextCompletion string // Always "text_completion" +type TextSimilarity string // Always "text_similarity" +type Thread string // Always "thread" +type ThreadCreated string // Always "thread.created" +type ThreadDeleted string // Always "thread.deleted" +type ThreadMessage string // Always "thread.message" +type ThreadMessageCompleted string // Always "thread.message.completed" +type ThreadMessageCreated string // Always "thread.message.created" +type ThreadMessageDeleted string // Always "thread.message.deleted" +type ThreadMessageDelta string // Always "thread.message.delta" +type ThreadMessageInProgress string // Always "thread.message.in_progress" +type ThreadMessageIncomplete string // Always "thread.message.incomplete" +type ThreadRun string // Always "thread.run" +type ThreadRunCancelled string // Always "thread.run.cancelled" +type ThreadRunCancelling string // Always "thread.run.cancelling" +type ThreadRunCompleted string // Always "thread.run.completed" +type ThreadRunCreated string // Always "thread.run.created" +type ThreadRunExpired string // Always "thread.run.expired" +type ThreadRunFailed string // Always "thread.run.failed" +type ThreadRunInProgress string // Always "thread.run.in_progress" +type ThreadRunIncomplete string // Always "thread.run.incomplete" +type ThreadRunQueued string // Always "thread.run.queued" +type ThreadRunRequiresAction string // Always "thread.run.requires_action" +type ThreadRunStep string // Always "thread.run.step" +type ThreadRunStepCancelled string // Always "thread.run.step.cancelled" +type ThreadRunStepCompleted string // Always "thread.run.step.completed" +type ThreadRunStepCreated string // Always "thread.run.step.created" +type ThreadRunStepDelta string // Always "thread.run.step.delta" +type ThreadRunStepExpired string // Always "thread.run.step.expired" +type ThreadRunStepFailed string // Always "thread.run.step.failed" +type ThreadRunStepInProgress string // Always "thread.run.step.in_progress" +type Tokens string // Always "tokens" +type Tool string // Always "tool" +type ToolCalls string // Always "tool_calls" +type ToolExecutionError string // Always "tool_execution_error" +type TranscriptTextDelta string // Always "transcript.text.delta" +type TranscriptTextDone string // Always "transcript.text.done" +type Transcription string // Always "transcription" +type TranscriptionSessionCreated string // Always "transcription_session.created" +type TranscriptionSessionUpdate string // Always "transcription_session.update" +type TranscriptionSessionUpdated string // Always "transcription_session.updated" +type Type string // Always "type" +type Upload string // Always "upload" +type UploadPart string // Always "upload.part" +type URL string // Always "url" +type URLCitation string // Always "url_citation" +type User string // Always "user" +type VectorStore string // Always "vector_store" +type VectorStoreDeleted string // Always "vector_store.deleted" +type VectorStoreFile string // Always "vector_store.file" +type VectorStoreFileContentPage string // Always "vector_store.file_content.page" +type VectorStoreFileDeleted string // Always "vector_store.file.deleted" +type VectorStoreFilesBatch string // Always "vector_store.files_batch" +type VectorStoreSearchResultsPage string // Always "vector_store.search_results.page" +type Wait string // Always "wait" +type Wandb string // Always "wandb" +type WebSearchCall string // Always "web_search_call" func (c AllowedTools) Default() AllowedTools { return "allowed_tools" } func (c Approximate) Default() Approximate { return "approximate" } @@ -255,7 +308,42 @@ func (c ContainerFileCitation) Default() ContainerFileCitation { return "conta func (c ContainerFile) Default() ContainerFile { return "container.file" } func (c Content) Default() Content { return "content" } func (c Conversation) Default() Conversation { return "conversation" } +func (c ConversationCreated) Default() ConversationCreated { return "conversation.created" } func (c ConversationDeleted) Default() ConversationDeleted { return "conversation.deleted" } +func (c ConversationItemAdded) Default() ConversationItemAdded { return "conversation.item.added" } +func (c ConversationItemCreate) Default() ConversationItemCreate { return "conversation.item.create" } +func (c ConversationItemCreated) Default() ConversationItemCreated { + return "conversation.item.created" +} +func (c ConversationItemDelete) Default() ConversationItemDelete { return "conversation.item.delete" } +func (c ConversationItemDeleted) Default() ConversationItemDeleted { + return "conversation.item.deleted" +} +func (c ConversationItemDone) Default() ConversationItemDone { return "conversation.item.done" } +func (c ConversationItemInputAudioTranscriptionCompleted) Default() ConversationItemInputAudioTranscriptionCompleted { + return "conversation.item.input_audio_transcription.completed" +} +func (c ConversationItemInputAudioTranscriptionDelta) Default() ConversationItemInputAudioTranscriptionDelta { + return "conversation.item.input_audio_transcription.delta" +} +func (c ConversationItemInputAudioTranscriptionFailed) Default() ConversationItemInputAudioTranscriptionFailed { + return "conversation.item.input_audio_transcription.failed" +} +func (c ConversationItemInputAudioTranscriptionSegment) Default() ConversationItemInputAudioTranscriptionSegment { + return "conversation.item.input_audio_transcription.segment" +} +func (c ConversationItemRetrieve) Default() ConversationItemRetrieve { + return "conversation.item.retrieve" +} +func (c ConversationItemRetrieved) Default() ConversationItemRetrieved { + return "conversation.item.retrieved" +} +func (c ConversationItemTruncate) Default() ConversationItemTruncate { + return "conversation.item.truncate" +} +func (c ConversationItemTruncated) Default() ConversationItemTruncated { + return "conversation.item.truncated" +} func (c CreatedAt) Default() CreatedAt { return "created_at" } func (c Custom) Default() Custom { return "custom" } func (c CustomToolCall) Default() CustomToolCall { return "custom_tool_call" } @@ -288,6 +376,7 @@ func (c Function) Default() Function { return "funct func (c FunctionCall) Default() FunctionCall { return "function_call" } func (c FunctionCallOutput) Default() FunctionCallOutput { return "function_call_output" } func (c Grammar) Default() Grammar { return "grammar" } +func (c HTTPError) Default() HTTPError { return "http_error" } func (c Image) Default() Image { return "image" } func (c ImageEditCompleted) Default() ImageEditCompleted { return "image_edit.completed" } func (c ImageEditPartialImage) Default() ImageEditPartialImage { return "image_edit.partial_image" } @@ -300,36 +389,73 @@ func (c ImageGenerationCompleted) Default() ImageGenerationCompleted { func (c ImageGenerationPartialImage) Default() ImageGenerationPartialImage { return "image_generation.partial_image" } -func (c ImageURL) Default() ImageURL { return "image_url" } -func (c InputAudio) Default() InputAudio { return "input_audio" } -func (c InputFile) Default() InputFile { return "input_file" } -func (c InputImage) Default() InputImage { return "input_image" } -func (c InputText) Default() InputText { return "input_text" } -func (c JSONObject) Default() JSONObject { return "json_object" } -func (c JSONSchema) Default() JSONSchema { return "json_schema" } -func (c Keypress) Default() Keypress { return "keypress" } -func (c LabelModel) Default() LabelModel { return "label_model" } -func (c LastActiveAt) Default() LastActiveAt { return "last_active_at" } -func (c List) Default() List { return "list" } -func (c LocalShell) Default() LocalShell { return "local_shell" } -func (c LocalShellCall) Default() LocalShellCall { return "local_shell_call" } -func (c LocalShellCallOutput) Default() LocalShellCallOutput { return "local_shell_call_output" } -func (c Logs) Default() Logs { return "logs" } -func (c Mcp) Default() Mcp { return "mcp" } -func (c McpApprovalRequest) Default() McpApprovalRequest { return "mcp_approval_request" } -func (c McpApprovalResponse) Default() McpApprovalResponse { return "mcp_approval_response" } -func (c McpCall) Default() McpCall { return "mcp_call" } -func (c McpListTools) Default() McpListTools { return "mcp_list_tools" } -func (c Message) Default() Message { return "message" } -func (c MessageCreation) Default() MessageCreation { return "message_creation" } -func (c Model) Default() Model { return "model" } -func (c Move) Default() Move { return "move" } -func (c Multi) Default() Multi { return "multi" } -func (c OpenPage) Default() OpenPage { return "open_page" } -func (c Other) Default() Other { return "other" } -func (c OutputAudio) Default() OutputAudio { return "output_audio" } +func (c ImageURL) Default() ImageURL { return "image_url" } +func (c Inf) Default() Inf { return "inf" } +func (c InputAudio) Default() InputAudio { return "input_audio" } +func (c InputAudioBufferAppend) Default() InputAudioBufferAppend { return "input_audio_buffer.append" } +func (c InputAudioBufferClear) Default() InputAudioBufferClear { return "input_audio_buffer.clear" } +func (c InputAudioBufferCleared) Default() InputAudioBufferCleared { + return "input_audio_buffer.cleared" +} +func (c InputAudioBufferCommit) Default() InputAudioBufferCommit { return "input_audio_buffer.commit" } +func (c InputAudioBufferCommitted) Default() InputAudioBufferCommitted { + return "input_audio_buffer.committed" +} +func (c InputAudioBufferSpeechStarted) Default() InputAudioBufferSpeechStarted { + return "input_audio_buffer.speech_started" +} +func (c InputAudioBufferSpeechStopped) Default() InputAudioBufferSpeechStopped { + return "input_audio_buffer.speech_stopped" +} +func (c InputAudioBufferTimeoutTriggered) Default() InputAudioBufferTimeoutTriggered { + return "input_audio_buffer.timeout_triggered" +} +func (c InputFile) Default() InputFile { return "input_file" } +func (c InputImage) Default() InputImage { return "input_image" } +func (c InputText) Default() InputText { return "input_text" } +func (c JSONObject) Default() JSONObject { return "json_object" } +func (c JSONSchema) Default() JSONSchema { return "json_schema" } +func (c Keypress) Default() Keypress { return "keypress" } +func (c LabelModel) Default() LabelModel { return "label_model" } +func (c LastActiveAt) Default() LastActiveAt { return "last_active_at" } +func (c List) Default() List { return "list" } +func (c LocalShell) Default() LocalShell { return "local_shell" } +func (c LocalShellCall) Default() LocalShellCall { return "local_shell_call" } +func (c LocalShellCallOutput) Default() LocalShellCallOutput { return "local_shell_call_output" } +func (c Logs) Default() Logs { return "logs" } +func (c Mcp) Default() Mcp { return "mcp" } +func (c McpApprovalRequest) Default() McpApprovalRequest { return "mcp_approval_request" } +func (c McpApprovalResponse) Default() McpApprovalResponse { return "mcp_approval_response" } +func (c McpCall) Default() McpCall { return "mcp_call" } +func (c McpListTools) Default() McpListTools { return "mcp_list_tools" } +func (c McpListToolsCompleted) Default() McpListToolsCompleted { return "mcp_list_tools.completed" } +func (c McpListToolsFailed) Default() McpListToolsFailed { return "mcp_list_tools.failed" } +func (c McpListToolsInProgress) Default() McpListToolsInProgress { return "mcp_list_tools.in_progress" } +func (c McpToolCall) Default() McpToolCall { return "mcp_tool_call" } +func (c Message) Default() Message { return "message" } +func (c MessageCreation) Default() MessageCreation { return "message_creation" } +func (c Model) Default() Model { return "model" } +func (c Move) Default() Move { return "move" } +func (c Multi) Default() Multi { return "multi" } +func (c OpenPage) Default() OpenPage { return "open_page" } +func (c Other) Default() Other { return "other" } +func (c OutputAudio) Default() OutputAudio { return "output_audio" } +func (c OutputAudioBufferClear) Default() OutputAudioBufferClear { return "output_audio_buffer.clear" } +func (c OutputAudioBufferCleared) Default() OutputAudioBufferCleared { + return "output_audio_buffer.cleared" +} +func (c OutputAudioBufferStarted) Default() OutputAudioBufferStarted { + return "output_audio_buffer.started" +} +func (c OutputAudioBufferStopped) Default() OutputAudioBufferStopped { + return "output_audio_buffer.stopped" +} func (c OutputText) Default() OutputText { return "output_text" } +func (c ProtocolError) Default() ProtocolError { return "protocol_error" } func (c Python) Default() Python { return "python" } +func (c RateLimitsUpdated) Default() RateLimitsUpdated { return "rate_limits.updated" } +func (c Realtime) Default() Realtime { return "realtime" } +func (c RealtimeCallIncoming) Default() RealtimeCallIncoming { return "realtime.call.incoming" } func (c Reasoning) Default() Reasoning { return "reasoning" } func (c ReasoningText) Default() ReasoningText { return "reasoning_text" } func (c Refusal) Default() Refusal { return "refusal" } @@ -342,6 +468,7 @@ func (c ResponseAudioTranscriptDelta) Default() ResponseAudioTranscriptDelta { func (c ResponseAudioTranscriptDone) Default() ResponseAudioTranscriptDone { return "response.audio.transcript.done" } +func (c ResponseCancel) Default() ResponseCancel { return "response.cancel" } func (c ResponseCancelled) Default() ResponseCancelled { return "response.cancelled" } func (c ResponseCodeInterpreterCallCodeDelta) Default() ResponseCodeInterpreterCallCodeDelta { return "response.code_interpreter_call_code.delta" @@ -365,6 +492,7 @@ func (c ResponseContentPartAdded) Default() ResponseContentPartAdded { func (c ResponseContentPartDone) Default() ResponseContentPartDone { return "response.content_part.done" } +func (c ResponseCreate) Default() ResponseCreate { return "response.create" } func (c ResponseCreated) Default() ResponseCreated { return "response.created" } func (c ResponseCustomToolCallInputDelta) Default() ResponseCustomToolCallInputDelta { return "response.custom_tool_call_input.delta" @@ -372,6 +500,7 @@ func (c ResponseCustomToolCallInputDelta) Default() ResponseCustomToolCallInputD func (c ResponseCustomToolCallInputDone) Default() ResponseCustomToolCallInputDone { return "response.custom_tool_call_input.done" } +func (c ResponseDone) Default() ResponseDone { return "response.done" } func (c ResponseFailed) Default() ResponseFailed { return "response.failed" } func (c ResponseFileSearchCallCompleted) Default() ResponseFileSearchCallCompleted { return "response.file_search_call.completed" @@ -424,6 +553,18 @@ func (c ResponseMcpListToolsFailed) Default() ResponseMcpListToolsFailed { func (c ResponseMcpListToolsInProgress) Default() ResponseMcpListToolsInProgress { return "response.mcp_list_tools.in_progress" } +func (c ResponseOutputAudioTranscriptDelta) Default() ResponseOutputAudioTranscriptDelta { + return "response.output_audio_transcript.delta" +} +func (c ResponseOutputAudioTranscriptDone) Default() ResponseOutputAudioTranscriptDone { + return "response.output_audio_transcript.done" +} +func (c ResponseOutputAudioDelta) Default() ResponseOutputAudioDelta { + return "response.output_audio.delta" +} +func (c ResponseOutputAudioDone) Default() ResponseOutputAudioDone { + return "response.output_audio.done" +} func (c ResponseOutputItemAdded) Default() ResponseOutputItemAdded { return "response.output_item.added" } @@ -465,10 +606,14 @@ func (c ResponseWebSearchCallInProgress) Default() ResponseWebSearchCallInProgre func (c ResponseWebSearchCallSearching) Default() ResponseWebSearchCallSearching { return "response.web_search_call.searching" } +func (c RetentionRatio) Default() RetentionRatio { return "retention_ratio" } func (c ScoreModel) Default() ScoreModel { return "score_model" } func (c Screenshot) Default() Screenshot { return "screenshot" } func (c Scroll) Default() Scroll { return "scroll" } func (c Search) Default() Search { return "search" } +func (c SessionCreated) Default() SessionCreated { return "session.created" } +func (c SessionUpdate) Default() SessionUpdate { return "session.update" } +func (c SessionUpdated) Default() SessionUpdated { return "session.updated" } func (c Static) Default() Static { return "static" } func (c StringCheck) Default() StringCheck { return "string_check" } func (c SubmitToolOutputs) Default() SubmitToolOutputs { return "submit_tool_outputs" } @@ -517,17 +662,28 @@ func (c ThreadRunStepInProgress) Default() ThreadRunStepInProgress { func (c Tokens) Default() Tokens { return "tokens" } func (c Tool) Default() Tool { return "tool" } func (c ToolCalls) Default() ToolCalls { return "tool_calls" } +func (c ToolExecutionError) Default() ToolExecutionError { return "tool_execution_error" } func (c TranscriptTextDelta) Default() TranscriptTextDelta { return "transcript.text.delta" } func (c TranscriptTextDone) Default() TranscriptTextDone { return "transcript.text.done" } -func (c Type) Default() Type { return "type" } -func (c Upload) Default() Upload { return "upload" } -func (c UploadPart) Default() UploadPart { return "upload.part" } -func (c URL) Default() URL { return "url" } -func (c URLCitation) Default() URLCitation { return "url_citation" } -func (c User) Default() User { return "user" } -func (c VectorStore) Default() VectorStore { return "vector_store" } -func (c VectorStoreDeleted) Default() VectorStoreDeleted { return "vector_store.deleted" } -func (c VectorStoreFile) Default() VectorStoreFile { return "vector_store.file" } +func (c Transcription) Default() Transcription { return "transcription" } +func (c TranscriptionSessionCreated) Default() TranscriptionSessionCreated { + return "transcription_session.created" +} +func (c TranscriptionSessionUpdate) Default() TranscriptionSessionUpdate { + return "transcription_session.update" +} +func (c TranscriptionSessionUpdated) Default() TranscriptionSessionUpdated { + return "transcription_session.updated" +} +func (c Type) Default() Type { return "type" } +func (c Upload) Default() Upload { return "upload" } +func (c UploadPart) Default() UploadPart { return "upload.part" } +func (c URL) Default() URL { return "url" } +func (c URLCitation) Default() URLCitation { return "url_citation" } +func (c User) Default() User { return "user" } +func (c VectorStore) Default() VectorStore { return "vector_store" } +func (c VectorStoreDeleted) Default() VectorStoreDeleted { return "vector_store.deleted" } +func (c VectorStoreFile) Default() VectorStoreFile { return "vector_store.file" } func (c VectorStoreFileContentPage) Default() VectorStoreFileContentPage { return "vector_store.file_content.page" } @@ -540,31 +696,54 @@ func (c Wait) Default() Wait { return "wait" } func (c Wandb) Default() Wandb { return "wandb" } func (c WebSearchCall) Default() WebSearchCall { return "web_search_call" } -func (c AllowedTools) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Approximate) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Assistant) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AssistantDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Auto) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Batch) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BatchCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BatchCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BatchExpired) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BatchFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ChatCompletion) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ChatCompletionChunk) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ChatCompletionDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CheckpointPermission) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Click) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeInterpreter) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeInterpreterCall) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ComputerCallOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ComputerScreenshot) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ComputerUsePreview) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContainerFileCitation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContainerFile) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Content) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Conversation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ConversationDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AllowedTools) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Approximate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Assistant) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AssistantDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Auto) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Batch) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BatchCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BatchCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BatchExpired) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BatchFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ChatCompletion) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ChatCompletionChunk) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ChatCompletionDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CheckpointPermission) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Click) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeInterpreter) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeInterpreterCall) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ComputerCallOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ComputerScreenshot) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ComputerUsePreview) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContainerFileCitation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContainerFile) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Content) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Conversation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemCreate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemDelete) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemInputAudioTranscriptionCompleted) MarshalJSON() ([]byte, error) { + return marshalString(c) +} +func (c ConversationItemInputAudioTranscriptionDelta) MarshalJSON() ([]byte, error) { + return marshalString(c) +} +func (c ConversationItemInputAudioTranscriptionFailed) MarshalJSON() ([]byte, error) { + return marshalString(c) +} +func (c ConversationItemInputAudioTranscriptionSegment) MarshalJSON() ([]byte, error) { + return marshalString(c) +} +func (c ConversationItemRetrieve) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemRetrieved) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemTruncate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ConversationItemTruncated) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c CreatedAt) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Custom) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c CustomToolCall) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -595,6 +774,7 @@ func (c Function) MarshalJSON() ([]byte, error) { r func (c FunctionCall) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c FunctionCallOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Grammar) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c HTTPError) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Image) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ImageEditCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ImageEditPartialImage) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -604,7 +784,16 @@ func (c ImageGenerationCall) MarshalJSON() ([]byte, error) { r func (c ImageGenerationCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ImageGenerationPartialImage) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ImageURL) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Inf) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c InputAudio) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferAppend) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferClear) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferCleared) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferCommit) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferCommitted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferSpeechStarted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferSpeechStopped) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputAudioBufferTimeoutTriggered) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c InputFile) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c InputImage) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c InputText) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -623,6 +812,10 @@ func (c McpApprovalRequest) MarshalJSON() ([]byte, error) { r func (c McpApprovalResponse) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c McpCall) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c McpListTools) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c McpListToolsCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c McpListToolsFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c McpListToolsInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c McpToolCall) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Message) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c MessageCreation) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Model) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -631,8 +824,16 @@ func (c Multi) MarshalJSON() ([]byte, error) { r func (c OpenPage) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Other) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c OutputAudio) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c OutputAudioBufferClear) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c OutputAudioBufferCleared) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c OutputAudioBufferStarted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c OutputAudioBufferStopped) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c OutputText) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ProtocolError) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Python) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c RateLimitsUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Realtime) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c RealtimeCallIncoming) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Reasoning) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ReasoningText) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Refusal) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -641,6 +842,7 @@ func (c ResponseAudioDelta) MarshalJSON() ([]byte, error) { r func (c ResponseAudioDone) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseAudioTranscriptDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseAudioTranscriptDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseCancel) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseCodeInterpreterCallCodeDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseCodeInterpreterCallCodeDone) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -652,9 +854,11 @@ func (c ResponseCodeInterpreterCallInterpreting) MarshalJSON() ([]byte, error) { func (c ResponseCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseContentPartAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseContentPartDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseCreate) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseCustomToolCallInputDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseCustomToolCallInputDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseDone) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseFileSearchCallCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ResponseFileSearchCallInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -667,95 +871,108 @@ func (c ResponseImageGenerationCallInProgress) MarshalJSON() ([]byte, error) { r func (c ResponseImageGenerationCallPartialImage) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseIncomplete) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpCallArgumentsDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpCallArgumentsDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpCallCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpCallFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpCallInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpListToolsCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpListToolsFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseMcpListToolsInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseOutputItemAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseOutputItemDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseOutputTextAnnotationAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseOutputTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseOutputTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseQueued) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseReasoningSummaryPartAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseReasoningSummaryPartDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseReasoningSummaryTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseReasoningSummaryTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseReasoningTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseReasoningTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseRefusalDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseRefusalDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseWebSearchCallCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseWebSearchCallInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ResponseWebSearchCallSearching) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ScoreModel) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Screenshot) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Scroll) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Search) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Static) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c StringCheck) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c SubmitToolOutputs) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c SummaryText) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c System) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Text) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextCompletion) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextSimilarity) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Thread) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessage) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessageCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessageCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessageDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessageDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessageInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadMessageIncomplete) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRun) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunCancelling) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunExpired) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunIncomplete) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunQueued) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunRequiresAction) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStep) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepExpired) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ThreadRunStepInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Tokens) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Tool) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ToolCalls) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TranscriptTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TranscriptTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Type) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Upload) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c UploadPart) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c URL) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c URLCitation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c User) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStore) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStoreDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStoreFile) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStoreFileContentPage) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStoreFileDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStoreFilesBatch) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c VectorStoreSearchResultsPage) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Wait) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Wandb) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c WebSearchCall) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseIncomplete) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpCallArgumentsDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpCallArgumentsDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpCallCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpCallFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpCallInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpListToolsCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpListToolsFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseMcpListToolsInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputAudioTranscriptDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputAudioTranscriptDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputAudioDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputAudioDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputItemAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputItemDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputTextAnnotationAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseOutputTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseQueued) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseReasoningSummaryPartAdded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseReasoningSummaryPartDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseReasoningSummaryTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseReasoningSummaryTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseReasoningTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseReasoningTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseRefusalDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseRefusalDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseWebSearchCallCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseWebSearchCallInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ResponseWebSearchCallSearching) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c RetentionRatio) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ScoreModel) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Screenshot) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Scroll) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Search) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionUpdate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Static) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c StringCheck) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SubmitToolOutputs) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SummaryText) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c System) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Text) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextCompletion) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextSimilarity) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Thread) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessage) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessageCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessageCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessageDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessageDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessageInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadMessageIncomplete) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRun) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunCancelling) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunExpired) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunIncomplete) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunQueued) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunRequiresAction) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStep) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepCancelled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepExpired) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ThreadRunStepInProgress) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Tokens) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Tool) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ToolCalls) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ToolExecutionError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TranscriptTextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TranscriptTextDone) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Transcription) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TranscriptionSessionCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TranscriptionSessionUpdate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TranscriptionSessionUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Type) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Upload) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c UploadPart) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c URL) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c URLCitation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c User) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStore) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStoreDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStoreFile) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStoreFileContentPage) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStoreFileDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStoreFilesBatch) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VectorStoreSearchResultsPage) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Wait) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Wandb) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WebSearchCall) MarshalJSON() ([]byte, error) { return marshalString(c) } type constant[T any] interface { Constant[T] diff --git a/webhooks/webhook.go b/webhooks/webhook.go index 2ade2618..94d35551 100644 --- a/webhooks/webhook.go +++ b/webhooks/webhook.go @@ -767,6 +767,87 @@ const ( FineTuningJobSucceededWebhookEventObjectEvent FineTuningJobSucceededWebhookEventObject = "event" ) +// Sent when Realtime API Receives a incoming SIP call. +type RealtimeCallIncomingWebhookEvent struct { + // The unique ID of the event. + ID string `json:"id,required"` + // The Unix timestamp (in seconds) of when the model response was completed. + CreatedAt int64 `json:"created_at,required"` + // Event data payload. + Data RealtimeCallIncomingWebhookEventData `json:"data,required"` + // The type of the event. Always `realtime.call.incoming`. + Type constant.RealtimeCallIncoming `json:"type,required"` + // The object of the event. Always `event`. + // + // Any of "event". + Object RealtimeCallIncomingWebhookEventObject `json:"object"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + Data respjson.Field + Type respjson.Field + Object respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeCallIncomingWebhookEvent) RawJSON() string { return r.JSON.raw } +func (r *RealtimeCallIncomingWebhookEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Event data payload. +type RealtimeCallIncomingWebhookEventData struct { + // The unique ID of this call. + CallID string `json:"call_id,required"` + // Headers from the SIP Invite. + SipHeaders []RealtimeCallIncomingWebhookEventDataSipHeader `json:"sip_headers,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CallID respjson.Field + SipHeaders respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeCallIncomingWebhookEventData) RawJSON() string { return r.JSON.raw } +func (r *RealtimeCallIncomingWebhookEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A header from the SIP Invite. +type RealtimeCallIncomingWebhookEventDataSipHeader struct { + // Name of the SIP Header. + Name string `json:"name,required"` + // Value of the SIP Header. + Value string `json:"value,required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Name respjson.Field + Value respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r RealtimeCallIncomingWebhookEventDataSipHeader) RawJSON() string { return r.JSON.raw } +func (r *RealtimeCallIncomingWebhookEventDataSipHeader) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The object of the event. Always `event`. +type RealtimeCallIncomingWebhookEventObject string + +const ( + RealtimeCallIncomingWebhookEventObjectEvent RealtimeCallIncomingWebhookEventObject = "event" +) + // Sent when a background response has been cancelled. type ResponseCancelledWebhookEvent struct { // The unique ID of the event. @@ -1001,8 +1082,9 @@ const ( // [EvalRunCanceledWebhookEvent], [EvalRunFailedWebhookEvent], // [EvalRunSucceededWebhookEvent], [FineTuningJobCancelledWebhookEvent], // [FineTuningJobFailedWebhookEvent], [FineTuningJobSucceededWebhookEvent], -// [ResponseCancelledWebhookEvent], [ResponseCompletedWebhookEvent], -// [ResponseFailedWebhookEvent], [ResponseIncompleteWebhookEvent]. +// [RealtimeCallIncomingWebhookEvent], [ResponseCancelledWebhookEvent], +// [ResponseCompletedWebhookEvent], [ResponseFailedWebhookEvent], +// [ResponseIncompleteWebhookEvent]. // // Use the [UnwrapWebhookEventUnion.AsAny] method to switch on the variant. // @@ -1015,15 +1097,16 @@ type UnwrapWebhookEventUnion struct { // [BatchFailedWebhookEventData], [EvalRunCanceledWebhookEventData], // [EvalRunFailedWebhookEventData], [EvalRunSucceededWebhookEventData], // [FineTuningJobCancelledWebhookEventData], [FineTuningJobFailedWebhookEventData], - // [FineTuningJobSucceededWebhookEventData], [ResponseCancelledWebhookEventData], + // [FineTuningJobSucceededWebhookEventData], + // [RealtimeCallIncomingWebhookEventData], [ResponseCancelledWebhookEventData], // [ResponseCompletedWebhookEventData], [ResponseFailedWebhookEventData], // [ResponseIncompleteWebhookEventData] Data UnwrapWebhookEventUnionData `json:"data"` // Any of "batch.cancelled", "batch.completed", "batch.expired", "batch.failed", // "eval.run.canceled", "eval.run.failed", "eval.run.succeeded", // "fine_tuning.job.cancelled", "fine_tuning.job.failed", - // "fine_tuning.job.succeeded", "response.cancelled", "response.completed", - // "response.failed", "response.incomplete". + // "fine_tuning.job.succeeded", "realtime.call.incoming", "response.cancelled", + // "response.completed", "response.failed", "response.incomplete". Type string `json:"type"` Object string `json:"object"` JSON struct { @@ -1053,6 +1136,7 @@ func (EvalRunSucceededWebhookEvent) implUnwrapWebhookEventUnion() {} func (FineTuningJobCancelledWebhookEvent) implUnwrapWebhookEventUnion() {} func (FineTuningJobFailedWebhookEvent) implUnwrapWebhookEventUnion() {} func (FineTuningJobSucceededWebhookEvent) implUnwrapWebhookEventUnion() {} +func (RealtimeCallIncomingWebhookEvent) implUnwrapWebhookEventUnion() {} func (ResponseCancelledWebhookEvent) implUnwrapWebhookEventUnion() {} func (ResponseCompletedWebhookEvent) implUnwrapWebhookEventUnion() {} func (ResponseFailedWebhookEvent) implUnwrapWebhookEventUnion() {} @@ -1071,6 +1155,7 @@ func (ResponseIncompleteWebhookEvent) implUnwrapWebhookEventUnion() {} // case webhooks.FineTuningJobCancelledWebhookEvent: // case webhooks.FineTuningJobFailedWebhookEvent: // case webhooks.FineTuningJobSucceededWebhookEvent: +// case webhooks.RealtimeCallIncomingWebhookEvent: // case webhooks.ResponseCancelledWebhookEvent: // case webhooks.ResponseCompletedWebhookEvent: // case webhooks.ResponseFailedWebhookEvent: @@ -1100,6 +1185,8 @@ func (u UnwrapWebhookEventUnion) AsAny() anyUnwrapWebhookEvent { return u.AsFineTuningJobFailed() case "fine_tuning.job.succeeded": return u.AsFineTuningJobSucceeded() + case "realtime.call.incoming": + return u.AsRealtimeCallIncoming() case "response.cancelled": return u.AsResponseCancelled() case "response.completed": @@ -1162,6 +1249,11 @@ func (u UnwrapWebhookEventUnion) AsFineTuningJobSucceeded() (v FineTuningJobSucc return } +func (u UnwrapWebhookEventUnion) AsRealtimeCallIncoming() (v RealtimeCallIncomingWebhookEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u UnwrapWebhookEventUnion) AsResponseCancelled() (v ResponseCancelledWebhookEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return @@ -1196,10 +1288,16 @@ func (r *UnwrapWebhookEventUnion) UnmarshalJSON(data []byte) error { // For type safety it is recommended to directly use a variant of the // [UnwrapWebhookEventUnion]. type UnwrapWebhookEventUnionData struct { - ID string `json:"id"` - JSON struct { - ID respjson.Field - raw string + ID string `json:"id"` + // This field is from variant [RealtimeCallIncomingWebhookEventData]. + CallID string `json:"call_id"` + // This field is from variant [RealtimeCallIncomingWebhookEventData]. + SipHeaders []RealtimeCallIncomingWebhookEventDataSipHeader `json:"sip_headers"` + JSON struct { + ID respjson.Field + CallID respjson.Field + SipHeaders respjson.Field + raw string } `json:"-"` } From 30db6c914bd298530340a47aef1a9e65c877dcc7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Sep 2025 05:06:47 +0000 Subject: [PATCH 10/10] release: 2.2.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 24 ++++++++++++++++++++++++ README.md | 2 +- internal/version.go | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 19588bdd..bfc26f9c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.1.1" + ".": "2.2.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a09ef5ee..6e46138c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 2.2.0 (2025-09-02) + +Full Changelog: [v2.1.1...v2.2.0](https://github.com/openai/openai-go/compare/v2.1.1...v2.2.0) + +### Features + +* **api:** Add connectors support for MCP tool ([35888bc](https://github.com/openai/openai-go/commit/35888bcd26c7633e8ea68f9213cc3977b8ac49eb)) +* **api:** add web search filters ([6f2c71d](https://github.com/openai/openai-go/commit/6f2c71d4e28971fc73e7e291d40f3b875d9cc42a)) +* **api:** adding support for /v1/conversations to the API ([5b7c31b](https://github.com/openai/openai-go/commit/5b7c31bde9c1086d3fb71c88dfdf74228845b22e)) +* **api:** realtime API updates ([130fc8e](https://github.com/openai/openai-go/commit/130fc8ea5ba39e6c1457ed6d26ef827d931a6242)) +* **client:** add support for verifying signatures on incoming webhooks ([f7c8dbb](https://github.com/openai/openai-go/commit/f7c8dbb6b5bd5bab72b7d146dc255d543b0b5a71)) + + +### Bug Fixes + +* **azure:** compatibility with edit image endpoint ([#477](https://github.com/openai/openai-go/issues/477)) ([d156eec](https://github.com/openai/openai-go/commit/d156eeca37bc86a5d8e1c973063a8425744810f1)) +* close body before retrying ([8dfed35](https://github.com/openai/openai-go/commit/8dfed35f11a00970ad804ab985cf393c2332ea8f)) + + +### Chores + +* **internal/ci:** setup breaking change detection ([0af0cd0](https://github.com/openai/openai-go/commit/0af0cd01302d3859a4e43554ed8e665007f69aad)) +* **internal:** version bump ([3265795](https://github.com/openai/openai-go/commit/3265795fffa44fb40d65a800b300807d9f1e7b2b)) + ## 2.1.1 (2025-08-20) Full Changelog: [v2.1.0...v2.1.1](https://github.com/openai/openai-go/compare/v2.1.0...v2.1.1) diff --git a/README.md b/README.md index a1f90fac..e3bc785b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Or to pin the version: ```sh -go get -u 'github.com/openai/openai-go/v2@v2.1.1' +go get -u 'github.com/openai/openai-go/v2@v2.2.0' ``` diff --git a/internal/version.go b/internal/version.go index e670ce25..0759debd 100644 --- a/internal/version.go +++ b/internal/version.go @@ -2,4 +2,4 @@ package internal -const PackageVersion = "2.1.1" // x-release-please-version +const PackageVersion = "2.2.0" // x-release-please-version