diff --git a/clients/python/llmengine/data_types/gen/openai.py b/clients/python/llmengine/data_types/gen/openai.py index 86177079f..37752fc17 100644 --- a/clients/python/llmengine/data_types/gen/openai.py +++ b/clients/python/llmengine/data_types/gen/openai.py @@ -1,18877 +1,4438 @@ # mypy: ignore-errors # generated by datamodel-codegen: # filename: openai-spec.yaml -# timestamp: 2025-12-02T21:52:25+00:00 +# timestamp: 2024-08-22T02:56:18+00:00 from __future__ import annotations -from typing import Annotated, Any, Dict, List, Literal, Optional, Union +from typing import Any, Dict, List, Optional, Union import pydantic -# isort: off -if hasattr(pydantic, "VERSION") and pydantic.VERSION.startswith("2."): +PYDANTIC_V2 = hasattr(pydantic, "VERSION") and pydantic.VERSION.startswith("2.") +if PYDANTIC_V2: from pydantic.v1 import AnyUrl, BaseModel, Extra, Field # noqa: F401 else: from pydantic import AnyUrl, BaseModel, Extra, Field # type: ignore # noqa: F401 -# isort: on +from typing_extensions import Annotated, Literal -class AddUploadPartRequest(BaseModel): - class Config: - extra = Extra.forbid +class Error(BaseModel): + code: str + message: str + param: str + type: str + - data: Annotated[bytes, Field(description='The chunk of bytes for this Part.\n')] +class ErrorResponse(BaseModel): + error: Error -class Owner(BaseModel): - type: Annotated[ - Optional[str], Field(description='Always `user`', example='user') - ] = None - object: Annotated[ - Optional[str], +class DeleteModelResponse(BaseModel): + id: str + deleted: bool + object: str + + +class Prompt(BaseModel): + __root__: Annotated[ + Optional[List[int]], Field( - description='The object type, which is always organization.user', - example='organization.user', + description="The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n", + example="[1212, 318, 257, 1332, 13]", + min_items=1, ), - ] = None - id: Annotated[ - Optional[str], + ] = "<|endoftext|>" + + +class Prompt1Item(BaseModel): + __root__: Annotated[List[int], Field(min_items=1)] + + +class Prompt1(BaseModel): + __root__: Annotated[ + Optional[List[Prompt1Item]], Field( - description='The identifier, which can be referenced in API endpoints', - example='sa_456', + description="The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n", + example="[[1212, 318, 257, 1332, 13]]", + min_items=1, ), - ] = None - name: Annotated[ - Optional[str], - Field(description='The name of the user', example='My Service Account'), - ] = None - created_at: Annotated[ - Optional[int], + ] = "<|endoftext|>" + + +class Stop(BaseModel): + __root__: Annotated[ + Optional[List[str]], Field( - description='The Unix timestamp (in seconds) of when the user was created', - example=1711471533, + description="Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.\n", + max_items=4, + min_items=1, ), ] = None - role: Annotated[ - Optional[str], Field(description='Always `owner`', example='owner') - ] = None -class AdminApiKey(BaseModel): - object: Annotated[ - str, +class Logprobs(BaseModel): + text_offset: Optional[List[int]] = None + token_logprobs: Optional[List[float]] = None + tokens: Optional[List[str]] = None + top_logprobs: Optional[List[Dict[str, float]]] = None + + +class Choice(BaseModel): + finish_reason: Annotated[ + Literal["stop", "length", "content_filter"], Field( - description='The object type, which is always `organization.admin_api_key`', - example='organization.admin_api_key', + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\nor `content_filter` if content was omitted due to a flag from our content filters.\n" ), ] - id: Annotated[ - str, + index: int + logprobs: Logprobs + text: str + + +class ChatCompletionRequestMessageContentPartText(BaseModel): + type: Annotated[Literal["text"], Field(description="The type of the content part.")] + text: Annotated[str, Field(description="The text content.")] + + +class ImageUrl(BaseModel): + url: Annotated[ + AnyUrl, + Field(description="Either a URL of the image or the base64 encoded image data."), + ] + detail: Annotated[ + Optional[Literal["auto", "low", "high"]], Field( - description='The identifier, which can be referenced in API endpoints', - example='key_abc', + description="Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding)." ), + ] = "auto" + + +class ChatCompletionRequestMessageContentPartImage(BaseModel): + type: Annotated[Literal["image_url"], Field(description="The type of the content part.")] + image_url: ImageUrl + + +class ChatCompletionRequestMessageContentPartRefusal(BaseModel): + type: Annotated[Literal["refusal"], Field(description="The type of the content part.")] + refusal: Annotated[str, Field(description="The refusal message generated by the model.")] + + +class ChatCompletionRequestSystemMessageContentPart(BaseModel): + __root__: ChatCompletionRequestMessageContentPartText + + +class ChatCompletionRequestUserMessageContentPart(BaseModel): + __root__: Union[ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartImage, ] - name: Annotated[ - str, Field(description='The name of the API key', example='Administration Key') + + +class ChatCompletionRequestAssistantMessageContentPart(BaseModel): + __root__: Union[ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartRefusal, ] - redacted_value: Annotated[ - str, + + +class ChatCompletionRequestToolMessageContentPart(BaseModel): + __root__: ChatCompletionRequestMessageContentPartText + + +class Content(BaseModel): + __root__: Annotated[ + List[ChatCompletionRequestSystemMessageContentPart], Field( - description='The redacted value of the API key', example='sk-admin...def' + description="An array of content parts with a defined type. For system messages, only type `text` is supported.", + min_items=1, + title="Array of content parts", ), ] - value: Annotated[ + + +class ChatCompletionRequestSystemMessage(BaseModel): + content: Annotated[ + Union[str, Content], Field(description="The contents of the system message.") + ] + role: Annotated[ + Literal["system"], + Field(description="The role of the messages author, in this case `system`."), + ] + name: Annotated[ Optional[str], Field( - description='The value of the API key. Only shown on create.', - example='sk-admin-1234abcd', + description="An optional name for the participant. Provides the model information to differentiate between participants of the same role." ), ] = None - created_at: Annotated[ - int, + + +class Content1(BaseModel): + __root__: Annotated[ + List[ChatCompletionRequestUserMessageContentPart], Field( - description='The Unix timestamp (in seconds) of when the API key was created', - example=1711471533, + description="An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4o` model.", + min_items=1, + title="Array of content parts", ), ] - last_used_at: Optional[int] - owner: Owner - - -class ApiKeyList(BaseModel): - object: Annotated[Optional[str], Field(example='list')] = None - data: Optional[List[AdminApiKey]] = None - has_more: Annotated[Optional[bool], Field(example=False)] = None - first_id: Annotated[Optional[str], Field(example='key_abc')] = None - last_id: Annotated[Optional[str], Field(example='key_xyz')] = None -class AssignedRoleDetails(BaseModel): - id: Annotated[str, Field(description='Identifier for the role.')] - name: Annotated[str, Field(description='Name of the role.')] - permissions: Annotated[ - List[str], Field(description='Permissions associated with the role.') - ] - resource_type: Annotated[ - str, Field(description='Resource type the role applies to.') - ] - predefined_role: Annotated[ - bool, Field(description='Whether the role is predefined by OpenAI.') - ] - description: Annotated[Optional[str], Field(description='Description of the role.')] - created_at: Annotated[ - Optional[int], Field(description='When the role was created.') +class ChatCompletionRequestUserMessage(BaseModel): + content: Annotated[ + Union[str, Content1], Field(description="The contents of the user message.\n") ] - updated_at: Annotated[ - Optional[int], Field(description='When the role was last updated.') + role: Annotated[ + Literal["user"], + Field(description="The role of the messages author, in this case `user`."), ] - created_by: Annotated[ + name: Annotated[ Optional[str], - Field(description='Identifier of the actor who created the role.'), - ] - created_by_user_obj: Annotated[ - Optional[Dict[str, Any]], Field( - description='User details for the actor that created the role, when available.' + description="An optional name for the participant. Provides the model information to differentiate between participants of the same role." ), - ] - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Arbitrary metadata stored on the role.'), - ] + ] = None -class Name(BaseModel): +class Content2(BaseModel): __root__: Annotated[ - str, + Optional[List[ChatCompletionRequestAssistantMessageContentPart]], Field( - description='The name of the assistant. The maximum length is 256 characters.\n', - max_length=256, + description="An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.", + min_items=1, + title="Array of content parts", ), - ] + ] = None -class Description(BaseModel): - __root__: Annotated[ +class FunctionCall(BaseModel): + arguments: Annotated[ str, Field( - description='The description of the assistant. The maximum length is 512 characters.\n', - max_length=512, + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." ), ] + name: Annotated[str, Field(description="The name of the function to call.")] -class Instructions(BaseModel): +class Content3(BaseModel): __root__: Annotated[ - str, + List[ChatCompletionRequestToolMessageContentPart], Field( - description='The system instructions that the assistant uses. The maximum length is 256,000 characters.\n', - max_length=256000, + description="An array of content parts with a defined type. For tool messages, only type `text` is supported.", + min_items=1, + title="Array of content parts", ), ] -class CodeInterpreter(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n', - max_items=20, - ), - ] = [] +class ChatCompletionRequestToolMessage(BaseModel): + role: Annotated[ + Literal["tool"], + Field(description="The role of the messages author, in this case `tool`."), + ] + content: Annotated[Union[str, Content3], Field(description="The contents of the tool message.")] + tool_call_id: Annotated[str, Field(description="Tool call that this message is responding to.")] -class FileSearch(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] = None +class ChatCompletionRequestFunctionMessage(BaseModel): + role: Annotated[ + Literal["function"], + Field(description="The role of the messages author, in this case `function`."), + ] + content: Annotated[str, Field(description="The contents of the function message.")] + name: Annotated[str, Field(description="The name of the function to call.")] -class ToolResources(BaseModel): - code_interpreter: Optional[CodeInterpreter] = None - file_search: Optional[FileSearch] = None +class FunctionParameters(BaseModel): + pass + + class Config: + extra = Extra.allow -class Temperature(BaseModel): - __root__: Annotated[ - float, +class ChatCompletionFunctions(BaseModel): + description: Annotated[ + Optional[str], Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - example=1, - ge=0.0, - le=2.0, + description="A description of what the function does, used by the model to choose when and how to call the function." + ), + ] = None + name: Annotated[ + str, + Field( + description="The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." ), ] + parameters: Optional[FunctionParameters] = None -class TopP(BaseModel): - __root__: Annotated[ - float, +class ChatCompletionFunctionCallOption(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] + + +class FunctionObject(BaseModel): + description: Annotated[ + Optional[str], Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - example=1, - ge=0.0, - le=1.0, + description="A description of what the function does, used by the model to choose when and how to call the function." + ), + ] = None + name: Annotated[ + str, + Field( + description="The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." ), ] + parameters: Optional[FunctionParameters] = None + strict: Annotated[ + Optional[bool], + Field( + description="Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling)." + ), + ] = False -class AssistantSupportedModels(BaseModel): - __root__: Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'o3-mini', - 'o3-mini-2025-01-31', - 'o1', - 'o1-2024-12-17', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', +class ResponseFormatText(BaseModel): + type: Annotated[ + Literal["text"], + Field(description="The type of response format being defined: `text`"), ] -class AssistantToolsCode(BaseModel): +class ResponseFormatJsonObject(BaseModel): type: Annotated[ - Literal['AssistantToolsCode'], - Field(description='The type of tool being defined: `code_interpreter`'), + Literal["json_object"], + Field(description="The type of response format being defined: `json_object`"), ] -class AssistantToolsFileSearchTypeOnly(BaseModel): +class ResponseFormatJsonSchemaSchema(BaseModel): + pass + + class Config: + extra = Extra.allow + + +class JsonSchema(BaseModel): + description: Annotated[ + Optional[str], + Field( + description="A description of what the response format is for, used by the model to determine how to respond in the format." + ), + ] = None + name: Annotated[ + str, + Field( + description="The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." + ), + ] + schema_: Annotated[Optional[ResponseFormatJsonSchemaSchema], Field(alias="schema")] = None + strict: Annotated[ + Optional[bool], + Field( + description="Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs)." + ), + ] = False + + +class ResponseFormatJsonSchema(BaseModel): type: Annotated[ - Literal['AssistantToolsFileSearchTypeOnly'], - Field(description='The type of tool being defined: `file_search`'), + Literal["json_schema"], + Field(description="The type of response format being defined: `json_schema`"), ] + json_schema: JsonSchema class Function(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] + name: Annotated[str, Field(description="The name of the function to call.")] -class AssistantsNamedToolChoice(BaseModel): +class ChatCompletionNamedToolChoice(BaseModel): type: Annotated[ - Literal['function', 'code_interpreter', 'file_search'], - Field( - description='The type of the tool. If type is `function`, the function name must be set' - ), + Literal["function"], + Field(description="The type of the tool. Currently, only `function` is supported."), ] - function: Optional[Function] = None + function: Function -class AudioResponseFormat(BaseModel): +class ParallelToolCalls(BaseModel): __root__: Annotated[ - Literal['json', 'text', 'srt', 'verbose_json', 'vtt', 'diarized_json'], + bool, Field( - description='The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, `vtt`, or `diarized_json`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. For `gpt-4o-transcribe-diarize`, the supported formats are `json`, `text`, and `diarized_json`, with `diarized_json` required to receive speaker annotations.\n' + description="Whether to enable [parallel function calling](/docs/guides/function-calling/parallel-function-calling) during tool use." ), ] -class AudioTranscription(BaseModel): - model: Annotated[ - Optional[ - Literal[ - 'whisper-1', - 'gpt-4o-mini-transcribe', - 'gpt-4o-transcribe', - 'gpt-4o-transcribe-diarize', - ] - ], - Field( - description='The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, and `gpt-4o-transcribe-diarize`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n' - ), - ] = None - language: Annotated[ - Optional[str], - Field( - description='The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n' - ), - ] = None - prompt: Annotated[ - Optional[str], +class Function1(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] + arguments: Annotated[ + str, Field( - description='An optional text to guide the model\'s style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example "expect words related to technology".\n' + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." ), - ] = None + ] -class Project(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - name: Annotated[Optional[str], Field(description='The project title.')] = None +class ChatCompletionMessageToolCall(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call.")] + type: Annotated[ + Literal["function"], + Field(description="The type of the tool. Currently, only `function` is supported."), + ] + function: Annotated[Function1, Field(description="The function that the model called.")] -class Data(BaseModel): - scopes: Annotated[ - Optional[List[str]], +class Function2(BaseModel): + name: Annotated[Optional[str], Field(description="The name of the function to call.")] = None + arguments: Annotated[ + Optional[str], Field( - description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`' + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." ), ] = None -class ApiKeyCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking ID of the API key.') - ] = None - data: Annotated[ - Optional[Data], Field(description='The payload used to create the API key.') - ] = None - - -class ChangesRequested(BaseModel): - scopes: Annotated[ - Optional[List[str]], - Field( - description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`' - ), +class ChatCompletionMessageToolCallChunk(BaseModel): + index: int + id: Annotated[Optional[str], Field(description="The ID of the tool call.")] = None + type: Annotated[ + Optional[Literal["function"]], + Field(description="The type of the tool. Currently, only `function` is supported."), ] = None + function: Optional[Function2] = None -class ApiKeyUpdated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking ID of the API key.') - ] = None - changes_requested: Annotated[ - Optional[ChangesRequested], - Field(description='The payload used to update the API key.'), - ] = None +class ChatCompletionRole(BaseModel): + __root__: Annotated[ + Literal["system", "user", "assistant", "tool", "function"], + Field(description="The role of the author of a message"), + ] -class ApiKeyDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking ID of the API key.') +class ChatCompletionStreamOptions(BaseModel): + include_usage: Annotated[ + Optional[bool], + Field( + description="If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value.\n" + ), ] = None -class Data1(BaseModel): - project_id: Annotated[ +class FunctionCall2(BaseModel): + arguments: Annotated[ Optional[str], Field( - description='The ID of the project that the checkpoint permission was created for.' + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." ), ] = None - fine_tuned_model_checkpoint: Annotated[ - Optional[str], Field(description='The ID of the fine-tuned model checkpoint.') - ] = None + name: Annotated[Optional[str], Field(description="The name of the function to call.")] = None -class CheckpointPermissionCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the checkpoint permission.') - ] = None - data: Annotated[ - Optional[Data1], - Field(description='The payload used to create the checkpoint permission.'), - ] = None - - -class CheckpointPermissionDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the checkpoint permission.') +class ChatCompletionStreamResponseDelta(BaseModel): + content: Annotated[Optional[str], Field(description="The contents of the chunk message.")] = ( + None + ) + function_call: Annotated[ + Optional[FunctionCall2], + Field( + description="Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + ), ] = None - - -class ExternalKeyRegistered(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the external key configuration.') + tool_calls: Optional[List[ChatCompletionMessageToolCallChunk]] = None + role: Annotated[ + Optional[Literal["system", "user", "assistant", "tool"]], + Field(description="The role of the author of this message."), ] = None - data: Annotated[ - Optional[Dict[str, Any]], - Field(description='The configuration for the external key.'), + refusal: Annotated[ + Optional[str], Field(description="The refusal message generated by the model.") ] = None -class ExternalKeyRemoved(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the external key configuration.') - ] = None +class Stop1(BaseModel): + __root__: Annotated[ + List[str], + Field( + description="Up to 4 sequences where the API will stop generating further tokens.\n", + max_items=4, + min_items=1, + ), + ] -class Data2(BaseModel): - group_name: Annotated[Optional[str], Field(description='The group name.')] = None +class TopLogprob(BaseModel): + token: Annotated[str, Field(description="The token.")] + logprob: Annotated[ + float, + Field( + description="The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + ), + ] + bytes: Annotated[ + List[int], + Field( + description="A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + ), + ] -class GroupCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the group.')] = None - data: Annotated[ - Optional[Data2], Field(description='Information about the created group.') - ] = None +class ChatCompletionTokenLogprob(BaseModel): + token: Annotated[str, Field(description="The token.")] + logprob: Annotated[ + float, + Field( + description="The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + ), + ] + bytes: Annotated[ + List[int], + Field( + description="A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + ), + ] + top_logprobs: Annotated[ + List[TopLogprob], + Field( + description="List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned." + ), + ] -class ChangesRequested1(BaseModel): - group_name: Annotated[ - Optional[str], Field(description='The updated group name.') - ] = None +class Logprobs2(BaseModel): + content: Annotated[ + List[ChatCompletionTokenLogprob], + Field(description="A list of message content tokens with log probability information."), + ] + refusal: Annotated[ + List[ChatCompletionTokenLogprob], + Field(description="A list of message refusal tokens with log probability information."), + ] -class GroupUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the group.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested1], - Field(description='The payload used to update the group.'), +class Choice3(BaseModel): + delta: ChatCompletionStreamResponseDelta + logprobs: Annotated[ + Optional[Logprobs2], + Field(description="Log probability information for the choice."), ] = None + finish_reason: Annotated[ + Literal["stop", "length", "tool_calls", "content_filter", "function_call"], + Field( + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" + ), + ] + index: Annotated[int, Field(description="The index of the choice in the list of choices.")] -class GroupDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the group.')] = None - - -class ScimEnabled(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the SCIM was enabled for.') - ] = None +class Usage(BaseModel): + completion_tokens: Annotated[ + int, Field(description="Number of tokens in the generated completion.") + ] + prompt_tokens: Annotated[int, Field(description="Number of tokens in the prompt.")] + total_tokens: Annotated[ + int, + Field(description="Total number of tokens used in the request (prompt + completion)."), + ] -class ScimDisabled(BaseModel): +class CreateChatCompletionStreamResponse(BaseModel): id: Annotated[ - Optional[str], Field(description='The ID of the SCIM was disabled for.') - ] = None - - -class Data3(BaseModel): - email: Annotated[ - Optional[str], Field(description='The email invited to the organization.') + str, + Field( + description="A unique identifier for the chat completion. Each chunk has the same ID." + ), + ] + choices: Annotated[ + List[Choice3], + Field( + description='A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the\nlast chunk if you set `stream_options: {"include_usage": true}`.\n' + ), + ] + created: Annotated[ + int, + Field( + description="The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp." + ), + ] + model: Annotated[str, Field(description="The model to generate the completion.")] + service_tier: Annotated[ + Optional[Literal["scale", "default"]], + Field( + description="The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.", + example="scale", + ), ] = None - role: Annotated[ + system_fingerprint: Annotated[ Optional[str], Field( - description='The role the email was invited to be. Is either `owner` or `member`.' + description="This fingerprint represents the backend configuration that the model runs with.\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None - - -class InviteSent(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the invite.')] = None - data: Annotated[ - Optional[Data3], Field(description='The payload used to create the invite.') + object: Annotated[ + Literal["chat.completion.chunk"], + Field(description="The object type, which is always `chat.completion.chunk`."), + ] + usage: Annotated[ + Optional[Usage], + Field( + description='An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request.\nWhen present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request.\n' + ), ] = None -class InviteAccepted(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the invite.')] = None - - -class InviteDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the invite.')] = None +class CreateChatCompletionImageResponse(BaseModel): + pass -class IpAllowlistCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the IP allowlist configuration.') - ] = None - allowed_ips: Annotated[ - Optional[List[str]], +class CreateImageRequest(BaseModel): + prompt: Annotated[ + str, Field( - description='The IP addresses or CIDR ranges included in the configuration.' + description="A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.", + example="A cute baby sea otter", ), - ] = None - - -class IpAllowlistUpdated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - allowed_ips: Annotated[ - Optional[List[str]], + ] + model: Annotated[ + Optional[Union[str, Literal["dall-e-2", "dall-e-3"]]], + Field(description="The model to use for image generation.", example="dall-e-3"), + ] = "dall-e-2" + n: Annotated[ + Optional[int], + Field( + description="The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.", + example=1, + ge=1, + le=10, + ), + ] = 1 + quality: Annotated[ + Optional[Literal["standard", "hd"]], Field( - description='The updated set of IP addresses or CIDR ranges in the configuration.' + description="The quality of the image that will be generated. `hd` creates images with finer details and greater consistency across the image. This param is only supported for `dall-e-3`.", + example="standard", ), - ] = None - - -class IpAllowlistDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the IP allowlist configuration.') - ] = None - allowed_ips: Annotated[ - Optional[List[str]], + ] = "standard" + response_format: Annotated[ + Optional[Literal["url", "b64_json"]], + Field( + description="The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.", + example="url", + ), + ] = "url" + size: Annotated[ + Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]], + Field( + description="The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models.", + example="1024x1024", + ), + ] = "1024x1024" + style: Annotated[ + Optional[Literal["vivid", "natural"]], + Field( + description="The style of the generated images. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for `dall-e-3`.", + example="vivid", + ), + ] = "vivid" + user: Annotated[ + Optional[str], Field( - description='The IP addresses or CIDR ranges that were in the configuration.' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + example="user-1234", ), ] = None -class Config(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the IP allowlist configuration.') +class Image(BaseModel): + b64_json: Annotated[ + Optional[str], + Field( + description="The base64-encoded JSON of the generated image, if `response_format` is `b64_json`." + ), ] = None - - -class IpAllowlistConfigActivated(BaseModel): - configs: Annotated[ - Optional[List[Config]], - Field(description='The configurations that were activated.'), + url: Annotated[ + Optional[str], + Field( + description="The URL of the generated image, if `response_format` is `url` (default)." + ), ] = None - - -class IpAllowlistConfigDeactivated(BaseModel): - configs: Annotated[ - Optional[List[Config]], - Field(description='The configurations that were deactivated.'), + revised_prompt: Annotated[ + Optional[str], + Field( + description="The prompt that was used to generate the image, if there was any revision to the prompt." + ), ] = None -class LoginFailed(BaseModel): - error_code: Annotated[ - Optional[str], Field(description='The error code of the failure.') - ] = None - error_message: Annotated[ - Optional[str], Field(description='The error message of the failure.') - ] = None - - -class LogoutFailed(BaseModel): - error_code: Annotated[ - Optional[str], Field(description='The error code of the failure.') - ] = None - error_message: Annotated[ - Optional[str], Field(description='The error message of the failure.') - ] = None - - -class ChangesRequested2(BaseModel): - title: Annotated[Optional[str], Field(description='The organization title.')] = None - description: Annotated[ - Optional[str], Field(description='The organization description.') - ] = None - name: Annotated[Optional[str], Field(description='The organization name.')] = None - threads_ui_visibility: Annotated[ - Optional[str], - Field( - description='Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`.' - ), - ] = None - usage_dashboard_visibility: Annotated[ - Optional[str], - Field( - description='Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`.' - ), - ] = None - api_call_logging: Annotated[ - Optional[str], - Field( - description='How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects`' - ), - ] = None - api_call_logging_project_ids: Annotated[ - Optional[str], - Field( - description='The list of project ids if api_call_logging is set to `enabled_for_selected_projects`' - ), - ] = None - - -class OrganizationUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The organization ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested2], - Field(description='The payload used to update the organization settings.'), - ] = None - - -class Data4(BaseModel): - name: Annotated[Optional[str], Field(description='The project name.')] = None - title: Annotated[ - Optional[str], - Field(description='The title of the project as seen on the dashboard.'), - ] = None - - -class ProjectCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - data: Annotated[ - Optional[Data4], Field(description='The payload used to create the project.') - ] = None - - -class ChangesRequested3(BaseModel): - title: Annotated[ - Optional[str], - Field(description='The title of the project as seen on the dashboard.'), - ] = None - - -class ProjectUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested3], - Field(description='The payload used to update the project.'), - ] = None - - -class ProjectArchived(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - - -class ProjectDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - - -class ChangesRequested4(BaseModel): - max_requests_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum requests per minute.') - ] = None - max_tokens_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum tokens per minute.') - ] = None - max_images_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum images per minute. Only relevant for certain models.' - ), - ] = None - max_audio_megabytes_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum audio megabytes per minute. Only relevant for certain models.' - ), - ] = None - max_requests_per_1_day: Annotated[ - Optional[int], - Field( - description='The maximum requests per day. Only relevant for certain models.' - ), - ] = None - batch_1_day_max_input_tokens: Annotated[ - Optional[int], - Field( - description='The maximum batch input tokens per day. Only relevant for certain models.' - ), - ] = None - - -class RateLimitUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The rate limit ID')] = None - changes_requested: Annotated[ - Optional[ChangesRequested4], - Field(description='The payload used to update the rate limits.'), - ] = None - - -class RateLimitDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The rate limit ID')] = None - - -class RoleCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The role ID.')] = None - role_name: Annotated[Optional[str], Field(description='The name of the role.')] = ( - None - ) - permissions: Annotated[ - Optional[List[str]], Field(description='The permissions granted by the role.') - ] = None - resource_type: Annotated[ - Optional[str], Field(description='The type of resource the role belongs to.') - ] = None - resource_id: Annotated[ - Optional[str], Field(description='The resource the role is scoped to.') - ] = None - - -class ChangesRequested5(BaseModel): - role_name: Annotated[ - Optional[str], Field(description='The updated role name, when provided.') - ] = None - resource_id: Annotated[ - Optional[str], Field(description='The resource the role is scoped to.') - ] = None - resource_type: Annotated[ - Optional[str], Field(description='The type of resource the role belongs to.') - ] = None - permissions_added: Annotated[ - Optional[List[str]], Field(description='The permissions added to the role.') - ] = None - permissions_removed: Annotated[ - Optional[List[str]], Field(description='The permissions removed from the role.') - ] = None - description: Annotated[ - Optional[str], Field(description='The updated role description, when provided.') - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Additional metadata stored on the role.'), - ] = None - - -class RoleUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The role ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested5], - Field(description='The payload used to update the role.'), - ] = None - - -class RoleDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The role ID.')] = None - - -class RoleAssignmentCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The identifier of the role assignment.') - ] = None - principal_id: Annotated[ - Optional[str], - Field(description='The principal (user or group) that received the role.'), - ] = None - principal_type: Annotated[ - Optional[str], - Field( - description='The type of principal (user or group) that received the role.' - ), - ] = None - resource_id: Annotated[ - Optional[str], - Field(description='The resource the role assignment is scoped to.'), - ] = None - resource_type: Annotated[ - Optional[str], - Field(description='The type of resource the role assignment is scoped to.'), - ] = None - - -class RoleAssignmentDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The identifier of the role assignment.') - ] = None - principal_id: Annotated[ - Optional[str], - Field(description='The principal (user or group) that had the role removed.'), - ] = None - principal_type: Annotated[ - Optional[str], - Field( - description='The type of principal (user or group) that had the role removed.' - ), - ] = None - resource_id: Annotated[ - Optional[str], - Field(description='The resource the role assignment was scoped to.'), - ] = None - resource_type: Annotated[ - Optional[str], - Field(description='The type of resource the role assignment was scoped to.'), - ] = None - - -class Data5(BaseModel): - role: Annotated[ - Optional[str], - Field( - description='The role of the service account. Is either `owner` or `member`.' - ), - ] = None - - -class ServiceAccountCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The service account ID.')] = None - data: Annotated[ - Optional[Data5], - Field(description='The payload used to create the service account.'), - ] = None - - -class ChangesRequested6(BaseModel): - role: Annotated[ - Optional[str], - Field( - description='The role of the service account. Is either `owner` or `member`.' - ), - ] = None - - -class ServiceAccountUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The service account ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested6], - Field(description='The payload used to updated the service account.'), - ] = None - - -class ServiceAccountDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The service account ID.')] = None - - -class Data6(BaseModel): - role: Annotated[ - Optional[str], - Field(description='The role of the user. Is either `owner` or `member`.'), - ] = None - - -class UserAdded(BaseModel): - id: Annotated[Optional[str], Field(description='The user ID.')] = None - data: Annotated[ - Optional[Data6], - Field(description='The payload used to add the user to the project.'), - ] = None - - -class ChangesRequested7(BaseModel): - role: Annotated[ - Optional[str], - Field(description='The role of the user. Is either `owner` or `member`.'), - ] = None - - -class UserUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested7], - Field(description='The payload used to update the user.'), - ] = None - - -class UserDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The user ID.')] = None - - -class CertificateCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - - -class CertificateUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - - -class CertificateDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - certificate: Annotated[ - Optional[str], Field(description='The certificate content in PEM format.') - ] = None - - -class Certificate(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - - -class CertificatesActivated(BaseModel): - certificates: Optional[List[Certificate]] = None - - -class CertificatesDeactivated(BaseModel): - certificates: Optional[List[Certificate]] = None - - -class AuditLogActorServiceAccount(BaseModel): - id: Annotated[Optional[str], Field(description='The service account id.')] = None - - -class AuditLogActorUser(BaseModel): - id: Annotated[Optional[str], Field(description='The user id.')] = None - email: Annotated[Optional[str], Field(description='The user email.')] = None - - -class AuditLogEventType(BaseModel): - __root__: Annotated[ - Literal[ - 'api_key.created', - 'api_key.updated', - 'api_key.deleted', - 'certificate.created', - 'certificate.updated', - 'certificate.deleted', - 'certificates.activated', - 'certificates.deactivated', - 'checkpoint.permission.created', - 'checkpoint.permission.deleted', - 'external_key.registered', - 'external_key.removed', - 'group.created', - 'group.updated', - 'group.deleted', - 'invite.sent', - 'invite.accepted', - 'invite.deleted', - 'ip_allowlist.created', - 'ip_allowlist.updated', - 'ip_allowlist.deleted', - 'ip_allowlist.config.activated', - 'ip_allowlist.config.deactivated', - 'login.succeeded', - 'login.failed', - 'logout.succeeded', - 'logout.failed', - 'organization.updated', - 'project.created', - 'project.updated', - 'project.archived', - 'project.deleted', - 'rate_limit.updated', - 'rate_limit.deleted', - 'resource.deleted', - 'role.created', - 'role.updated', - 'role.deleted', - 'role.assignment.created', - 'role.assignment.deleted', - 'scim.enabled', - 'scim.disabled', - 'service_account.created', - 'service_account.updated', - 'service_account.deleted', - 'user.added', - 'user.updated', - 'user.deleted', - ], - Field(description='The event type.'), - ] - - -class AutoChunkingStrategyRequestParam(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['AutoChunkingStrategyRequestParam'], Field(description='Always `auto`.') - ] - - -class InputTokensDetails(BaseModel): - cached_tokens: Annotated[ - int, - Field( - description='The number of tokens that were retrieved from the cache. [More on\nprompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n' - ), - ] - - -class OutputTokensDetails(BaseModel): - reasoning_tokens: Annotated[ - int, Field(description='The number of reasoning tokens.') - ] - - -class Usage(BaseModel): - input_tokens: Annotated[int, Field(description='The number of input tokens.')] - input_tokens_details: Annotated[ - InputTokensDetails, - Field(description='A detailed breakdown of the input tokens.'), - ] - output_tokens: Annotated[int, Field(description='The number of output tokens.')] - output_tokens_details: Annotated[ - OutputTokensDetails, - Field(description='A detailed breakdown of the output tokens.'), - ] - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - - -class BatchFileExpirationAfter(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created.' - ), - ] - seconds: Annotated[ - int, - Field( - description='The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).', - ge=3600, - le=2592000, - ), - ] - - -class BatchRequestInput(BaseModel): - custom_id: Annotated[ - Optional[str], - Field( - description='A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch.' - ), - ] = None - method: Annotated[ - Optional[Literal['POST']], - Field( - description='The HTTP method to be used for the request. Currently only `POST` is supported.' - ), - ] = None - url: Annotated[ - Optional[str], - Field( - description='The OpenAI API relative URL to be used for the request. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, and `/v1/moderations` are supported.' - ), - ] = None - - -class Response(BaseModel): - status_code: Annotated[ - Optional[int], Field(description='The HTTP status code of the response') - ] = None - request_id: Annotated[ - Optional[str], - Field( - description='An unique identifier for the OpenAI API request. Please include this request ID when contacting support.' - ), - ] = None - body: Annotated[ - Optional[Dict[str, Any]], Field(description='The JSON body of the response') - ] = None - - -class Error(BaseModel): - code: Annotated[ - Optional[str], - Field( - description='A machine-readable error code.\n\nPossible values:\n- `batch_expired`: The request could not be executed before the\n completion window ended.\n- `batch_cancelled`: The batch was cancelled before this request\n executed.\n- `request_timeout`: The underlying call to the model timed out.\n' - ), - ] = None - message: Annotated[ - Optional[str], Field(description='A human-readable error message.') - ] = None - - -class BatchRequestOutput(BaseModel): - id: Optional[str] = None - custom_id: Annotated[ - Optional[str], - Field( - description='A developer-provided per-request id that will be used to match outputs to inputs.' - ), - ] = None - response: Optional[Response] = None - error: Optional[Error] = None - - -class CertificateDetails(BaseModel): - valid_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) of when the certificate becomes valid.' - ), - ] = None - expires_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) of when the certificate expires.' - ), - ] = None - content: Annotated[ - Optional[str], - Field(description='The content of the certificate in PEM format.'), - ] = None - - -class Certificate2(BaseModel): - object: Annotated[ - Literal[ - 'certificate', - 'organization.certificate', - 'organization.project.certificate', - ], - Field( - description='The object type.\n\n- If creating, updating, or getting a specific certificate, the object type is `certificate`.\n- If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`.\n- If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`.\n' - ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the certificate.')] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the certificate was uploaded.' - ), - ] - certificate_details: CertificateDetails - active: Annotated[ - Optional[bool], - Field( - description='Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate.' - ), - ] = None - - -class ChatCompletionAllowedTools(BaseModel): - mode: Annotated[ - Literal['auto', 'required'], - Field( - description='Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n' - ), - ] - tools: Annotated[ - List[Dict[str, Any]], - Field( - description='A list of tool definitions that the model should be allowed to call.\n\nFor the Chat Completions API, the list of tool definitions might look like:\n```json\n[\n { "type": "function", "function": { "name": "get_weather" } },\n { "type": "function", "function": { "name": "get_time" } }\n]\n```\n' - ), - ] - - -class ChatCompletionAllowedToolsChoice(BaseModel): - type: Annotated[ - Literal['allowed_tools'], - Field(description='Allowed tool configuration type. Always `allowed_tools`.'), - ] - allowed_tools: ChatCompletionAllowedTools - - -class ChatCompletionDeleted(BaseModel): - object: Annotated[ - Literal['chat.completion.deleted'], - Field(description='The type of object being deleted.'), - ] - id: Annotated[ - str, Field(description='The ID of the chat completion that was deleted.') - ] - deleted: Annotated[ - bool, Field(description='Whether the chat completion was deleted.') - ] - - -class ChatCompletionFunctionCallOption(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] - - -class Custom(BaseModel): - name: Annotated[str, Field(description='The name of the custom tool to call.')] - input: Annotated[ - str, - Field(description='The input for the custom tool call generated by the model.'), - ] - - -class ChatCompletionMessageCustomToolCall(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call.')] - type: Annotated[ - Literal['ChatCompletionMessageCustomToolCall'], - Field(description='The type of the tool. Always `custom`.'), - ] - custom: Annotated[ - Custom, Field(description='The custom tool that the model called.') - ] - - -class Function1(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] - arguments: Annotated[ - str, - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] - - -class ChatCompletionMessageToolCall(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call.')] - type: Annotated[ - Literal['ChatCompletionMessageToolCall'], - Field( - description='The type of the tool. Currently, only `function` is supported.' - ), - ] - function: Annotated[ - Function1, Field(description='The function that the model called.') - ] - - -class Function2(BaseModel): - name: Annotated[ - Optional[str], Field(description='The name of the function to call.') - ] = None - arguments: Annotated[ - Optional[str], - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] = None - - -class ChatCompletionMessageToolCallChunk(BaseModel): - index: int - id: Annotated[Optional[str], Field(description='The ID of the tool call.')] = None - type: Annotated[ - Optional[Literal['function']], - Field( - description='The type of the tool. Currently, only `function` is supported.' - ), - ] = None - function: Optional[Function2] = None - - -class ChatCompletionMessageToolCalls1(BaseModel): - __root__: Annotated[ - Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall], - Field(discriminator='type'), - ] - - -class ChatCompletionMessageToolCalls(BaseModel): - __root__: Annotated[ - List[ChatCompletionMessageToolCalls1], - Field( - description='The tool calls generated by the model, such as function calls.' - ), - ] - - -class ChatCompletionModalities(BaseModel): - __root__: Optional[List[Literal['text', 'audio']]] - - -class Function3(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] - - -class ChatCompletionNamedToolChoice(BaseModel): - type: Annotated[ - Literal['function'], - Field(description='For function calling, the type is always `function`.'), - ] - function: Function3 - - -class Custom1(BaseModel): - name: Annotated[str, Field(description='The name of the custom tool to call.')] - - -class ChatCompletionNamedToolChoiceCustom(BaseModel): - type: Annotated[ - Literal['custom'], - Field(description='For custom tool calling, the type is always `custom`.'), - ] - custom: Custom1 - - -class Audio(BaseModel): - id: Annotated[ - str, - Field( - description='Unique identifier for a previous audio response from the model.\n' - ), - ] - - -class FunctionCall(BaseModel): - arguments: Annotated[ - str, - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] - name: Annotated[str, Field(description='The name of the function to call.')] - - -class ChatCompletionRequestFunctionMessage(BaseModel): - role: Annotated[ - Literal['ChatCompletionRequestFunctionMessage'], - Field(description='The role of the messages author, in this case `function`.'), - ] - content: Optional[str] - name: Annotated[str, Field(description='The name of the function to call.')] - - -class InputAudio(BaseModel): - data: Annotated[str, Field(description='Base64 encoded audio data.')] - format: Annotated[ - Literal['wav', 'mp3'], - Field( - description='The format of the encoded audio data. Currently supports "wav" and "mp3".\n' - ), - ] - - -class ChatCompletionRequestMessageContentPartAudio(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartAudio'], - Field(description='The type of the content part. Always `input_audio`.'), - ] - input_audio: InputAudio - - -class File(BaseModel): - filename: Annotated[ - Optional[str], - Field( - description='The name of the file, used when passing the file to the model as a \nstring.\n' - ), - ] = None - file_data: Annotated[ - Optional[str], - Field( - description='The base64 encoded file data, used when passing the file to the model \nas a string.\n' - ), - ] = None - file_id: Annotated[ - Optional[str], - Field(description='The ID of an uploaded file to use as input.\n'), - ] = None - - -class ChatCompletionRequestMessageContentPartFile(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartFile'], - Field(description='The type of the content part. Always `file`.'), - ] - file: File - - -class ImageUrl(BaseModel): - url: Annotated[ - AnyUrl, - Field( - description='Either a URL of the image or the base64 encoded image data.' - ), - ] - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).' - ), - ] = 'auto' - - -class ChatCompletionRequestMessageContentPartImage(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartImage'], - Field(description='The type of the content part.'), - ] - image_url: ImageUrl - - -class ChatCompletionRequestMessageContentPartRefusal(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartRefusal'], - Field(description='The type of the content part.'), - ] - refusal: Annotated[ - str, Field(description='The refusal message generated by the model.') - ] - - -class ChatCompletionRequestMessageContentPartText(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartText'], - Field(description='The type of the content part.'), - ] - text: Annotated[str, Field(description='The text content.')] - - -class ChatCompletionRequestSystemMessageContentPart(BaseModel): - __root__: ChatCompletionRequestMessageContentPartText - - -class ChatCompletionRequestToolMessageContentPart(BaseModel): - __root__: ChatCompletionRequestMessageContentPartText - - -class ChatCompletionRequestUserMessageContentPart(BaseModel): - __root__: Annotated[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartImage, - ChatCompletionRequestMessageContentPartAudio, - ChatCompletionRequestMessageContentPartFile, - ], - Field(discriminator='type'), - ] - - -class UrlCitation(BaseModel): - end_index: Annotated[ - int, - Field( - description='The index of the last character of the URL citation in the message.' - ), - ] - start_index: Annotated[ - int, - Field( - description='The index of the first character of the URL citation in the message.' - ), - ] - url: Annotated[str, Field(description='The URL of the web resource.')] - title: Annotated[str, Field(description='The title of the web resource.')] - - -class Annotation(BaseModel): - type: Annotated[ - Literal['url_citation'], - Field(description='The type of the URL citation. Always `url_citation`.'), - ] - url_citation: Annotated[ - UrlCitation, Field(description='A URL citation when using web search.') - ] - - -class Audio1(BaseModel): - id: Annotated[str, Field(description='Unique identifier for this audio response.')] - expires_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when this audio response will\nno longer be accessible on the server for use in multi-turn\nconversations.\n' - ), - ] - data: Annotated[ - str, - Field( - description='Base64 encoded audio bytes generated by the model, in the format\nspecified in the request.\n' - ), - ] - transcript: Annotated[ - str, Field(description='Transcript of the audio generated by the model.') - ] - - -class ChatCompletionResponseMessage(BaseModel): - content: Optional[str] - refusal: Optional[str] - tool_calls: Optional[ChatCompletionMessageToolCalls] = None - annotations: Annotated[ - Optional[List[Annotation]], - Field( - description='Annotations for the message, when applicable, as when using the\n[web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n' - ), - ] = None - role: Annotated[ - Literal['assistant'], - Field(description='The role of the author of this message.'), - ] - function_call: Annotated[ - Optional[FunctionCall], - Field( - description='Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.' - ), - ] = None - audio: Optional[Audio1] = None - - -class ChatCompletionRole(BaseModel): - __root__: Annotated[ - Literal['developer', 'system', 'user', 'assistant', 'tool', 'function'], - Field(description='The role of the author of a message'), - ] - - -class ChatCompletionStreamOptions1(BaseModel): - include_usage: Annotated[ - Optional[bool], - Field( - description='If set, an additional chunk will be streamed before the `data: [DONE]`\nmessage. The `usage` field on this chunk shows the token usage statistics\nfor the entire request, and the `choices` field will always be an empty\narray.\n\nAll other chunks will also include a `usage` field, but with a null\nvalue. **NOTE:** If the stream is interrupted, you may not receive the\nfinal usage chunk which contains the total token usage for the request.\n' - ), - ] = None - include_obfuscation: Annotated[ - Optional[bool], - Field( - description='When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n' - ), - ] = None - - -class ChatCompletionStreamOptions(BaseModel): - __root__: Optional[ChatCompletionStreamOptions1] - - -class FunctionCall2(BaseModel): - arguments: Annotated[ - Optional[str], - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the function to call.') - ] = None - - -class ChatCompletionStreamResponseDelta(BaseModel): - content: Optional[str] = None - function_call: Annotated[ - Optional[FunctionCall2], - Field( - description='Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.' - ), - ] = None - tool_calls: Optional[List[ChatCompletionMessageToolCallChunk]] = None - role: Annotated[ - Optional[Literal['developer', 'system', 'user', 'assistant', 'tool']], - Field(description='The role of the author of this message.'), - ] = None - refusal: Optional[str] = None - - -class TopLogprob(BaseModel): - token: Annotated[str, Field(description='The token.')] - logprob: Annotated[ - float, - Field( - description='The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.' - ), - ] - bytes: Optional[List[int]] - - -class ChatCompletionTokenLogprob(BaseModel): - token: Annotated[str, Field(description='The token.')] - logprob: Annotated[ - float, - Field( - description='The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.' - ), - ] - bytes: Optional[List[int]] - top_logprobs: Annotated[ - List[TopLogprob], - Field( - description='List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned.' - ), - ] - - -class ChatCompletionToolChoiceOption(BaseModel): - __root__: Annotated[ - Union[ - Literal['none', 'auto', 'required'], - ChatCompletionAllowedToolsChoice, - ChatCompletionNamedToolChoice, - ChatCompletionNamedToolChoiceCustom, - ], - Field( - description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tool and instead generates a message.\n`auto` means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools.\nSpecifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n\n`none` is the default when no tools are present. `auto` is the default if tools are present.\n' - ), - ] - - -class File1(BaseModel): - mime_type: Annotated[str, Field(description='The MIME type of the file.\n')] - file_id: Annotated[str, Field(description='The ID of the file.\n')] - - -class CodeInterpreterFileOutput(BaseModel): - type: Annotated[ - Literal['files'], - Field( - description='The type of the code interpreter file output. Always `files`.\n' - ), - ] - files: List[File1] - - -class CodeInterpreterTextOutput(BaseModel): - type: Annotated[ - Literal['logs'], - Field( - description='The type of the code interpreter text output. Always `logs`.\n' - ), - ] - logs: Annotated[ - str, Field(description='The logs of the code interpreter tool call.\n') - ] - - -class CompleteUploadRequest(BaseModel): - class Config: - extra = Extra.forbid - - part_ids: Annotated[List[str], Field(description='The ordered list of Part IDs.\n')] - md5: Annotated[ - Optional[str], - Field( - description='The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n' - ), - ] = None - - -class CompletionTokensDetails(BaseModel): - accepted_prediction_tokens: Annotated[ - int, - Field( - description='When using Predicted Outputs, the number of tokens in the\nprediction that appeared in the completion.\n' - ), - ] = 0 - audio_tokens: Annotated[ - int, Field(description='Audio input tokens generated by the model.') - ] = 0 - reasoning_tokens: Annotated[ - int, Field(description='Tokens generated by the model for reasoning.') - ] = 0 - rejected_prediction_tokens: Annotated[ - int, - Field( - description='When using Predicted Outputs, the number of tokens in the\nprediction that did not appear in the completion. However, like\nreasoning tokens, these tokens are still counted in the total\ncompletion tokens for purposes of billing, output, and context window\nlimits.\n' - ), - ] = 0 - - -class PromptTokensDetails(BaseModel): - audio_tokens: Annotated[ - int, Field(description='Audio input tokens present in the prompt.') - ] = 0 - cached_tokens: Annotated[ - int, Field(description='Cached tokens present in the prompt.') - ] = 0 - - -class CompletionUsage(BaseModel): - completion_tokens: Annotated[ - int, Field(description='Number of tokens in the generated completion.') - ] - prompt_tokens: Annotated[int, Field(description='Number of tokens in the prompt.')] - total_tokens: Annotated[ - int, - Field( - description='Total number of tokens used in the request (prompt + completion).' - ), - ] - completion_tokens_details: Annotated[ - Optional[CompletionTokensDetails], - Field(description='Breakdown of tokens used in a completion.'), - ] = None - prompt_tokens_details: Annotated[ - Optional[PromptTokensDetails], - Field(description='Breakdown of tokens used in the prompt.'), - ] = None - - -class ComputerScreenshotImage(BaseModel): - type: Annotated[ - Literal['computer_screenshot'], - Field( - description='Specifies the event type. For a computer screenshot, this property is \nalways set to `computer_screenshot`.\n' - ), - ] - image_url: Annotated[ - Optional[str], Field(description='The URL of the screenshot image.') - ] = None - file_id: Annotated[ - Optional[str], - Field( - description='The identifier of an uploaded file that contains the screenshot.' - ), - ] = None - - -class ContainerFileResource(BaseModel): - id: Annotated[str, Field(description='Unique identifier for the file.')] - object: Annotated[ - str, - Field(const=True, description='The type of this object (`container.file`).'), - ] = 'container.file' - container_id: Annotated[ - str, Field(description='The container this file belongs to.') - ] - created_at: Annotated[ - int, Field(description='Unix timestamp (in seconds) when the file was created.') - ] - bytes: Annotated[int, Field(description='Size of the file in bytes.')] - path: Annotated[str, Field(description='Path of the file in the container.')] - source: Annotated[ - str, Field(description='Source of the file (e.g., `user`, `assistant`).') - ] - - -class ExpiresAfter(BaseModel): - anchor: Annotated[ - Optional[Literal['last_active_at']], - Field(description='The reference point for the expiration.'), - ] = None - minutes: Annotated[ - Optional[int], - Field( - description='The number of minutes after the anchor before the container expires.' - ), - ] = None - - -class ContainerResource(BaseModel): - id: Annotated[str, Field(description='Unique identifier for the container.')] - object: Annotated[str, Field(description='The type of this object.')] - name: Annotated[str, Field(description='Name of the container.')] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) when the container was created.' - ), - ] - status: Annotated[ - str, Field(description='Status of the container (e.g., active, deleted).') - ] - expires_after: Annotated[ - Optional[ExpiresAfter], - Field( - description='The container will expire after this time period.\nThe anchor is the reference point for the expiration.\nThe minutes is the number of minutes after the anchor before the container expires.\n' - ), - ] = None - - -class Amount(BaseModel): - value: Annotated[ - Optional[float], Field(description='The numeric value of the cost.') - ] = None - currency: Annotated[ - Optional[str], Field(description='Lowercase ISO-4217 currency e.g. "usd"') - ] = None - - -class CostsResult(BaseModel): - object: Literal['CostsResult'] - amount: Annotated[ - Optional[Amount], - Field(description='The monetary value in its associated currency.'), - ] = None - line_item: Optional[str] = None - project_id: Optional[str] = None - - -class CodeInterpreter1(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n', - max_items=20, - ), - ] = [] - - -class ChunkingStrategy(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class Static(BaseModel): - class Config: - extra = Extra.forbid - - max_chunk_size_tokens: Annotated[ - int, - Field( - description='The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.', - ge=100, - le=4096, - ), - ] - chunk_overlap_tokens: Annotated[ - int, - Field( - description='The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n' - ), - ] - - -class ChunkingStrategy1(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class ChunkingStrategy2(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class ChunkingStrategy3(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class Logprobs(BaseModel): - content: Optional[List[ChatCompletionTokenLogprob]] - refusal: Optional[List[ChatCompletionTokenLogprob]] - - -class Choice(BaseModel): - finish_reason: Annotated[ - Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call'], - Field( - description='The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n' - ), - ] - index: Annotated[ - int, Field(description='The index of the choice in the list of choices.') - ] - message: ChatCompletionResponseMessage - logprobs: Optional[Logprobs] - - -class Logprobs1(BaseModel): - content: Annotated[ - Optional[List[ChatCompletionTokenLogprob]], - Field( - description='A list of message content tokens with log probability information.' - ), - ] - refusal: Annotated[ - Optional[List[ChatCompletionTokenLogprob]], - Field( - description='A list of message refusal tokens with log probability information.' - ), - ] - - -class Choice1(BaseModel): - delta: ChatCompletionStreamResponseDelta - logprobs: Annotated[ - Optional[Logprobs1], - Field(description='Log probability information for the choice.'), - ] = None - finish_reason: Annotated[ - Optional[ - Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call'] - ], - Field( - description='The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n' - ), - ] - index: Annotated[ - int, Field(description='The index of the choice in the list of choices.') - ] - - -class Prompt(BaseModel): - __root__: Annotated[ - Optional[List[int]], - Field( - description='The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n', - min_items=1, - title='Array of tokens', - ), - ] = None - - -class Prompt1Item(BaseModel): - __root__: Annotated[List[int], Field(min_items=1)] - - -class Prompt1(BaseModel): - __root__: Annotated[ - Optional[List[Prompt1Item]], - Field( - description='The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n', - min_items=1, - title='Array of token arrays', - ), - ] = None - - -class Logprobs2(BaseModel): - text_offset: Optional[List[int]] = None - token_logprobs: Optional[List[float]] = None - tokens: Optional[List[str]] = None - top_logprobs: Optional[List[Dict[str, float]]] = None - - -class Choice2(BaseModel): - finish_reason: Annotated[ - Literal['stop', 'length', 'content_filter'], - Field( - description='The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\nor `content_filter` if content was omitted due to a flag from our content filters.\n' - ), - ] - index: int - logprobs: Optional[Logprobs2] - text: str - - -class CreateCompletionResponse(BaseModel): - id: Annotated[str, Field(description='A unique identifier for the completion.')] - choices: Annotated[ - List[Choice2], - Field( - description='The list of completion choices the model generated for the input prompt.' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the completion was created.' - ), - ] - model: Annotated[str, Field(description='The model used for completion.')] - system_fingerprint: Annotated[ - Optional[str], - Field( - description='This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n' - ), - ] = None - object: Annotated[ - Literal['text_completion'], - Field(description='The object type, which is always "text_completion"'), - ] - usage: Optional[CompletionUsage] = None - - -class ExpiresAfter1(BaseModel): - anchor: Annotated[ - Literal['last_active_at'], - Field( - description="Time anchor for the expiration time. Currently only 'last_active_at' is supported." - ), - ] - minutes: int - - -class CreateContainerBody(BaseModel): - name: Annotated[str, Field(description='Name of the container to create.')] - file_ids: Annotated[ - Optional[List[str]], Field(description='IDs of files to copy to the container.') - ] = None - expires_after: Annotated[ - Optional[ExpiresAfter1], - Field( - description="Container expiration time in seconds relative to the 'anchor' time." - ), - ] = None - - -class CreateContainerFileBody(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='Name of the file to create.') - ] = None - file: Annotated[ - Optional[bytes], - Field(description='The File object (not file name) to be uploaded.\n'), - ] = None - - -class Input(BaseModel): - __root__: Annotated[ - List[str], - Field( - description='The array of strings that will be turned into an embedding.', - example='The quick brown fox jumped over the lazy dog', - max_items=2048, - min_items=1, - title='Array of strings', - ), - ] - - -class Input1(BaseModel): - __root__: Annotated[ - List[int], - Field( - description='The array of integers that will be turned into an embedding.', - example='The quick brown fox jumped over the lazy dog', - max_items=2048, - min_items=1, - title='Array of tokens', - ), - ] - - -class Input2Item(BaseModel): - __root__: Annotated[List[int], Field(min_items=1)] - - -class Input2(BaseModel): - __root__: Annotated[ - List[Input2Item], - Field( - description='The array of arrays containing integers that will be turned into an embedding.', - example='The quick brown fox jumped over the lazy dog', - max_items=2048, - min_items=1, - title='Array of token arrays', - ), - ] - - -class CreateEmbeddingRequest(BaseModel): - class Config: - extra = Extra.forbid - - input: Annotated[ - Union[str, Input, Input1, Input2], - Field( - description='Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request.\n', - example='The quick brown fox jumped over the lazy dog', - ), - ] - model: Annotated[ - Union[ - str, - Literal[ - 'text-embedding-ada-002', - 'text-embedding-3-small', - 'text-embedding-3-large', - ], - ], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n', - example='text-embedding-3-small', - ), - ] - encoding_format: Annotated[ - Literal['float', 'base64'], - Field( - description='The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).', - example='float', - ), - ] = 'float' - dimensions: Annotated[ - Optional[int], - Field( - description='The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n', - ge=1, - ), - ] = None - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - example='user-1234', - ), - ] = None - - -class Usage1(BaseModel): - prompt_tokens: Annotated[ - int, Field(description='The number of tokens used by the prompt.') - ] - total_tokens: Annotated[ - int, Field(description='The total number of tokens used by the request.') - ] - - -class InputMessages1(BaseModel): - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `item_reference`.'), - ] - item_reference: Annotated[ - str, - Field( - description='A reference to a variable in the `item` namespace. Ie, "item.input_trajectory"' - ), - ] - - -class CreateEvalCustomDataSourceConfig(BaseModel): - type: Annotated[ - Literal['CreateEvalCustomDataSourceConfig'], - Field(description='The type of data source. Always `custom`.'), - ] - item_schema: Annotated[ - Dict[str, Any], - Field(description='The json schema for each row in the data source.'), - ] - include_sample_schema: Annotated[ - bool, - Field( - description='Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source)' - ), - ] = False - - -class CreateEvalItem1(BaseModel): - role: Annotated[ - str, - Field( - description='The role of the message (e.g. "system", "assistant", "user").' - ), - ] - content: Annotated[str, Field(description='The content of the message.')] - - -class CreateEvalLogsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['CreateEvalLogsDataSourceConfig'], - Field(description='The type of data source. Always `logs`.'), - ] - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Metadata filters for the logs data source.'), - ] = None - - -class Template(BaseModel): - role: Annotated[ - str, - Field( - description='The role of the message (e.g. "system", "assistant", "user").' - ), - ] - content: Annotated[str, Field(description='The content of the message.')] - - -class InputMessages3(BaseModel): - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `item_reference`.'), - ] - item_reference: Annotated[ - str, - Field( - description='A reference to a variable in the `item` namespace. Ie, "item.name"' - ), - ] - - -class CreateEvalStoredCompletionsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['CreateEvalStoredCompletionsDataSourceConfig'], - Field(description='The type of data source. Always `stored_completions`.'), - ] - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Metadata filters for the stored completions data source.'), - ] = None - - -class CreateFineTuningCheckpointPermissionRequest(BaseModel): - class Config: - extra = Extra.forbid - - project_ids: Annotated[ - List[str], Field(description='The project identifiers to grant access to.') - ] - - -class BatchSize(BaseModel): - __root__: Annotated[ - int, - Field( - description='Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n', - ge=1, - le=256, - ), - ] - - -class LearningRateMultiplier(BaseModel): - __root__: Annotated[ - float, - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n', - gt=0.0, - ), - ] - - -class NEpochs(BaseModel): - __root__: Annotated[ - int, - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n', - ge=1, - le=50, - ), - ] - - -class Hyperparameters(BaseModel): - batch_size: Annotated[ - Union[Literal['auto'], BatchSize], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n' - ), - ] = 'auto' - - -class Wandb(BaseModel): - project: Annotated[ - str, - Field( - description='The name of the project that the new run will be created under.\n', - example='my-wandb-project', - ), - ] - name: Annotated[ - Optional[str], - Field( - description='A display name to set for the run. If not set, we will use the Job ID as the name.\n' - ), - ] = None - entity: Annotated[ - Optional[str], - Field( - description='The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n' - ), - ] = None - tags: Annotated[ - Optional[List[str]], - Field( - description='A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}".\n' - ), - ] = None - - -class Integration(BaseModel): - type: Annotated[ - Literal['wandb'], - Field( - description='The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported.\n' - ), - ] - wandb: Annotated[ - Wandb, - Field( - description='The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n' - ), - ] - - -class CreateGroupBody(BaseModel): - name: Annotated[ - str, - Field( - description='Human readable name for the group.', - max_length=255, - min_length=1, - ), - ] - - -class CreateGroupUserBody(BaseModel): - user_id: Annotated[ - str, Field(description='Identifier of the user to add to the group.') - ] - - -class Image(BaseModel): - __root__: Annotated[ - List[bytes], - Field( - description='The image(s) to edit. Must be a supported image file or an array of images.\n\nFor `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less\nthan 50MB. You can provide up to 16 images.\n\nFor `dall-e-2`, you can only provide one image, and it should be a square\n`png` file less than 4MB.\n', - max_items=16, - ), - ] - - -class CreateImageVariationRequest(BaseModel): - image: Annotated[ - bytes, - Field( - description='The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.' - ), - ] - model: Annotated[ - Optional[Union[Optional[str], Literal['dall-e-2']]], - Field( - description='The model to use for image generation. Only `dall-e-2` is supported at this time.' - ), - ] = None - n: Annotated[ - Optional[int], - Field( - description='The number of images to generate. Must be between 1 and 10.', - example=1, - ge=1, - le=10, - ), - ] = 1 - response_format: Annotated[ - Optional[Literal['url', 'b64_json']], - Field( - description='The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.', - example='url', - ), - ] = 'url' - size: Annotated[ - Optional[Literal['256x256', '512x512', '1024x1024']], - Field( - description='The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.', - example='1024x1024', - ), - ] = '1024x1024' - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - example='user-1234', - ), - ] = None - - -class Tools1(BaseModel): - __root__: Annotated[ - Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly], - Field(discriminator='type'), - ] - - -class Attachment(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The ID of the file to attach to the message.') - ] = None - tools: Annotated[ - Optional[List[Tools1]], Field(description='The tools to add this file to.') - ] = None - - -class Categories(BaseModel): - hate: Annotated[ - bool, - Field( - description='Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment.' - ), - ] - hate_threatening: Annotated[ - bool, - Field( - alias='hate/threatening', - description='Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.', - ), - ] - harassment: Annotated[ - bool, - Field( - description='Content that expresses, incites, or promotes harassing language towards any target.' - ), - ] - harassment_threatening: Annotated[ - bool, - Field( - alias='harassment/threatening', - description='Harassment content that also includes violence or serious harm towards any target.', - ), - ] - illicit: Optional[bool] - illicit_violent: Annotated[Optional[bool], Field(alias='illicit/violent')] - self_harm: Annotated[ - bool, - Field( - alias='self-harm', - description='Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.', - ), - ] - self_harm_intent: Annotated[ - bool, - Field( - alias='self-harm/intent', - description='Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders.', - ), - ] - self_harm_instructions: Annotated[ - bool, - Field( - alias='self-harm/instructions', - description='Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts.', - ), - ] - sexual: Annotated[ - bool, - Field( - description='Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness).' - ), - ] - sexual_minors: Annotated[ - bool, - Field( - alias='sexual/minors', - description='Sexual content that includes an individual who is under 18 years old.', - ), - ] - violence: Annotated[ - bool, - Field(description='Content that depicts death, violence, or physical injury.'), - ] - violence_graphic: Annotated[ - bool, - Field( - alias='violence/graphic', - description='Content that depicts death, violence, or physical injury in graphic detail.', - ), - ] - - -class CategoryScores(BaseModel): - hate: Annotated[float, Field(description="The score for the category 'hate'.")] - hate_threatening: Annotated[ - float, - Field( - alias='hate/threatening', - description="The score for the category 'hate/threatening'.", - ), - ] - harassment: Annotated[ - float, Field(description="The score for the category 'harassment'.") - ] - harassment_threatening: Annotated[ - float, - Field( - alias='harassment/threatening', - description="The score for the category 'harassment/threatening'.", - ), - ] - illicit: Annotated[ - float, Field(description="The score for the category 'illicit'.") - ] - illicit_violent: Annotated[ - float, - Field( - alias='illicit/violent', - description="The score for the category 'illicit/violent'.", - ), - ] - self_harm: Annotated[ - float, - Field(alias='self-harm', description="The score for the category 'self-harm'."), - ] - self_harm_intent: Annotated[ - float, - Field( - alias='self-harm/intent', - description="The score for the category 'self-harm/intent'.", - ), - ] - self_harm_instructions: Annotated[ - float, - Field( - alias='self-harm/instructions', - description="The score for the category 'self-harm/instructions'.", - ), - ] - sexual: Annotated[float, Field(description="The score for the category 'sexual'.")] - sexual_minors: Annotated[ - float, - Field( - alias='sexual/minors', - description="The score for the category 'sexual/minors'.", - ), - ] - violence: Annotated[ - float, Field(description="The score for the category 'violence'.") - ] - violence_graphic: Annotated[ - float, - Field( - alias='violence/graphic', - description="The score for the category 'violence/graphic'.", - ), - ] - - -class CategoryAppliedInputTypes(BaseModel): - hate: Annotated[ - List[Literal['text']], - Field(description="The applied input type(s) for the category 'hate'."), - ] - hate_threatening: Annotated[ - List[Literal['text']], - Field( - alias='hate/threatening', - description="The applied input type(s) for the category 'hate/threatening'.", - ), - ] - harassment: Annotated[ - List[Literal['text']], - Field(description="The applied input type(s) for the category 'harassment'."), - ] - harassment_threatening: Annotated[ - List[Literal['text']], - Field( - alias='harassment/threatening', - description="The applied input type(s) for the category 'harassment/threatening'.", - ), - ] - illicit: Annotated[ - List[Literal['text']], - Field(description="The applied input type(s) for the category 'illicit'."), - ] - illicit_violent: Annotated[ - List[Literal['text']], - Field( - alias='illicit/violent', - description="The applied input type(s) for the category 'illicit/violent'.", - ), - ] - self_harm: Annotated[ - List[Literal['text', 'image']], - Field( - alias='self-harm', - description="The applied input type(s) for the category 'self-harm'.", - ), - ] - self_harm_intent: Annotated[ - List[Literal['text', 'image']], - Field( - alias='self-harm/intent', - description="The applied input type(s) for the category 'self-harm/intent'.", - ), - ] - self_harm_instructions: Annotated[ - List[Literal['text', 'image']], - Field( - alias='self-harm/instructions', - description="The applied input type(s) for the category 'self-harm/instructions'.", - ), - ] - sexual: Annotated[ - List[Literal['text', 'image']], - Field(description="The applied input type(s) for the category 'sexual'."), - ] - sexual_minors: Annotated[ - List[Literal['text']], - Field( - alias='sexual/minors', - description="The applied input type(s) for the category 'sexual/minors'.", - ), - ] - violence: Annotated[ - List[Literal['text', 'image']], - Field(description="The applied input type(s) for the category 'violence'."), - ] - violence_graphic: Annotated[ - List[Literal['text', 'image']], - Field( - alias='violence/graphic', - description="The applied input type(s) for the category 'violence/graphic'.", - ), - ] - - -class Result(BaseModel): - flagged: Annotated[ - bool, Field(description='Whether any of the below categories are flagged.') - ] - categories: Annotated[ - Categories, - Field( - description='A list of the categories, and whether they are flagged or not.' - ), - ] - category_scores: Annotated[ - CategoryScores, - Field( - description='A list of the categories along with their scores as predicted by model.' - ), - ] - category_applied_input_types: Annotated[ - CategoryAppliedInputTypes, - Field( - description='A list of the categories along with the input type(s) that the score applies to.' - ), - ] - - -class CreateModerationResponse(BaseModel): - id: Annotated[ - str, Field(description='The unique identifier for the moderation request.') - ] - model: Annotated[ - str, Field(description='The model used to generate the moderation results.') - ] - results: Annotated[List[Result], Field(description='A list of moderation objects.')] - - -class ToolResources2(BaseModel): - code_interpreter: Optional[CodeInterpreter1] = None - file_search: Optional[FileSearch] = None - - -class ChunkingStrategy4(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class ChunkingStrategy5(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class ChunkingStrategy6(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class ChunkingStrategy7(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class Logprob(BaseModel): - token: Annotated[ - Optional[str], Field(description='The token in the transcription.') - ] = None - logprob: Annotated[ - Optional[float], Field(description='The log probability of the token.') - ] = None - bytes: Annotated[ - Optional[List[float]], Field(description='The bytes of the token.') - ] = None - - -class CreateTranslationRequest(BaseModel): - class Config: - extra = Extra.forbid - - file: Annotated[ - bytes, - Field( - description='The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n' - ), - ] - model: Annotated[ - Union[str, Literal['whisper-1']], - Field( - description='ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n', - example='whisper-1', - ), - ] - prompt: Annotated[ - Optional[str], - Field( - description="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 be in English.\n" - ), - ] = None - response_format: Annotated[ - Literal['json', 'text', 'srt', 'verbose_json', 'vtt'], - Field( - description='The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n' - ), - ] = 'json' - temperature: Annotated[ - float, - Field( - description='The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n' - ), - ] = 0 - - -class CreateTranslationResponseJson(BaseModel): - text: str - - -class CustomToolCall(BaseModel): - type: Annotated[ - Literal['CustomToolCall'], - Field( - description='The type of the custom tool call. Always `custom_tool_call`.\n' - ), - ] - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the custom tool call in the OpenAI platform.\n' - ), - ] = None - call_id: Annotated[ - str, - Field( - description='An identifier used to map this custom tool call to a tool call output.\n' - ), - ] - name: Annotated[ - str, Field(description='The name of the custom tool being called.\n') - ] - input: Annotated[ - str, - Field( - description='The input for the custom tool call generated by the model.\n' - ), - ] - - -class Format(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Unconstrained text format. Always `text`.'), - ] - - -class Grammar(BaseModel): - definition: Annotated[str, Field(description='The grammar definition.')] - syntax: Annotated[ - Literal['lark', 'regex'], - Field( - description='The syntax of the grammar definition. One of `lark` or `regex`.' - ), - ] - - -class Format1(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Grammar format. Always `grammar`.'), - ] - grammar: Annotated[ - Grammar, Field(description='Your chosen grammar.', title='Grammar format') - ] - - -class Custom2(BaseModel): - name: Annotated[ - str, - Field( - description='The name of the custom tool, used to identify it in tool calls.' - ), - ] - description: Annotated[ - Optional[str], - Field( - description='Optional description of the custom tool, used to provide more context.\n' - ), - ] = None - format: Annotated[ - Optional[Union[Format, Format1]], - Field( - description='The input format for the custom tool. Default is unconstrained text.\n', - discriminator='type', - ), - ] = None - - -class CustomToolChatCompletions(BaseModel): - type: Annotated[ - Literal['CustomToolChatCompletions'], - Field(description='The type of the custom tool. Always `custom`.'), - ] - custom: Annotated[ - Custom2, - Field( - description='Properties of the custom tool.\n', - title='Custom tool properties', - ), - ] - - -class DeleteAssistantResponse(BaseModel): - id: str - deleted: bool - object: Literal['assistant.deleted'] - - -class DeleteCertificateResponse(BaseModel): - object: Annotated[ - str, - Field( - const=True, description='The object type, must be `certificate.deleted`.' - ), - ] = 'certificate.deleted' - id: Annotated[str, Field(description='The ID of the certificate that was deleted.')] - - -class DeleteFileResponse(BaseModel): - id: str - object: Literal['file'] - deleted: bool - - -class DeleteFineTuningCheckpointPermissionResponse(BaseModel): - id: Annotated[ - str, - Field( - description='The ID of the fine-tuned model checkpoint permission that was deleted.' - ), - ] - object: Annotated[ - Literal['checkpoint.permission'], - Field(description='The object type, which is always "checkpoint.permission".'), - ] - deleted: Annotated[ - bool, - Field( - description='Whether the fine-tuned model checkpoint permission was successfully deleted.' - ), - ] - - -class DeleteMessageResponse(BaseModel): - id: str - deleted: bool - object: Literal['thread.message.deleted'] - - -class DeleteModelResponse(BaseModel): - id: str - deleted: bool - object: str - - -class DeleteThreadResponse(BaseModel): - id: str - deleted: bool - object: Literal['thread.deleted'] - - -class DeleteVectorStoreFileResponse(BaseModel): - id: str - deleted: bool - object: Literal['vector_store.file.deleted'] - - -class DeleteVectorStoreResponse(BaseModel): - id: str - deleted: bool - object: Literal['vector_store.deleted'] - - -class DeletedRoleAssignmentResource(BaseModel): - object: Annotated[ - str, - Field( - description='Identifier for the deleted assignment, such as `group.role.deleted` or `user.role.deleted`.' - ), - ] - deleted: Annotated[bool, Field(description='Whether the assignment was removed.')] - - -class DoneEvent(BaseModel): - event: Literal['done'] - data: Literal['[DONE]'] - - -class Embedding(BaseModel): - index: Annotated[ - int, Field(description='The index of the embedding in the list of embeddings.') - ] - embedding: Annotated[ - List[float], - Field( - description='The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings).\n' - ), - ] - object: Annotated[ - Literal['embedding'], - Field(description='The object type, which is always "embedding".'), - ] - - -class Error1(BaseModel): - code: Optional[str] - message: str - param: Optional[str] - type: str - - -class ErrorEvent(BaseModel): - event: Literal['ErrorEvent'] - data: Error1 - - -class ErrorResponse(BaseModel): - error: Error1 - - -class EvalApiError(BaseModel): - code: Annotated[str, Field(description='The error code.')] - message: Annotated[str, Field(description='The error message.')] - - -class EvalCustomDataSourceConfig(BaseModel): - type: Annotated[ - Literal['EvalCustomDataSourceConfig'], - Field(description='The type of data source. Always `custom`.'), - ] - schema_: Annotated[ - Dict[str, Any], - Field( - alias='schema', - description='The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n', - ), - ] - - -class Content7(BaseModel): - type: Annotated[ - Literal['output_text'], - Field(description='The type of the output text. Always `output_text`.\n'), - ] - text: Annotated[str, Field(description='The text output from the model.\n')] - - -class Content8(BaseModel): - type: Annotated[ - Literal['input_image'], - Field(description='The type of the image input. Always `input_image`.\n'), - ] - image_url: Annotated[str, Field(description='The URL of the image input.\n')] - detail: Annotated[ - Optional[str], - Field( - description='The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n' - ), - ] = None - - -class ContentItem(BaseModel): - item: Dict[str, Any] - sample: Optional[Dict[str, Any]] = None - - -class EvalJsonlFileContentSource(BaseModel): - type: Annotated[ - Literal['EvalJsonlFileContentSource'], - Field(description='The type of jsonl source. Always `file_content`.'), - ] - content: Annotated[ - List[ContentItem], Field(description='The content of the jsonl file.') - ] - - -class EvalJsonlFileIdSource(BaseModel): - type: Annotated[ - Literal['EvalJsonlFileIdSource'], - Field(description='The type of jsonl source. Always `file_id`.'), - ] - id: Annotated[str, Field(description='The identifier of the file.')] - - -class CreatedAfter(BaseModel): - __root__: Annotated[ - int, - Field( - description='Only include items created after this timestamp (inclusive). This is a query parameter used to select responses.', - ge=0, - ), - ] - - -class CreatedBefore(BaseModel): - __root__: Annotated[ - int, - Field( - description='Only include items created before this timestamp (inclusive). This is a query parameter used to select responses.', - ge=0, - ), - ] - - -class ResultCounts(BaseModel): - total: Annotated[int, Field(description='Total number of executed output items.')] - errored: Annotated[ - int, Field(description='Number of output items that resulted in an error.') - ] - failed: Annotated[ - int, - Field(description='Number of output items that failed to pass the evaluation.'), - ] - passed: Annotated[ - int, Field(description='Number of output items that passed the evaluation.') - ] - - -class PerModelUsageItem(BaseModel): - model_name: Annotated[str, Field(description='The name of the model.')] - invocation_count: Annotated[int, Field(description='The number of invocations.')] - prompt_tokens: Annotated[ - int, Field(description='The number of prompt tokens used.') - ] - completion_tokens: Annotated[ - int, Field(description='The number of completion tokens generated.') - ] - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - cached_tokens: Annotated[ - int, Field(description='The number of tokens retrieved from cache.') - ] - - -class PerTestingCriteriaResult(BaseModel): - testing_criteria: Annotated[ - str, Field(description='A description of the testing criteria.') - ] - passed: Annotated[ - int, Field(description='Number of tests passed for this criteria.') - ] - failed: Annotated[ - int, Field(description='Number of tests failed for this criteria.') - ] - - -class InputItem(BaseModel): - role: Annotated[ - str, - Field( - description='The role of the message sender (e.g., system, user, developer).' - ), - ] - content: Annotated[str, Field(description='The content of the message.')] - - -class OutputItem(BaseModel): - role: Annotated[ - Optional[str], - Field( - description='The role of the message (e.g. "system", "assistant", "user").' - ), - ] = None - content: Annotated[ - Optional[str], Field(description='The content of the message.') - ] = None - - -class Usage2(BaseModel): - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - completion_tokens: Annotated[ - int, Field(description='The number of completion tokens generated.') - ] - prompt_tokens: Annotated[ - int, Field(description='The number of prompt tokens used.') - ] - cached_tokens: Annotated[ - int, Field(description='The number of tokens retrieved from cache.') - ] - - -class Sample(BaseModel): - input: Annotated[List[InputItem], Field(description='An array of input messages.')] - output: Annotated[ - List[OutputItem], Field(description='An array of output messages.') - ] - finish_reason: Annotated[ - str, Field(description='The reason why the sample generation was finished.') - ] - model: Annotated[ - str, Field(description='The model used for generating the sample.') - ] - usage: Annotated[Usage2, Field(description='Token usage details for the sample.')] - error: EvalApiError - temperature: Annotated[float, Field(description='The sampling temperature used.')] - max_completion_tokens: Annotated[ - int, Field(description='The maximum number of tokens allowed for completion.') - ] - top_p: Annotated[float, Field(description='The top_p value used for sampling.')] - seed: Annotated[int, Field(description='The seed used for generating the sample.')] - - -class EvalRunOutputItemResult(BaseModel): - class Config: - extra = Extra.allow - - name: Annotated[str, Field(description='The name of the grader.')] - type: Annotated[ - Optional[str], - Field(description='The grader type (for example, "string-check-grader").'), - ] = None - score: Annotated[ - float, Field(description='The numeric score produced by the grader.') - ] - passed: Annotated[ - bool, Field(description='Whether the grader considered the output a pass.') - ] - sample: Annotated[ - Optional[Dict[str, Any]], - Field( - description='Optional sample or intermediate data produced by the grader.' - ), - ] = None - - -class FileExpirationAfter(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.' - ), - ] - seconds: Annotated[ - int, - Field( - description='The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).', - ge=3600, - le=2592000, - ), - ] - - -class FilePath(BaseModel): - type: Annotated[ - Literal['FilePath'], - Field(description='The type of the file path. Always `file_path`.\n'), - ] - file_id: Annotated[str, Field(description='The ID of the file.\n')] - index: Annotated[ - int, Field(description='The index of the file in the list of files.\n') - ] - - -class FileSearchRanker(BaseModel): - __root__: Annotated[ - Literal['auto', 'default_2024_08_21'], - Field( - description='The ranker to use for the file search. If not specified will use the `auto` ranker.' - ), - ] - - -class FileSearchRankingOptions(BaseModel): - ranker: Optional[FileSearchRanker] = None - score_threshold: Annotated[ - float, - Field( - description='The score threshold for the file search. All values must be a floating point number between 0 and 1.', - ge=0.0, - le=1.0, - ), - ] - - -class Beta(BaseModel): - __root__: Annotated[ - float, - Field( - description='The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n', - gt=0.0, - le=2.0, - ), - ] - - -class BatchSize1(BaseModel): - __root__: Annotated[ - int, - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n', - ge=1, - le=256, - ), - ] - - -class LearningRateMultiplier1(BaseModel): - __root__: Annotated[ - float, - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n', - gt=0.0, - ), - ] - - -class NEpochs1(BaseModel): - __root__: Annotated[ - int, - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n', - ge=1, - le=50, - ), - ] - - -class FineTuneDPOHyperparameters(BaseModel): - beta: Annotated[ - Optional[Union[Literal['auto'], Beta]], - Field( - description='The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n' - ), - ] = None - batch_size: Annotated[ - Union[Literal['auto'], BatchSize1], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier1]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs1], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n' - ), - ] = 'auto' - - -class FineTuneDPOMethod(BaseModel): - hyperparameters: Optional[FineTuneDPOHyperparameters] = None - - -class ComputeMultiplier(BaseModel): - __root__: Annotated[ - float, - Field( - description='Multiplier on amount of compute used for exploring search space during training.\n', - gt=1e-05, - le=10.0, - ), - ] - - -class EvalInterval(BaseModel): - __root__: Annotated[ - int, - Field( - description='The number of training steps between evaluation runs.\n', ge=1 - ), - ] - - -class EvalSamples(BaseModel): - __root__: Annotated[ - int, - Field( - description='Number of evaluation samples to generate per training step.\n', - ge=1, - ), - ] - - -class FineTuneReinforcementHyperparameters(BaseModel): - batch_size: Annotated[ - Union[Literal['auto'], BatchSize1], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier1]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs1], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n' - ), - ] = 'auto' - reasoning_effort: Annotated[ - Literal['default', 'low', 'medium', 'high'], - Field(description='Level of reasoning effort.\n'), - ] = 'default' - compute_multiplier: Annotated[ - Optional[Union[Literal['auto'], ComputeMultiplier]], - Field( - description='Multiplier on amount of compute used for exploring search space during training.\n' - ), - ] = None - eval_interval: Annotated[ - Union[Literal['auto'], EvalInterval], - Field(description='The number of training steps between evaluation runs.\n'), - ] = 'auto' - eval_samples: Annotated[ - Union[Literal['auto'], EvalSamples], - Field( - description='Number of evaluation samples to generate per training step.\n' - ), - ] = 'auto' - - -class FineTuneSupervisedHyperparameters(BaseModel): - batch_size: Annotated[ - Union[Literal['auto'], BatchSize1], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier1]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs1], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n' - ), - ] = 'auto' - - -class FineTuneSupervisedMethod(BaseModel): - hyperparameters: Optional[FineTuneSupervisedHyperparameters] = None - - -class FineTuningCheckpointPermission(BaseModel): - id: Annotated[ - str, - Field( - description='The permission identifier, which can be referenced in the API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the permission was created.' - ), - ] - project_id: Annotated[ - str, Field(description='The project identifier that the permission is for.') - ] - object: Annotated[ - Literal['checkpoint.permission'], - Field(description='The object type, which is always "checkpoint.permission".'), - ] - - -class Wandb1(BaseModel): - project: Annotated[ - str, - Field( - description='The name of the project that the new run will be created under.\n', - example='my-wandb-project', - ), - ] - name: Optional[str] = None - entity: Optional[str] = None - tags: Annotated[ - Optional[List[str]], - Field( - description='A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}".\n' - ), - ] = None - - -class FineTuningIntegration(BaseModel): - type: Annotated[ - Literal['wandb'], - Field( - description='The type of the integration being enabled for the fine-tuning job' - ), - ] - wandb: Annotated[ - Wandb1, - Field( - description='The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n' - ), - ] - - -class Error2(BaseModel): - code: Annotated[str, Field(description='A machine-readable error code.')] - message: Annotated[str, Field(description='A human-readable error message.')] - param: Optional[str] - - -class BatchSize4(BaseModel): - __root__: Annotated[ - int, - Field( - description='Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n', - ge=1, - le=256, - title='Auto', - ), - ] - - -class LearningRateMultiplier4(BaseModel): - __root__: Annotated[ - float, - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n', - gt=0.0, - ), - ] - - -class NEpochs4(BaseModel): - __root__: Annotated[ - int, - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n', - ge=1, - le=50, - ), - ] - - -class Hyperparameters1(BaseModel): - batch_size: Optional[Union[Literal['auto'], BatchSize4]] = None - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier4]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs4], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n' - ), - ] = 'auto' - - -class Integrations1(BaseModel): - __root__: Annotated[FineTuningIntegration, Field(discriminator='type')] - - -class Integrations(BaseModel): - __root__: Annotated[ - List[Integrations1], - Field( - description='A list of integrations to enable for this fine-tuning job.', - max_items=5, - ), - ] - - -class Metrics(BaseModel): - step: Optional[float] = None - train_loss: Optional[float] = None - train_mean_token_accuracy: Optional[float] = None - valid_loss: Optional[float] = None - valid_mean_token_accuracy: Optional[float] = None - full_valid_loss: Optional[float] = None - full_valid_mean_token_accuracy: Optional[float] = None - - -class FineTuningJobCheckpoint(BaseModel): - id: Annotated[ - str, - Field( - description='The checkpoint identifier, which can be referenced in the API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the checkpoint was created.' - ), - ] - fine_tuned_model_checkpoint: Annotated[ - str, - Field( - description='The name of the fine-tuned checkpoint model that is created.' - ), - ] - step_number: Annotated[ - int, Field(description='The step number that the checkpoint was created at.') - ] - metrics: Annotated[ - Metrics, - Field(description='Metrics at the step number during the fine-tuning job.'), - ] - fine_tuning_job_id: Annotated[ - str, - Field( - description='The name of the fine-tuning job that this checkpoint was created from.' - ), - ] - object: Annotated[ - Literal['fine_tuning.job.checkpoint'], - Field( - description='The object type, which is always "fine_tuning.job.checkpoint".' - ), - ] - - -class FineTuningJobEvent(BaseModel): - object: Annotated[ - Literal['fine_tuning.job.event'], - Field(description='The object type, which is always "fine_tuning.job.event".'), - ] - id: Annotated[str, Field(description='The object identifier.')] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the fine-tuning job was created.' - ), - ] - level: Annotated[ - Literal['info', 'warn', 'error'], - Field(description='The log level of the event.'), - ] - message: Annotated[str, Field(description='The message of the event.')] - type: Annotated[ - Optional[Literal['message', 'metrics']], Field(description='The type of event.') - ] = None - data: Annotated[ - Optional[Dict[str, Any]], - Field(description='The data associated with the event.'), - ] = None - - -class FunctionParameters(BaseModel): - pass - - class Config: - extra = Extra.allow - - -class FunctionToolCall(BaseModel): - id: Annotated[ - Optional[str], Field(description='The unique ID of the function tool call.\n') - ] = None - type: Annotated[ - Literal['FunctionToolCall'], - Field( - description='The type of the function tool call. Always `function_call`.\n' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the function tool call generated by the model.\n' - ), - ] - name: Annotated[str, Field(description='The name of the function to run.\n')] - arguments: Annotated[ - str, - Field(description='A JSON string of the arguments to pass to the function.\n'), - ] - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' - ), - ] = None - - -class FunctionToolCallResource(FunctionToolCall): - id: Annotated[str, Field(description='The unique ID of the function tool call.\n')] - type: Literal['FunctionToolCallResource'] - - -class GraderPython(BaseModel): - type: Annotated[ - Literal['GraderPython'], - Field(description='The object type, which is always `python`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - source: Annotated[str, Field(description='The source code of the python script.')] - image_tag: Annotated[ - Optional[str], Field(description='The image tag to use for the python script.') - ] = None - - -class MaxCompletionsTokens(BaseModel): - __root__: Annotated[ - int, - Field( - description='The maximum number of tokens the grader model may generate in its response.\n', - ge=1, - ), - ] - - -class GraderStringCheck(BaseModel): - type: Annotated[ - Literal['GraderStringCheck'], - Field(description='The object type, which is always `string_check`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - input: Annotated[ - str, Field(description='The input text. This may include template strings.') - ] - reference: Annotated[ - str, Field(description='The reference text. This may include template strings.') - ] - operation: Annotated[ - Literal['eq', 'ne', 'like', 'ilike'], - Field( - description='The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.' - ), - ] - - -class GraderTextSimilarity(BaseModel): - type: Annotated[ - Literal['GraderTextSimilarity'], Field(description='The type of grader.') - ] - name: Annotated[str, Field(description='The name of the grader.')] - input: Annotated[str, Field(description='The text being graded.')] - reference: Annotated[str, Field(description='The text being graded against.')] - evaluation_metric: Annotated[ - Literal[ - 'cosine', - 'fuzzy_match', - 'bleu', - 'gleu', - 'meteor', - 'rouge_1', - 'rouge_2', - 'rouge_3', - 'rouge_4', - 'rouge_5', - 'rouge_l', - ], - Field( - description='The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n' - ), - ] - - -class Group(BaseModel): - object: Annotated[Literal['group'], Field(description='Always `group`.')] - id: Annotated[str, Field(description='Identifier for the group.')] - name: Annotated[str, Field(description='Display name of the group.')] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) when the group was created.'), - ] - scim_managed: Annotated[ - bool, Field(description='Whether the group is managed through SCIM.') - ] - - -class GroupDeletedResource(BaseModel): - object: Annotated[ - Literal['group.deleted'], Field(description='Always `group.deleted`.') - ] - id: Annotated[str, Field(description='Identifier of the deleted group.')] - deleted: Annotated[bool, Field(description='Whether the group was deleted.')] - - -class GroupResourceWithSuccess(BaseModel): - id: Annotated[str, Field(description='Identifier for the group.')] - name: Annotated[str, Field(description='Updated display name for the group.')] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) when the group was created.'), - ] - is_scim_managed: Annotated[ - bool, - Field( - description='Whether the group is managed through SCIM and controlled by your identity provider.' - ), - ] - - -class GroupResponse(BaseModel): - id: Annotated[str, Field(description='Identifier for the group.')] - name: Annotated[str, Field(description='Display name of the group.')] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) when the group was created.'), - ] - is_scim_managed: Annotated[ - bool, - Field( - description='Whether the group is managed through SCIM and controlled by your identity provider.' - ), - ] - - -class GroupUserAssignment(BaseModel): - object: Annotated[Literal['group.user'], Field(description='Always `group.user`.')] - user_id: Annotated[str, Field(description='Identifier of the user that was added.')] - group_id: Annotated[ - str, Field(description='Identifier of the group the user was added to.') - ] - - -class GroupUserDeletedResource(BaseModel): - object: Annotated[ - Literal['group.user.deleted'], Field(description='Always `group.user.deleted`.') - ] - deleted: Annotated[ - bool, Field(description='Whether the group membership was removed.') - ] - - -class Image1(BaseModel): - b64_json: Annotated[ - Optional[str], - Field( - description='The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`.' - ), - ] = None - url: Annotated[ - Optional[str], - Field( - description='When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for `gpt-image-1`.' - ), - ] = None - revised_prompt: Annotated[ - Optional[str], - Field( - description='For `dall-e-3` only, the revised prompt that was used to generate the image.' - ), - ] = None - - -class ImageEditPartialImageEvent(BaseModel): - type: Annotated[ - Literal['ImageEditPartialImageEvent'], - Field( - description='The type of the event. Always `image_edit.partial_image`.\n' - ), - ] - b64_json: Annotated[ - str, - Field( - description='Base64-encoded partial image data, suitable for rendering as an image.\n' - ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the requested edited image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the requested edited image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the requested edited image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the requested edited image.\n'), - ] - partial_image_index: Annotated[ - int, Field(description='0-based index for the partial image (streaming).\n') - ] - - -class ImageGenPartialImageEvent(BaseModel): - type: Annotated[ - Literal['ImageGenPartialImageEvent'], - Field( - description='The type of the event. Always `image_generation.partial_image`.\n' - ), - ] - b64_json: Annotated[ - str, - Field( - description='Base64-encoded partial image data, suitable for rendering as an image.\n' - ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the requested image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the requested image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the requested image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the requested image.\n'), - ] - partial_image_index: Annotated[ - int, Field(description='0-based index for the partial image (streaming).\n') - ] - - -class InputImageMask(BaseModel): - class Config: - extra = Extra.forbid - - image_url: Annotated[ - Optional[str], Field(description='Base64-encoded mask image.\n') - ] = None - file_id: Annotated[ - Optional[str], Field(description='File ID for the mask image.\n') - ] = None - - -class ImageGenToolCall(BaseModel): - type: Annotated[ - Literal['ImageGenToolCall'], - Field( - description='The type of the image generation call. Always `image_generation_call`.\n' - ), - ] - id: Annotated[ - str, Field(description='The unique ID of the image generation call.\n') - ] - status: Annotated[ - Literal['in_progress', 'completed', 'generating', 'failed'], - Field(description='The status of the image generation call.\n'), - ] - result: Optional[str] - - -class InputTokensDetails1(BaseModel): - text_tokens: Annotated[ - int, Field(description='The number of text tokens in the input prompt.') - ] - image_tokens: Annotated[ - int, Field(description='The number of image tokens in the input prompt.') - ] - - -class ImagesUsage(BaseModel): - total_tokens: Annotated[ - int, - Field( - description='The total number of tokens (images and text) used for the image generation.\n' - ), - ] - input_tokens: Annotated[ - int, - Field( - description='The number of tokens (images and text) in the input prompt.' - ), - ] - output_tokens: Annotated[ - int, Field(description='The number of image tokens in the output image.') - ] - input_tokens_details: Annotated[ - InputTokensDetails1, - Field( - description='The input tokens detailed information for the image generation.' - ), - ] - - -class InputAudio1(BaseModel): - data: Annotated[str, Field(description='Base64-encoded audio data.\n')] - format: Annotated[ - Literal['mp3', 'wav'], - Field( - description='The format of the audio data. Currently supported formats are `mp3` and\n`wav`.\n' - ), - ] - - -class InputAudioModel(BaseModel): - type: Annotated[ - Literal['input_audio'], - Field(description='The type of the input item. Always `input_audio`.\n'), - ] - input_audio: InputAudio1 - - -class Project1(BaseModel): - id: Annotated[Optional[str], Field(description="Project's public ID")] = None - role: Annotated[ - Optional[Literal['member', 'owner']], - Field(description='Project membership role'), - ] = None - - -class Invite(BaseModel): - object: Annotated[ - Literal['organization.invite'], - Field(description='The object type, which is always `organization.invite`'), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - email: Annotated[ - str, - Field( - description='The email address of the individual to whom the invite was sent' - ), - ] - role: Annotated[ - Literal['owner', 'reader'], Field(description='`owner` or `reader`') - ] - status: Annotated[ - Literal['accepted', 'expired', 'pending'], - Field(description='`accepted`,`expired`, or `pending`'), - ] - invited_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the invite was sent.' - ), - ] - expires_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the invite expires.' - ), - ] - accepted_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) of when the invite was accepted.' - ), - ] = None - projects: Annotated[ - Optional[List[Project1]], - Field( - description='The projects that were granted membership upon acceptance of the invite.' - ), - ] = None - - -class InviteDeleteResponse(BaseModel): - object: Annotated[ - Literal['organization.invite.deleted'], - Field( - description='The object type, which is always `organization.invite.deleted`' - ), - ] - id: str - deleted: bool - - -class InviteListResponse(BaseModel): - object: Annotated[ - Literal['list'], Field(description='The object type, which is always `list`') - ] - data: List[Invite] - first_id: Annotated[ - Optional[str], - Field(description='The first `invite_id` in the retrieved `list`'), - ] = None - last_id: Annotated[ - Optional[str], Field(description='The last `invite_id` in the retrieved `list`') - ] = None - has_more: Annotated[ - Optional[bool], - Field( - description='The `has_more` property is used for pagination to indicate there are additional results.' - ), - ] = None - - -class InviteProjectGroupBody(BaseModel): - group_id: Annotated[ - str, Field(description='Identifier of the group to add to the project.') - ] - role: Annotated[ - str, Field(description='Identifier of the project role to grant to the group.') - ] - - -class Project2(BaseModel): - id: Annotated[str, Field(description="Project's public ID")] - role: Annotated[ - Literal['member', 'owner'], Field(description='Project membership role') - ] - - -class InviteRequest(BaseModel): - email: Annotated[str, Field(description='Send an email to this address')] - role: Annotated[ - Literal['reader', 'owner'], Field(description='`owner` or `reader`') - ] - projects: Annotated[ - Optional[List[Project2]], - Field( - description='An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior.' - ), - ] = None - - -class ListCertificatesResponse(BaseModel): - data: List[Certificate2] - first_id: Annotated[Optional[str], Field(example='cert_abc')] = None - last_id: Annotated[Optional[str], Field(example='cert_abc')] = None - has_more: bool - object: Literal['list'] - - -class ListFineTuningCheckpointPermissionResponse(BaseModel): - data: List[FineTuningCheckpointPermission] - object: Literal['list'] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: bool - - -class ListFineTuningJobCheckpointsResponse(BaseModel): - data: List[FineTuningJobCheckpoint] - object: Literal['list'] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: bool - - -class ListFineTuningJobEventsResponse(BaseModel): - data: List[FineTuningJobEvent] - object: Literal['list'] - has_more: bool - - -class LocalShellToolCallOutput(BaseModel): - type: Annotated[ - Literal['LocalShellToolCallOutput'], - Field( - description='The type of the local shell tool call output. Always `local_shell_call_output`.\n' - ), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the local shell tool call generated by the model.\n' - ), - ] - output: Annotated[ - str, - Field( - description='A JSON string of the output of the local shell tool call.\n' - ), - ] - status: Optional[Literal['in_progress', 'completed', 'incomplete']] = None - - -class LogProbProperties(BaseModel): - token: Annotated[ - str, - Field(description='The token that was used to generate the log probability.\n'), - ] - logprob: Annotated[float, Field(description='The log probability of the token.\n')] - bytes: Annotated[ - List[int], - Field( - description='The bytes that were used to generate the log probability.\n' - ), - ] - - -class MCPApprovalRequest(BaseModel): - type: Annotated[ - Literal['MCPApprovalRequest'], - Field(description='The type of the item. Always `mcp_approval_request`.\n'), - ] - id: Annotated[str, Field(description='The unique ID of the approval request.\n')] - server_label: Annotated[ - str, Field(description='The label of the MCP server making the request.\n') - ] - name: Annotated[str, Field(description='The name of the tool to run.\n')] - arguments: Annotated[ - str, Field(description='A JSON string of arguments for the tool.\n') - ] - - -class MCPApprovalResponse(BaseModel): - type: Annotated[ - Literal['MCPApprovalResponse'], - Field(description='The type of the item. Always `mcp_approval_response`.\n'), - ] - id: Optional[str] = None - approval_request_id: Annotated[ - str, Field(description='The ID of the approval request being answered.\n') - ] - approve: Annotated[bool, Field(description='Whether the request was approved.\n')] - reason: Optional[str] = None - - -class MCPApprovalResponseResource(BaseModel): - type: Annotated[ - Literal['MCPApprovalResponseResource'], - Field(description='The type of the item. Always `mcp_approval_response`.\n'), - ] - id: Annotated[str, Field(description='The unique ID of the approval response\n')] - approval_request_id: Annotated[ - str, Field(description='The ID of the approval request being answered.\n') - ] - approve: Annotated[bool, Field(description='Whether the request was approved.\n')] - reason: Optional[str] = None - - -class MCPListToolsTool(BaseModel): - name: Annotated[str, Field(description='The name of the tool.\n')] - description: Optional[str] = None - input_schema: Annotated[ - Dict[str, Any], - Field(description="The JSON schema describing the tool's input.\n"), - ] - annotations: Optional[Dict[str, Any]] = None - - -class MCPToolFilter(BaseModel): - class Config: - extra = Extra.forbid - - tool_names: Annotated[ - Optional[List[str]], - Field(description='List of allowed tool names.', title='MCP allowed tools'), - ] = None - read_only: Annotated[ - Optional[bool], - Field( - description='Indicates whether or not a tool modifies data or is read-only. If an\nMCP server is [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),\nit will match this filter.\n' - ), - ] = None - - -class ImageFile(BaseModel): - file_id: Annotated[ - str, - Field( - description='The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' - ), - ] - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.' - ), - ] = 'auto' - - -class MessageContentImageFileObject(BaseModel): - type: Annotated[ - Literal['MessageContentImageFileObject'], - Field(description='Always `image_file`.'), - ] - image_file: ImageFile - - -class ImageUrl1(BaseModel): - url: Annotated[ - AnyUrl, - Field( - description='The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' - ), - ] - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`' - ), - ] = 'auto' - - -class MessageContentImageUrlObject(BaseModel): - type: Annotated[ - Literal['MessageContentImageUrlObject'], - Field(description='The type of the content part.'), - ] - image_url: ImageUrl1 - - -class MessageContentRefusalObject(BaseModel): - type: Annotated[ - Literal['MessageContentRefusalObject'], Field(description='Always `refusal`.') - ] - refusal: str - - -class FileCitation(BaseModel): - file_id: Annotated[ - str, Field(description='The ID of the specific File the citation is from.') - ] - - -class MessageContentTextAnnotationsFileCitationObject(BaseModel): - type: Annotated[ - Literal['MessageContentTextAnnotationsFileCitationObject'], - Field(description='Always `file_citation`.'), - ] - text: Annotated[ - str, - Field(description='The text in the message content that needs to be replaced.'), - ] - file_citation: FileCitation - start_index: Annotated[int, Field(ge=0)] - end_index: Annotated[int, Field(ge=0)] - - -class FilePath1(BaseModel): - file_id: Annotated[str, Field(description='The ID of the file that was generated.')] - - -class MessageContentTextAnnotationsFilePathObject(BaseModel): - type: Annotated[ - Literal['MessageContentTextAnnotationsFilePathObject'], - Field(description='Always `file_path`.'), - ] - text: Annotated[ - str, - Field(description='The text in the message content that needs to be replaced.'), - ] - file_path: FilePath1 - start_index: Annotated[int, Field(ge=0)] - end_index: Annotated[int, Field(ge=0)] - - -class ImageFile1(BaseModel): - file_id: Annotated[ - Optional[str], - Field( - description='The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' - ), - ] = None - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.' - ), - ] = 'auto' - - -class MessageDeltaContentImageFileObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the content part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentImageFileObject'], - Field(description='Always `image_file`.'), - ] - image_file: Optional[ImageFile1] = None - - -class ImageUrl2(BaseModel): - url: Annotated[ - Optional[str], - Field( - description='The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' - ), - ] = None - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`.' - ), - ] = 'auto' - - -class MessageDeltaContentImageUrlObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the content part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentImageUrlObject'], - Field(description='Always `image_url`.'), - ] - image_url: Optional[ImageUrl2] = None - - -class MessageDeltaContentRefusalObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the refusal part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentRefusalObject'], - Field(description='Always `refusal`.'), - ] - refusal: Optional[str] = None - - -class FileCitation1(BaseModel): - file_id: Annotated[ - Optional[str], - Field(description='The ID of the specific File the citation is from.'), - ] = None - quote: Annotated[ - Optional[str], Field(description='The specific quote in the file.') - ] = None - - -class MessageDeltaContentTextAnnotationsFileCitationObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the annotation in the text content part.') - ] - type: Annotated[ - Literal['MessageDeltaContentTextAnnotationsFileCitationObject'], - Field(description='Always `file_citation`.'), - ] - text: Annotated[ - Optional[str], - Field(description='The text in the message content that needs to be replaced.'), - ] = None - file_citation: Optional[FileCitation1] = None - start_index: Annotated[Optional[int], Field(ge=0)] = None - end_index: Annotated[Optional[int], Field(ge=0)] = None - - -class FilePath2(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The ID of the file that was generated.') - ] = None - - -class MessageDeltaContentTextAnnotationsFilePathObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the annotation in the text content part.') - ] - type: Annotated[ - Literal['MessageDeltaContentTextAnnotationsFilePathObject'], - Field(description='Always `file_path`.'), - ] - text: Annotated[ - Optional[str], - Field(description='The text in the message content that needs to be replaced.'), - ] = None - file_path: Optional[FilePath2] = None - start_index: Annotated[Optional[int], Field(ge=0)] = None - end_index: Annotated[Optional[int], Field(ge=0)] = None - - -class IncompleteDetails(BaseModel): - reason: Annotated[ - Literal[ - 'content_filter', 'max_tokens', 'run_cancelled', 'run_expired', 'run_failed' - ], - Field(description='The reason the message is incomplete.'), - ] - - -class Attachment1(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The ID of the file to attach to the message.') - ] = None - tools: Annotated[ - Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly]]], - Field(description='The tools to add this file to.'), - ] = None - - -class MessageRequestContentTextObject(BaseModel): - type: Annotated[ - Literal['MessageRequestContentTextObject'], Field(description='Always `text`.') - ] - text: Annotated[str, Field(description='Text content to be sent to the model')] - - -class Metadata(BaseModel): - __root__: Optional[Dict[str, str]] - - -class Model(BaseModel): - id: Annotated[ - str, - Field( - description='The model identifier, which can be referenced in the API endpoints.' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) when the model was created.' - ), - ] - object: Annotated[ - Literal['model'], Field(description='The object type, which is always "model".') - ] - owned_by: Annotated[str, Field(description='The organization that owns the model.')] - - -class TopLogprobs(BaseModel): - __root__: Annotated[ - int, - Field( - description='An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n', - ge=0, - le=20, - ), - ] - - -class Temperature2(BaseModel): - __root__: Annotated[ - float, - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n', - example=1, - ge=0.0, - le=2.0, - ), - ] - - -class TopP2(BaseModel): - __root__: Annotated[ - float, - Field( - description='An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n', - example=1, - ge=0.0, - le=1.0, - ), - ] - - -class CodeInterpreter4(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n', - max_items=20, - ), - ] = [] - - -class FileSearch7(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] = None - - -class ToolResources4(BaseModel): - code_interpreter: Optional[CodeInterpreter4] = None - file_search: Optional[FileSearch7] = None - - -class Temperature3(BaseModel): - __root__: Annotated[ - float, - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - example=1, - ge=0.0, - le=2.0, - ), - ] - - -class TopP3(BaseModel): - __root__: Annotated[ - float, - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - example=1, - ge=0.0, - le=1.0, - ), - ] - - -class ModifyCertificateRequest(BaseModel): - name: Annotated[str, Field(description='The updated name for the certificate')] - - -class ModifyMessageRequest(BaseModel): - class Config: - extra = Extra.forbid - - metadata: Optional[Metadata] = None - - -class ModifyRunRequest(BaseModel): - class Config: - extra = Extra.forbid - - metadata: Optional[Metadata] = None - - -class CodeInterpreter5(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n', - max_items=20, - ), - ] = [] - - -class FileSearch8(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_items=1, - ), - ] = None - - -class ToolResources5(BaseModel): - code_interpreter: Optional[CodeInterpreter5] = None - file_search: Optional[FileSearch8] = None - - -class ModifyThreadRequest(BaseModel): - class Config: - extra = Extra.forbid - - tool_resources: Optional[ToolResources5] = None - metadata: Optional[Metadata] = None - - -class Move(BaseModel): - type: Annotated[ - Literal['Move'], - Field( - description='Specifies the event type. For a move action, this property is \nalways set to `move`.\n' - ), - ] - x: Annotated[int, Field(description='The x-coordinate to move to.\n')] - y: Annotated[int, Field(description='The y-coordinate to move to.\n')] - - -class NoiseReductionType(BaseModel): - __root__: Annotated[ - Literal['near_field', 'far_field'], - Field( - description='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.\n' - ), - ] - - -class OpenAIFile(BaseModel): - id: Annotated[ - str, - Field( - description='The file identifier, which can be referenced in the API endpoints.' - ), - ] - bytes: Annotated[int, Field(description='The size of the file, in bytes.')] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the file was created.' - ), - ] - expires_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the file will expire.' - ), - ] = None - filename: Annotated[str, Field(description='The name of the file.')] - object: Annotated[ - Literal['file'], Field(description='The object type, which is always `file`.') - ] - purpose: Annotated[ - Literal[ - 'assistants', - 'assistants_output', - 'batch', - 'batch_output', - 'fine-tune', - 'fine-tune-results', - 'vision', - 'user_data', - ], - Field( - description='The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.' - ), - ] - status: Annotated[ - Literal['uploaded', 'processed', 'error'], - Field( - description='Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.' - ), - ] - status_details: Annotated[ - Optional[str], - Field( - description='Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`.' - ), - ] = None - - -class OtherChunkingStrategyResponseParam(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['OtherChunkingStrategyResponseParam'], - Field(description='Always `other`.'), - ] - - -class OutputAudio(BaseModel): - type: Annotated[ - Literal['output_audio'], - Field(description='The type of the output audio. Always `output_audio`.\n'), - ] - data: Annotated[ - str, Field(description='Base64-encoded audio data from the model.\n') - ] - transcript: Annotated[ - str, Field(description='The transcript of the audio data from the model.\n') - ] - - -class ParallelToolCalls(BaseModel): - __root__: Annotated[ - bool, - Field( - description='Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use.' - ), - ] - - -class PartialImages1(BaseModel): - __root__: Annotated[ - int, - Field( - description='The number of partial images to generate. This parameter is used for\nstreaming responses that return partial images. Value must be between 0 and 3.\nWhen set to 0, the response will be a single image sent in one streaming event.\n\nNote that the final image may be sent before the full number of partial images\nare generated if the full image is generated more quickly.\n', - example=1, - ge=0, - le=3, - ), - ] - - -class PartialImages(BaseModel): - __root__: Optional[PartialImages1] - - -class Content9(BaseModel): - __root__: Annotated[ - List[ChatCompletionRequestMessageContentPartText], - Field( - description='An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text inputs.', - min_items=1, - title='Array of content parts', - ), - ] - - -class PredictionContent(BaseModel): - type: Annotated[ - Literal['PredictionContent'], - Field( - description='The type of the predicted content you want to provide. This type is\ncurrently always `content`.\n' - ), - ] - content: Annotated[ - Union[str, Content9], - Field( - description='The content that should be matched when generating a model response.\nIf generated tokens would match this content, the entire model response\ncan be returned much more quickly.\n' - ), - ] - - -class Project3(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - object: Annotated[ - Literal['organization.project'], - Field(description='The object type, which is always `organization.project`'), - ] - name: Annotated[ - str, Field(description='The name of the project. This appears in reporting.') - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the project was created.' - ), - ] - archived_at: Optional[int] = None - status: Annotated[ - Literal['active', 'archived'], Field(description='`active` or `archived`') - ] - - -class ProjectApiKeyDeleteResponse(BaseModel): - object: Literal['organization.project.api_key.deleted'] - id: str - deleted: bool - - -class ProjectCreateRequest(BaseModel): - name: Annotated[ - str, - Field( - description='The friendly name of the project, this name appears in reports.' - ), - ] - geography: Annotated[ - Optional[Literal['US', 'EU', 'JP', 'IN', 'KR', 'CA', 'AU', 'SG']], - Field( - description='Create the project with the specified data residency region. Your organization must have access to Data residency functionality in order to use. See [data residency controls](https://platform.openai.com/docs/guides/your-data#data-residency-controls) to review the functionality and limitations of setting this field.' - ), - ] = None - - -class ProjectGroup(BaseModel): - object: Annotated[ - Literal['project.group'], Field(description='Always `project.group`.') - ] - project_id: Annotated[str, Field(description='Identifier of the project.')] - group_id: Annotated[ - str, - Field(description='Identifier of the group that has access to the project.'), - ] - group_name: Annotated[str, Field(description='Display name of the group.')] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) when the group was granted project access.' - ), - ] - - -class ProjectGroupDeletedResource(BaseModel): - object: Annotated[ - Literal['project.group.deleted'], - Field(description='Always `project.group.deleted`.'), - ] - deleted: Annotated[ - bool, - Field(description='Whether the group membership in the project was removed.'), - ] - - -class ProjectGroupListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[ProjectGroup], - Field(description='Project group memberships returned in the current page.'), - ] - has_more: Annotated[ - bool, - Field( - description='Whether additional project group memberships are available.' - ), - ] - next: Annotated[ - Optional[str], - Field( - description='Cursor to fetch the next page of results, or `null` when there are no more results.' - ), - ] - - -class ProjectListResponse(BaseModel): - object: Literal['list'] - data: List[Project3] - first_id: str - last_id: str - has_more: bool - - -class ProjectRateLimit(BaseModel): - object: Annotated[ - Literal['project.rate_limit'], - Field(description='The object type, which is always `project.rate_limit`'), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - model: Annotated[str, Field(description='The model this rate limit applies to.')] - max_requests_per_1_minute: Annotated[ - int, Field(description='The maximum requests per minute.') - ] - max_tokens_per_1_minute: Annotated[ - int, Field(description='The maximum tokens per minute.') - ] - max_images_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum images per minute. Only present for relevant models.' - ), - ] = None - max_audio_megabytes_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum audio megabytes per minute. Only present for relevant models.' - ), - ] = None - max_requests_per_1_day: Annotated[ - Optional[int], - Field( - description='The maximum requests per day. Only present for relevant models.' - ), - ] = None - batch_1_day_max_input_tokens: Annotated[ - Optional[int], - Field( - description='The maximum batch input tokens per day. Only present for relevant models.' - ), - ] = None - - -class ProjectRateLimitListResponse(BaseModel): - object: Literal['list'] - data: List[ProjectRateLimit] - first_id: str - last_id: str - has_more: bool - - -class ProjectRateLimitUpdateRequest(BaseModel): - max_requests_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum requests per minute.') - ] = None - max_tokens_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum tokens per minute.') - ] = None - max_images_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum images per minute. Only relevant for certain models.' - ), - ] = None - max_audio_megabytes_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum audio megabytes per minute. Only relevant for certain models.' - ), - ] = None - max_requests_per_1_day: Annotated[ - Optional[int], - Field( - description='The maximum requests per day. Only relevant for certain models.' - ), - ] = None - batch_1_day_max_input_tokens: Annotated[ - Optional[int], - Field( - description='The maximum batch input tokens per day. Only relevant for certain models.' - ), - ] = None - - -class ProjectServiceAccount(BaseModel): - object: Annotated[ - Literal['organization.project.service_account'], - Field( - description='The object type, which is always `organization.project.service_account`' - ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the service account')] - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the service account was created' - ), - ] - - -class ProjectServiceAccountApiKey(BaseModel): - object: Annotated[ - Literal['organization.project.service_account.api_key'], - Field( - description='The object type, which is always `organization.project.service_account.api_key`' - ), - ] - value: str - name: str - created_at: int - id: str - - -class ProjectServiceAccountCreateRequest(BaseModel): - name: Annotated[ - str, Field(description='The name of the service account being created.') - ] - - -class ProjectServiceAccountCreateResponse(BaseModel): - object: Literal['organization.project.service_account'] - id: str - name: str - role: Annotated[ - Literal['member'], - Field(description='Service accounts can only have one role of type `member`'), - ] - created_at: int - api_key: ProjectServiceAccountApiKey - - -class ProjectServiceAccountDeleteResponse(BaseModel): - object: Literal['organization.project.service_account.deleted'] - id: str - deleted: bool - - -class ProjectServiceAccountListResponse(BaseModel): - object: Literal['list'] - data: List[ProjectServiceAccount] - first_id: str - last_id: str - has_more: bool - - -class ProjectUpdateRequest(BaseModel): - name: Annotated[ - str, - Field( - description='The updated name of the project, this name appears in reports.' - ), - ] - - -class ProjectUser(BaseModel): - object: Annotated[ - Literal['organization.project.user'], - Field( - description='The object type, which is always `organization.project.user`' - ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the user')] - email: Annotated[str, Field(description='The email address of the user')] - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - added_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the project was added.' - ), - ] - - -class ProjectUserCreateRequest(BaseModel): - user_id: Annotated[str, Field(description='The ID of the user.')] - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - - -class ProjectUserDeleteResponse(BaseModel): - object: Literal['organization.project.user.deleted'] - id: str - deleted: bool - - -class ProjectUserListResponse(BaseModel): - object: str - data: List[ProjectUser] - first_id: str - last_id: str - has_more: bool - - -class ProjectUserUpdateRequest(BaseModel): - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - - -class PublicAssignOrganizationGroupRoleBody(BaseModel): - role_id: Annotated[str, Field(description='Identifier of the role to assign.')] - - -class PublicCreateOrganizationRoleBody(BaseModel): - role_name: Annotated[str, Field(description='Unique name for the role.')] - permissions: Annotated[ - List[str], Field(description='Permissions to grant to the role.') - ] - description: Annotated[ - Optional[str], Field(description='Optional description of the role.') - ] = None - - -class PublicUpdateOrganizationRoleBody(BaseModel): - permissions: Annotated[ - Optional[List[str]], - Field(description='Updated set of permissions for the role.'), - ] = None - description: Annotated[ - Optional[str], Field(description='New description for the role.') - ] = None - role_name: Annotated[Optional[str], Field(description='New name for the role.')] = ( - None - ) - - -class RealtimeAudioFormats1(BaseModel): - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The audio format. Always `audio/pcm`.'), - ] - rate: Annotated[ - Optional[Literal[24000]], - Field(description='The sample rate of the audio. Always `24000`.'), - ] = None - - -class RealtimeAudioFormats2(BaseModel): - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The audio format. Always `audio/pcmu`.'), - ] - - -class RealtimeAudioFormats3(BaseModel): - type: Annotated[ - Literal['2#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The audio format. Always `audio/pcma`.'), - ] - - -class RealtimeAudioFormats(BaseModel): - __root__: Annotated[ - Union[RealtimeAudioFormats1, RealtimeAudioFormats2, RealtimeAudioFormats3], - Field(discriminator='type'), - ] - - -class RealtimeBetaClientEventConversationItemDelete(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.delete`.', - ), - ] = 'conversation.item.delete' - item_id: Annotated[str, Field(description='The ID of the item to delete.')] - - -class RealtimeBetaClientEventConversationItemRetrieve(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.retrieve`.', - ), - ] = 'conversation.item.retrieve' - item_id: Annotated[str, Field(description='The ID of the item to retrieve.')] - - -class RealtimeBetaClientEventConversationItemTruncate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.truncate`.', - ), - ] = 'conversation.item.truncate' - item_id: Annotated[ - str, - Field( - description='The ID of the assistant message item to truncate. Only assistant message \nitems can be truncated.\n' - ), - ] - content_index: Annotated[ - int, - Field(description='The index of the content part to truncate. Set this to 0.'), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Inclusive duration up to which audio is truncated, in milliseconds. If \nthe audio_end_ms is greater than the actual audio duration, the server \nwill respond with an error.\n' - ), - ] - - -class RealtimeBetaClientEventInputAudioBufferAppend(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.append`.', - ), - ] = 'input_audio_buffer.append' - audio: Annotated[ - str, - Field( - description='Base64-encoded audio bytes. This must be in the format specified by the \n`input_audio_format` field in the session configuration.\n' - ), - ] - - -class RealtimeBetaClientEventInputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.clear`.', - ), - ] = 'input_audio_buffer.clear' - - -class RealtimeBetaClientEventInputAudioBufferCommit(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.commit`.', - ), - ] = 'input_audio_buffer.commit' - - -class RealtimeBetaClientEventOutputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='The unique ID of the client event used for error handling.'), - ] = None - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `output_audio_buffer.clear`.', - ), - ] = 'output_audio_buffer.clear' - - -class RealtimeBetaClientEventResponseCancel(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, Field(const=True, description='The event type, must be `response.cancel`.') - ] = 'response.cancel' - response_id: Annotated[ - Optional[str], - Field( - description='A specific response ID to cancel - if not provided, will cancel an \nin-progress response in the default conversation.\n' - ), - ] = None - - -class Error3(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - - -class StatusDetails(BaseModel): - type: Annotated[ - Optional[Literal['completed', 'cancelled', 'incomplete', 'failed']], - Field( - description='The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n' - ), - ] = None - reason: Annotated[ - Optional[ - Literal[ - 'turn_detected', - 'client_cancelled', - 'max_output_tokens', - 'content_filter', - ] - ], - Field( - description='The reason the Response did not complete. For a `cancelled` Response, \none of `turn_detected` (the server VAD detected a new start of speech) \nor `client_cancelled` (the client sent a cancel event). For an \n`incomplete` Response, one of `max_output_tokens` or `content_filter` \n(the server-side safety filter activated and cut off the response).\n' - ), - ] = None - error: Annotated[ - Optional[Error3], - Field( - description='A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n' - ), - ] = None - - -class CachedTokensDetails(BaseModel): - text_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached text tokens used as input for the Response.' - ), - ] = None - image_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached image tokens used as input for the Response.' - ), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached audio tokens used as input for the Response.' - ), - ] = None - - -class InputTokenDetails(BaseModel): - cached_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached tokens used as input for the Response.' - ), - ] = None - text_tokens: Annotated[ - Optional[int], - Field(description='The number of text tokens used as input for the Response.'), - ] = None - image_tokens: Annotated[ - Optional[int], - Field(description='The number of image tokens used as input for the Response.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='The number of audio tokens used as input for the Response.'), - ] = None - cached_tokens_details: Annotated[ - Optional[CachedTokensDetails], - Field( - description='Details about the cached tokens used as input for the Response.' - ), - ] = None - - -class OutputTokenDetails(BaseModel): - text_tokens: Annotated[ - Optional[int], - Field(description='The number of text tokens used in the Response.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='The number of audio tokens used in the Response.'), - ] = None - - -class Usage3(BaseModel): - total_tokens: Annotated[ - Optional[int], - Field( - description='The total number of tokens in the Response including input and output \ntext and audio tokens.\n' - ), - ] = None - input_tokens: Annotated[ - Optional[int], - Field( - description='The number of input tokens used in the Response, including text and \naudio tokens.\n' - ), - ] = None - output_tokens: Annotated[ - Optional[int], - Field( - description='The number of output tokens sent in the Response, including text and \naudio tokens.\n' - ), - ] = None - input_token_details: Annotated[ - Optional[InputTokenDetails], - Field(description='Details about the input tokens used in the Response.'), - ] = None - output_token_details: Annotated[ - Optional[OutputTokenDetails], - Field(description='Details about the output tokens used in the Response.'), - ] = None - - -class Tool1(BaseModel): - type: Annotated[ - Optional[Literal['function']], - Field(description='The type of the tool, i.e. `function`.'), - ] = None - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - description: Annotated[ - Optional[str], - Field( - description='The description of the function, including guidance on when and how \nto call it, and guidance about what to tell the user when calling \n(if anything).\n' - ), - ] = None - parameters: Annotated[ - Optional[Dict[str, Any]], - Field(description='Parameters of the function in JSON Schema.'), - ] = None - - -class RealtimeBetaServerEventConversationItemDeleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.deleted`.', - ), - ] = 'conversation.item.deleted' - item_id: Annotated[str, Field(description='The ID of the item that was deleted.')] - - -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.input_audio_transcription.delta`.', - ), - ] = 'conversation.item.input_audio_transcription.delta' - item_id: Annotated[str, Field(description='The ID of the item.')] - content_index: Annotated[ - Optional[int], - Field(description="The index of the content part in the item's content array."), - ] = None - delta: Annotated[Optional[str], Field(description='The text delta.')] = None - logprobs: Optional[List[LogProbProperties]] = None - - -class Error4(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - message: Annotated[ - Optional[str], Field(description='A human-readable error message.') - ] = None - param: Annotated[ - Optional[str], Field(description='Parameter related to the error, if any.') - ] = None - - -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.failed'], - Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.failed`.\n' - ), - ] - item_id: Annotated[str, Field(description='The ID of the user message item.')] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - error: Annotated[Error4, Field(description='Details of the transcription error.')] - - -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionSegment(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.input_audio_transcription.segment`.', - ), - ] = 'conversation.item.input_audio_transcription.segment' - item_id: Annotated[ - str, Field(description='The ID of the item containing the input audio content.') - ] - content_index: Annotated[ - int, - Field(description='The index of the input audio content part within the item.'), - ] - text: Annotated[str, Field(description='The text for this segment.')] - id: Annotated[str, Field(description='The segment identifier.')] - speaker: Annotated[ - str, Field(description='The detected speaker label for this segment.') - ] - start: Annotated[float, Field(description='Start time of the segment in seconds.')] - end: Annotated[float, Field(description='End time of the segment in seconds.')] - - -class RealtimeBetaServerEventConversationItemTruncated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `conversation.item.truncated`.', - ), - ] = 'conversation.item.truncated' - item_id: Annotated[ - str, - Field(description='The ID of the assistant message item that was truncated.'), - ] - content_index: Annotated[ - int, Field(description='The index of the content part that was truncated.') - ] - audio_end_ms: Annotated[ - int, - Field( - description='The duration up to which the audio was truncated, in milliseconds.\n' - ), - ] - - -class Error5(BaseModel): - type: Annotated[ - str, - Field( - description='The type of error (e.g., "invalid_request_error", "server_error").\n' - ), - ] - code: Optional[str] = None - message: Annotated[str, Field(description='A human-readable error message.')] - param: Optional[str] = None - event_id: Optional[str] = None - - -class RealtimeBetaServerEventError(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, Field(const=True, description='The event type, must be `error`.') - ] = 'error' - error: Annotated[Error5, Field(description='Details of the error.')] - - -class RealtimeBetaServerEventInputAudioBufferCleared(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.cleared`.', - ), - ] = 'input_audio_buffer.cleared' - - -class RealtimeBetaServerEventInputAudioBufferCommitted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.committed`.', - ), - ] = 'input_audio_buffer.committed' - previous_item_id: Optional[str] = None - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeBetaServerEventInputAudioBufferSpeechStarted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.speech_started`.', - ), - ] = 'input_audio_buffer.speech_started' - audio_start_ms: Annotated[ - int, - Field( - description='Milliseconds from the start of all audio written to the buffer during the \nsession when speech was first detected. This will correspond to the \nbeginning of audio sent to the model, and thus includes the \n`prefix_padding_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the user message item that will be created when speech stops.\n' - ), - ] - - -class RealtimeBetaServerEventInputAudioBufferSpeechStopped(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `input_audio_buffer.speech_stopped`.', - ), - ] = 'input_audio_buffer.speech_stopped' - audio_end_ms: Annotated[ - int, - Field( - description='Milliseconds since the session started when speech stopped. This will \ncorrespond to the end of audio sent to the model, and thus includes the \n`min_silence_duration_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeBetaServerEventMCPListToolsCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `mcp_list_tools.completed`.', - ), - ] = 'mcp_list_tools.completed' - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeBetaServerEventMCPListToolsFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, description='The event type, must be `mcp_list_tools.failed`.' - ), - ] = 'mcp_list_tools.failed' - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeBetaServerEventMCPListToolsInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `mcp_list_tools.in_progress`.', - ), - ] = 'mcp_list_tools.in_progress' - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RateLimit(BaseModel): - name: Annotated[ - Optional[Literal['requests', 'tokens']], - Field(description='The name of the rate limit (`requests`, `tokens`).\n'), - ] = None - limit: Annotated[ - Optional[int], - Field(description='The maximum allowed value for the rate limit.'), - ] = None - remaining: Annotated[ - Optional[int], - Field(description='The remaining value before the limit is reached.'), - ] = None - reset_seconds: Annotated[ - Optional[float], Field(description='Seconds until the rate limit resets.') - ] = None - - -class RealtimeBetaServerEventRateLimitsUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field(const=True, description='The event type, must be `rate_limits.updated`.'), - ] = 'rate_limits.updated' - rate_limits: Annotated[ - List[RateLimit], Field(description='List of rate limit information.') - ] - - -class RealtimeBetaServerEventResponseAudioDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.output_audio.delta`.', - ), - ] = 'response.output_audio.delta' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='Base64-encoded audio data delta.')] - - -class RealtimeBetaServerEventResponseAudioDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.output_audio.done`.', - ), - ] = 'response.output_audio.done' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - - -class RealtimeBetaServerEventResponseAudioTranscriptDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.output_audio_transcript.delta`.', - ), - ] = 'response.output_audio_transcript.delta' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The transcript delta.')] - - -class RealtimeBetaServerEventResponseAudioTranscriptDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.output_audio_transcript.done`.', - ), - ] = 'response.output_audio_transcript.done' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - transcript: Annotated[str, Field(description='The final transcript of the audio.')] - - -class Part(BaseModel): - type: Annotated[ - Optional[Literal['text', 'audio']], - Field(description='The content type ("text", "audio").'), - ] = None - text: Annotated[ - Optional[str], Field(description='The text content (if type is "text").') - ] = None - audio: Annotated[ - Optional[str], - Field(description='Base64-encoded audio data (if type is "audio").'), - ] = None - transcript: Annotated[ - Optional[str], - Field(description='The transcript of the audio (if type is "audio").'), - ] = None - - -class RealtimeBetaServerEventResponseContentPartAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.content_part.added`.', - ), - ] = 'response.content_part.added' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[ - str, - Field(description='The ID of the item to which the content part was added.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that was added.')] - - -class RealtimeBetaServerEventResponseContentPartDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.content_part.done`.', - ), - ] = 'response.content_part.done' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that is done.')] - - -class RealtimeBetaServerEventResponseFunctionCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.function_call_arguments.delta`.\n', - ), - ] = 'response.function_call_arguments.delta' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - delta: Annotated[str, Field(description='The arguments delta as a JSON string.')] - - -class RealtimeBetaServerEventResponseFunctionCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.function_call_arguments.done`.\n', - ), - ] = 'response.function_call_arguments.done' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - arguments: Annotated[ - str, Field(description='The final arguments as a JSON string.') - ] - - -class RealtimeBetaServerEventResponseMCPCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.mcp_call_arguments.delta`.', - ), - ] = 'response.mcp_call_arguments.delta' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - delta: Annotated[str, Field(description='The JSON-encoded arguments delta.')] - obfuscation: Optional[str] = None - - -class RealtimeBetaServerEventResponseMCPCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.mcp_call_arguments.done`.', - ), - ] = 'response.mcp_call_arguments.done' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - arguments: Annotated[ - str, Field(description='The final JSON-encoded arguments string.') - ] - - -class RealtimeBetaServerEventResponseMCPCallCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.mcp_call.completed`.', - ), - ] = 'response.mcp_call.completed' - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeBetaServerEventResponseMCPCallFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.mcp_call.failed`.', - ), - ] = 'response.mcp_call.failed' - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeBetaServerEventResponseMCPCallInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.mcp_call.in_progress`.', - ), - ] = 'response.mcp_call.in_progress' - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeBetaServerEventResponseTextDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.output_text.delta`.', - ), - ] = 'response.output_text.delta' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The text delta.')] - - -class RealtimeBetaServerEventResponseTextDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field( - const=True, - description='The event type, must be `response.output_text.done`.', - ), - ] = 'response.output_text.done' - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - text: Annotated[str, Field(description='The final text content.')] - - -class RealtimeCallReferRequest(BaseModel): - class Config: - extra = Extra.forbid - - target_uri: Annotated[ - str, - Field( - description='URI that should appear in the SIP Refer-To header. Supports values like\n`tel:+14155550123` or `sip:agent@example.com`.', - example='tel:+14155550123', - ), - ] - - -class RealtimeCallRejectRequest(BaseModel): - class Config: - extra = Extra.forbid - - status_code: Annotated[ - Optional[int], - Field( - description='SIP response code to send back to the caller. Defaults to `603` (Decline)\nwhen omitted.', - example=486, - ), - ] = None - - -class RealtimeClientEventConversationItemDelete(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['conversation.item.delete'], - Field( - const=True, - description='The event type, must be `conversation.item.delete`.', - ), - ] - item_id: Annotated[str, Field(description='The ID of the item to delete.')] - - -class RealtimeClientEventConversationItemRetrieve(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['conversation.item.retrieve'], - Field( - const=True, - description='The event type, must be `conversation.item.retrieve`.', - ), - ] - item_id: Annotated[str, Field(description='The ID of the item to retrieve.')] - - -class RealtimeClientEventConversationItemTruncate(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['conversation.item.truncate'], - Field( - const=True, - description='The event type, must be `conversation.item.truncate`.', - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the assistant message item to truncate. Only assistant message \nitems can be truncated.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part to truncate. Set this to `0`.' - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Inclusive duration up to which audio is truncated, in milliseconds. If \nthe audio_end_ms is greater than the actual audio duration, the server \nwill respond with an error.\n' - ), - ] - - -class RealtimeClientEventInputAudioBufferAppend(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['input_audio_buffer.append'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.append`.', - ), - ] - audio: Annotated[ - str, - Field( - description='Base64-encoded audio bytes. This must be in the format specified by the \n`input_audio_format` field in the session configuration.\n' - ), - ] - - -class RealtimeClientEventInputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['input_audio_buffer.clear'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.clear`.', - ), - ] - - -class RealtimeClientEventInputAudioBufferCommit(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['input_audio_buffer.commit'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.commit`.', - ), - ] - - -class RealtimeClientEventOutputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='The unique ID of the client event used for error handling.'), - ] = None - type: Annotated[ - Literal['output_audio_buffer.clear'], - Field( - const=True, - description='The event type, must be `output_audio_buffer.clear`.', - ), - ] - - -class RealtimeClientEventResponseCancel(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['response.cancel'], - Field(const=True, description='The event type, must be `response.cancel`.'), - ] - response_id: Annotated[ - Optional[str], - Field( - description='A specific response ID to cancel - if not provided, will cancel an \nin-progress response in the default conversation.\n' - ), - ] = None - - -class RealtimeConversationItemFunctionCall(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemFunctionCall'], - Field(description='The type of the item. Always `function_call`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - call_id: Annotated[ - Optional[str], Field(description='The ID of the function call.') - ] = None - name: Annotated[str, Field(description='The name of the function being called.')] - arguments: Annotated[ - str, - Field( - description='The arguments of the function call. This is a JSON-encoded string representing the arguments passed to the function, for example `{"arg1": "value1", "arg2": 42}`.' - ), - ] - - -class RealtimeConversationItemFunctionCallOutput(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemFunctionCallOutput'], - Field(description='The type of the item. Always `function_call_output`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - call_id: Annotated[ - str, Field(description='The ID of the function call this output is for.') - ] - output: Annotated[ - str, - Field( - description='The output of the function call, this is free text and can contain any information or simply be empty.' - ), - ] - - -class ContentItem1(BaseModel): - type: Annotated[ - Optional[Literal['output_text', 'output_audio']], - Field( - description='The content type, `output_text` or `output_audio` depending on the session `output_modalities` configuration.' - ), - ] = None - text: Annotated[Optional[str], Field(description='The text content.')] = None - audio: Annotated[ - Optional[str], - Field( - description='Base64-encoded audio bytes, these will be parsed as the format specified in the session output audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified.' - ), - ] = None - transcript: Annotated[ - Optional[str], - Field( - description='The transcript of the audio content, this will always be present if the output type is `audio`.' - ), - ] = None - - -class RealtimeConversationItemMessageAssistant(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemMessageAssistant'], - Field(description='The type of the item. Always `message`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - role: Annotated[ - Literal['assistant'], - Field(description='The role of the message sender. Always `assistant`.'), - ] - content: Annotated[ - List[ContentItem1], Field(description='The content of the message.') - ] - - -class ContentItem2(BaseModel): - type: Annotated[ - Optional[Literal['input_text']], - Field(description='The content type. Always `input_text` for system messages.'), - ] = None - text: Annotated[Optional[str], Field(description='The text content.')] = None - - -class RealtimeConversationItemMessageSystem(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemMessageSystem'], - Field(description='The type of the item. Always `message`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - role: Annotated[ - Literal['system'], - Field(description='The role of the message sender. Always `system`.'), - ] - content: Annotated[ - List[ContentItem2], Field(description='The content of the message.') - ] - - -class ContentItem3(BaseModel): - type: Annotated[ - Optional[Literal['input_text', 'input_audio', 'input_image']], - Field( - description='The content type (`input_text`, `input_audio`, or `input_image`).' - ), - ] = None - text: Annotated[ - Optional[str], Field(description='The text content (for `input_text`).') - ] = None - audio: Annotated[ - Optional[str], - Field( - description='Base64-encoded audio bytes (for `input_audio`), these will be parsed as the format specified in the session input audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified.' - ), - ] = None - image_url: Annotated[ - Optional[str], - Field( - description='Base64-encoded image bytes (for `input_image`) as a data URI. For example `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...`. Supported formats are PNG and JPEG.' - ), - ] = None - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='The detail level of the image (for `input_image`). `auto` will default to `high`.' - ), - ] = 'auto' - transcript: Annotated[ - Optional[str], - Field( - description='Transcript of the audio (for `input_audio`). This is not sent to the model, but will be attached to the message item for reference.' - ), - ] = None - - -class RealtimeConversationItemMessageUser(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemMessageUser'], - Field(description='The type of the item. Always `message`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - role: Annotated[ - Literal['user'], - Field(description='The role of the message sender. Always `user`.'), - ] - content: Annotated[ - List[ContentItem3], Field(description='The content of the message.') - ] - - -class ContentItem4(BaseModel): - type: Annotated[ - Optional[Literal['input_text', 'input_audio', 'item_reference', 'text']], - Field( - description='The content type (`input_text`, `input_audio`, `item_reference`, `text`).\n' - ), - ] = None - text: Annotated[ - Optional[str], - Field( - description='The text content, used for `input_text` and `text` content types.\n' - ), - ] = None - id: Annotated[ - Optional[str], - Field( - description='ID of a previous conversation item to reference (for `item_reference`\ncontent types in `response.create` events). These can reference both\nclient and server created items.\n' - ), - ] = None - audio: Annotated[ - Optional[str], - Field( - description='Base64-encoded audio bytes, used for `input_audio` content type.\n' - ), - ] = None - transcript: Annotated[ - Optional[str], - Field( - description='The transcript of the audio, used for `input_audio` content type.\n' - ), - ] = None - - -class RealtimeConversationItemWithReference(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='For an item of type (`message` | `function_call` | `function_call_output`)\nthis field allows the client to assign the unique ID of the item. It is\nnot required because the server will generate one if not provided.\n\nFor an item of type `item_reference`, this field is required and is a\nreference to any item that has previously existed in the conversation.\n' - ), - ] = None - type: Annotated[ - Optional[ - Literal[ - 'message', 'function_call', 'function_call_output', 'item_reference' - ] - ], - Field( - description='The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`).\n' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`.\n' - ), - ] = None - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field( - description='The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect \non the conversation, but are accepted for consistency with the \n`conversation.item.created` event.\n' - ), - ] = None - role: Annotated[ - Optional[Literal['user', 'assistant', 'system']], - Field( - description='The role of the message sender (`user`, `assistant`, `system`), only \napplicable for `message` items.\n' - ), - ] = None - content: Annotated[ - Optional[List[ContentItem4]], - Field( - description='The content of the message, applicable for `message` items. \n- Message items of role `system` support only `input_text` content\n- Message items of role `user` support `input_text` and `input_audio` \n content\n- Message items of role `assistant` support `text` content.\n' - ), - ] = None - call_id: Annotated[ - Optional[str], - Field( - description='The ID of the function call (for `function_call` and \n`function_call_output` items). If passed on a `function_call_output` \nitem, the server will check that a `function_call` item with the same \nID exists in the conversation history.\n' - ), - ] = None - name: Annotated[ - Optional[str], - Field( - description='The name of the function being called (for `function_call` items).\n' - ), - ] = None - arguments: Annotated[ - Optional[str], - Field( - description='The arguments of the function call (for `function_call` items).\n' - ), - ] = None - output: Annotated[ - Optional[str], - Field( - description='The output of the function call (for `function_call_output` items).\n' - ), - ] = None - - -class ExpiresAfter2(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='The anchor point for the client secret expiration, meaning that `seconds` will be added to the `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` is currently supported.\n' - ), - ] = 'created_at' - seconds: Annotated[ - int, - Field( - description='The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200` (2 hours). This default to 600 seconds (10 minutes) if not specified.\n', - ge=10, - le=7200, - ), - ] = 600 - - -class RealtimeFunctionTool(BaseModel): - type: Annotated[ - Literal['RealtimeFunctionTool'], - Field(description='The type of the tool, i.e. `function`.'), - ] - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - description: Annotated[ - Optional[str], - Field( - description='The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n' - ), - ] = None - parameters: Annotated[ - Optional[Dict[str, Any]], - Field(description='Parameters of the function in JSON Schema.'), - ] = None - - -class RealtimeMCPApprovalRequest(BaseModel): - type: Annotated[ - Literal['RealtimeMCPApprovalRequest'], - Field(description='The type of the item. Always `mcp_approval_request`.'), - ] - id: Annotated[str, Field(description='The unique ID of the approval request.')] - server_label: Annotated[ - str, Field(description='The label of the MCP server making the request.') - ] - name: Annotated[str, Field(description='The name of the tool to run.')] - arguments: Annotated[ - str, Field(description='A JSON string of arguments for the tool.') - ] - - -class RealtimeMCPApprovalResponse(BaseModel): - type: Annotated[ - Literal['RealtimeMCPApprovalResponse'], - Field(description='The type of the item. Always `mcp_approval_response`.'), - ] - id: Annotated[str, Field(description='The unique ID of the approval response.')] - approval_request_id: Annotated[ - str, Field(description='The ID of the approval request being answered.') - ] - approve: Annotated[bool, Field(description='Whether the request was approved.')] - reason: Optional[str] = None - - -class RealtimeMCPHTTPError(BaseModel): - type: Literal['http_error'] - code: int - message: str - - -class RealtimeMCPListTools(BaseModel): - type: Annotated[ - Literal['RealtimeMCPListTools'], - Field(description='The type of the item. Always `mcp_list_tools`.'), - ] - id: Annotated[Optional[str], Field(description='The unique ID of the list.')] = None - server_label: Annotated[str, Field(description='The label of the MCP server.')] - tools: Annotated[ - List[MCPListToolsTool], Field(description='The tools available on the server.') - ] - - -class RealtimeMCPProtocolError(BaseModel): - type: Literal['protocol_error'] - code: int - message: str - - -class RealtimeMCPToolExecutionError(BaseModel): - type: Literal['tool_execution_error'] - message: str - - -class Error6(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - - -class StatusDetails1(BaseModel): - type: Annotated[ - Optional[Literal['completed', 'cancelled', 'incomplete', 'failed']], - Field( - description='The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n' - ), - ] = None - reason: Annotated[ - Optional[ - Literal[ - 'turn_detected', - 'client_cancelled', - 'max_output_tokens', - 'content_filter', - ] - ], - Field( - description='The reason the Response did not complete. For a `cancelled` Response, one of `turn_detected` (the server VAD detected a new start of speech) or `client_cancelled` (the client sent a cancel event). For an `incomplete` Response, one of `max_output_tokens` or `content_filter` (the server-side safety filter activated and cut off the response).\n' - ), - ] = None - error: Annotated[ - Optional[Error6], - Field( - description='A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n' - ), - ] = None - - -class InputTokenDetails1(BaseModel): - cached_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached tokens used as input for the Response.' - ), - ] = None - text_tokens: Annotated[ - Optional[int], - Field(description='The number of text tokens used as input for the Response.'), - ] = None - image_tokens: Annotated[ - Optional[int], - Field(description='The number of image tokens used as input for the Response.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='The number of audio tokens used as input for the Response.'), - ] = None - cached_tokens_details: Annotated[ - Optional[CachedTokensDetails], - Field( - description='Details about the cached tokens used as input for the Response.' - ), - ] = None - - -class Usage4(BaseModel): - total_tokens: Annotated[ - Optional[int], - Field( - description='The total number of tokens in the Response including input and output \ntext and audio tokens.\n' - ), - ] = None - input_tokens: Annotated[ - Optional[int], - Field( - description='The number of input tokens used in the Response, including text and \naudio tokens.\n' - ), - ] = None - output_tokens: Annotated[ - Optional[int], - Field( - description='The number of output tokens sent in the Response, including text and \naudio tokens.\n' - ), - ] = None - input_token_details: Annotated[ - Optional[InputTokenDetails1], - Field( - description='Details about the input tokens used in the Response. Cached tokens are tokens from previous turns in the conversation that are included as context for the current response. Cached tokens here are counted as a subset of input tokens, meaning input tokens will include cached and uncached tokens.' - ), - ] = None - output_token_details: Annotated[ - Optional[OutputTokenDetails], - Field(description='Details about the output tokens used in the Response.'), - ] = None - - -class Conversation1(BaseModel): - id: Annotated[ - Optional[str], Field(description='The unique ID of the conversation.') - ] = None - object: Annotated[ - str, - Field( - const=True, description='The object type, must be `realtime.conversation`.' - ), - ] = 'realtime.conversation' - - -class RealtimeServerEventConversationCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.created'], - Field( - const=True, description='The event type, must be `conversation.created`.' - ), - ] - conversation: Annotated[ - Conversation1, Field(description='The conversation resource.') - ] - - -class RealtimeServerEventConversationItemDeleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.deleted'], - Field( - const=True, - description='The event type, must be `conversation.item.deleted`.', - ), - ] - item_id: Annotated[str, Field(description='The ID of the item that was deleted.')] - - -class RealtimeServerEventConversationItemInputAudioTranscriptionDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.delta'], - Field( - const=True, - description='The event type, must be `conversation.item.input_audio_transcription.delta`.', - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item containing the audio that is being transcribed.' - ), - ] - content_index: Annotated[ - Optional[int], - Field(description="The index of the content part in the item's content array."), - ] = None - delta: Annotated[Optional[str], Field(description='The text delta.')] = None - logprobs: Optional[List[LogProbProperties]] = None - - -class Error7(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - message: Annotated[ - Optional[str], Field(description='A human-readable error message.') - ] = None - param: Annotated[ - Optional[str], Field(description='Parameter related to the error, if any.') - ] = None - - -class RealtimeServerEventConversationItemInputAudioTranscriptionFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['RealtimeServerEventConversationItemInputAudioTranscriptionFailed'], - Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.failed`.\n' - ), - ] - item_id: Annotated[str, Field(description='The ID of the user message item.')] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - error: Annotated[Error7, Field(description='Details of the transcription error.')] - - -class RealtimeServerEventConversationItemInputAudioTranscriptionSegment(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.segment'], - Field( - const=True, - description='The event type, must be `conversation.item.input_audio_transcription.segment`.', - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the item containing the input audio content.') - ] - content_index: Annotated[ - int, - Field(description='The index of the input audio content part within the item.'), - ] - text: Annotated[str, Field(description='The text for this segment.')] - id: Annotated[str, Field(description='The segment identifier.')] - speaker: Annotated[ - str, Field(description='The detected speaker label for this segment.') - ] - start: Annotated[float, Field(description='Start time of the segment in seconds.')] - end: Annotated[float, Field(description='End time of the segment in seconds.')] - - -class RealtimeServerEventConversationItemTruncated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.truncated'], - Field( - const=True, - description='The event type, must be `conversation.item.truncated`.', - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the assistant message item that was truncated.'), - ] - content_index: Annotated[ - int, Field(description='The index of the content part that was truncated.') - ] - audio_end_ms: Annotated[ - int, - Field( - description='The duration up to which the audio was truncated, in milliseconds.\n' - ), - ] - - -class Error8(BaseModel): - type: Annotated[ - str, - Field( - description='The type of error (e.g., "invalid_request_error", "server_error").\n' - ), - ] - code: Optional[str] = None - message: Annotated[str, Field(description='A human-readable error message.')] - param: Optional[str] = None - event_id: Optional[str] = None - - -class RealtimeServerEventError(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['error'], - Field(const=True, description='The event type, must be `error`.'), - ] - error: Annotated[Error8, Field(description='Details of the error.')] - - -class RealtimeServerEventInputAudioBufferCleared(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.cleared'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.cleared`.', - ), - ] - - -class RealtimeServerEventInputAudioBufferCommitted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.committed'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.committed`.', - ), - ] - previous_item_id: Optional[str] = None - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeServerEventInputAudioBufferSpeechStarted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.speech_started'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.speech_started`.', - ), - ] - audio_start_ms: Annotated[ - int, - Field( - description='Milliseconds from the start of all audio written to the buffer during the \nsession when speech was first detected. This will correspond to the \nbeginning of audio sent to the model, and thus includes the \n`prefix_padding_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the user message item that will be created when speech stops.\n' - ), - ] - - -class RealtimeServerEventInputAudioBufferSpeechStopped(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.speech_stopped'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.speech_stopped`.', - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Milliseconds since the session started when speech stopped. This will \ncorrespond to the end of audio sent to the model, and thus includes the \n`min_silence_duration_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeServerEventInputAudioBufferTimeoutTriggered(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.timeout_triggered'], - Field( - const=True, - description='The event type, must be `input_audio_buffer.timeout_triggered`.', - ), - ] - audio_start_ms: Annotated[ - int, - Field( - description='Millisecond offset of audio written to the input audio buffer that was after the playback time of the last model response.' - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Millisecond offset of audio written to the input audio buffer at the time the timeout was triggered.' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the item associated with this segment.') - ] - - -class RealtimeServerEventMCPListToolsCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.completed'], - Field( - const=True, - description='The event type, must be `mcp_list_tools.completed`.', - ), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeServerEventMCPListToolsFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.failed'], - Field( - const=True, description='The event type, must be `mcp_list_tools.failed`.' - ), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeServerEventMCPListToolsInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.in_progress'], - Field( - const=True, - description='The event type, must be `mcp_list_tools.in_progress`.', - ), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeServerEventOutputAudioBufferCleared(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['output_audio_buffer.cleared'], - Field( - const=True, - description='The event type, must be `output_audio_buffer.cleared`.', - ), - ] - response_id: Annotated[ - str, Field(description='The unique ID of the response that produced the audio.') - ] - - -class RealtimeServerEventOutputAudioBufferStarted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['output_audio_buffer.started'], - Field( - const=True, - description='The event type, must be `output_audio_buffer.started`.', - ), - ] - response_id: Annotated[ - str, Field(description='The unique ID of the response that produced the audio.') - ] - - -class RealtimeServerEventOutputAudioBufferStopped(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['output_audio_buffer.stopped'], - Field( - const=True, - description='The event type, must be `output_audio_buffer.stopped`.', - ), - ] - response_id: Annotated[ - str, Field(description='The unique ID of the response that produced the audio.') - ] - - -class RealtimeServerEventRateLimitsUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['rate_limits.updated'], - Field(const=True, description='The event type, must be `rate_limits.updated`.'), - ] - rate_limits: Annotated[ - List[RateLimit], Field(description='List of rate limit information.') - ] - - -class RealtimeServerEventResponseAudioDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio.delta'], - Field( - const=True, - description='The event type, must be `response.output_audio.delta`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='Base64-encoded audio data delta.')] - - -class RealtimeServerEventResponseAudioDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio.done'], - Field( - const=True, - description='The event type, must be `response.output_audio.done`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - - -class RealtimeServerEventResponseAudioTranscriptDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio_transcript.delta'], - Field( - const=True, - description='The event type, must be `response.output_audio_transcript.delta`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The transcript delta.')] - - -class RealtimeServerEventResponseAudioTranscriptDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio_transcript.done'], - Field( - const=True, - description='The event type, must be `response.output_audio_transcript.done`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - transcript: Annotated[str, Field(description='The final transcript of the audio.')] - - -class RealtimeServerEventResponseContentPartAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.content_part.added'], - Field( - const=True, - description='The event type, must be `response.content_part.added`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[ - str, - Field(description='The ID of the item to which the content part was added.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that was added.')] - - -class RealtimeServerEventResponseContentPartDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.content_part.done'], - Field( - const=True, - description='The event type, must be `response.content_part.done`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that is done.')] - - -class RealtimeServerEventResponseFunctionCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.function_call_arguments.delta'], - Field( - const=True, - description='The event type, must be `response.function_call_arguments.delta`.\n', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - delta: Annotated[str, Field(description='The arguments delta as a JSON string.')] - - -class RealtimeServerEventResponseFunctionCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.function_call_arguments.done'], - Field( - const=True, - description='The event type, must be `response.function_call_arguments.done`.\n', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - arguments: Annotated[ - str, Field(description='The final arguments as a JSON string.') - ] - - -class RealtimeServerEventResponseMCPCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call_arguments.delta'], - Field( - const=True, - description='The event type, must be `response.mcp_call_arguments.delta`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - delta: Annotated[str, Field(description='The JSON-encoded arguments delta.')] - obfuscation: Optional[str] = None - - -class RealtimeServerEventResponseMCPCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call_arguments.done'], - Field( - const=True, - description='The event type, must be `response.mcp_call_arguments.done`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - arguments: Annotated[ - str, Field(description='The final JSON-encoded arguments string.') - ] - - -class RealtimeServerEventResponseMCPCallCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.completed'], - Field( - const=True, - description='The event type, must be `response.mcp_call.completed`.', - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeServerEventResponseMCPCallFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.failed'], - Field( - const=True, - description='The event type, must be `response.mcp_call.failed`.', - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeServerEventResponseMCPCallInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.in_progress'], - Field( - const=True, - description='The event type, must be `response.mcp_call.in_progress`.', - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeServerEventResponseTextDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_text.delta'], - Field( - const=True, - description='The event type, must be `response.output_text.delta`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The text delta.')] - - -class RealtimeServerEventResponseTextDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_text.done'], - Field( - const=True, - description='The event type, must be `response.output_text.done`.', - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - text: Annotated[str, Field(description='The final text content.')] - - -class InputAudioNoiseReduction(BaseModel): - type: Optional[NoiseReductionType] = None - - -class Tracing(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n' - ), - ] = None - - -class ClientSecret(BaseModel): - value: Annotated[ - str, - Field( - description='Ephemeral key usable in client environments to authenticate connections\nto the Realtime API. Use this in client-side environments rather than\na standard API token, which should only be used server-side.\n' - ), - ] - expires_at: Annotated[ - int, - Field( - description='Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n' - ), - ] - - -class InputAudioTranscription(BaseModel): - model: Annotated[ - Optional[str], Field(description='The model to use for transcription.\n') - ] = None - - -class TurnDetection(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class Tool2(BaseModel): - type: Annotated[ - Optional[Literal['function']], - Field(description='The type of the tool, i.e. `function`.'), - ] = None - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - description: Annotated[ - Optional[str], - Field( - description='The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n' - ), - ] = None - parameters: Annotated[ - Optional[Dict[str, Any]], - Field(description='Parameters of the function in JSON Schema.'), - ] = None - - -class NoiseReduction(BaseModel): - type: Optional[NoiseReductionType] = None - - -class Tracing2(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n' - ), - ] = None - - -class TurnDetection1(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Optional[float] = None - prefix_padding_ms: Optional[int] = None - silence_duration_ms: Optional[int] = None - - -class Input6(BaseModel): - format: Optional[RealtimeAudioFormats] = None - transcription: Annotated[ - Optional[AudioTranscription], - Field(description='Configuration for input audio transcription.\n'), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], - Field(description='Configuration for input audio noise reduction.\n'), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection1], - Field(description='Configuration for turn detection.\n'), - ] = None - - -class Tracing3(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n' - ), - ] = None - - -class TurnDetection2(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class ClientSecret1(BaseModel): - value: Annotated[ - str, - Field( - description='Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side.\n' - ), - ] - expires_at: Annotated[ - int, - Field( - description='Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n' - ), - ] - - -class Tracing4(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n' - ), - ] = None - - -class TurnDetection3(BaseModel): - type: Annotated[ - Optional[Literal['server_vad']], - Field( - description='Type of turn detection. Only `server_vad` is currently supported for transcription sessions.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class RealtimeTranscriptionSessionCreateRequest(BaseModel): - turn_detection: Annotated[ - Optional[TurnDetection3], - Field( - description='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.\n' - ), - ] = None - input_audio_noise_reduction: Annotated[ - Optional[InputAudioNoiseReduction], - Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' - ), - ] = None - input_audio_format: Annotated[ - Literal['pcm16', 'g711_ulaw', 'g711_alaw'], - Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n' - ), - ] = 'pcm16' - input_audio_transcription: Annotated[ - Optional[AudioTranscription], - Field( - description='Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n' - ), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='The set of items to include in the transcription. Current available items are:\n`item.input_audio_transcription.logprobs`\n' - ), - ] = None - - -class ClientSecret2(BaseModel): - value: Annotated[ - str, - Field( - description='Ephemeral key usable in client environments to authenticate connections\nto the Realtime API. Use this in client-side environments rather than\na standard API token, which should only be used server-side.\n' - ), - ] - expires_at: Annotated[ - int, - Field( - description='Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n' - ), - ] - - -class TurnDetection4(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class RealtimeTranscriptionSessionCreateResponse(BaseModel): - client_secret: Annotated[ - ClientSecret2, - Field( - description='Ephemeral key returned by the API. Only present when the session is\ncreated on the server via REST API.\n' - ), - ] - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' - ), - ] = None - input_audio_format: Annotated[ - Optional[str], - Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' - ), - ] = None - input_audio_transcription: Annotated[ - Optional[AudioTranscription], - Field(description='Configuration of the transcription model.\n'), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection4], - Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' - ), - ] = None - - -class Input9(BaseModel): - format: Optional[RealtimeAudioFormats] = None - transcription: Annotated[ - Optional[AudioTranscription], - Field(description='Configuration of the transcription model.\n'), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], - Field(description='Configuration for input audio noise reduction.\n'), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection4], - Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' - ), - ] = None - - -class Audio9(BaseModel): - input: Optional[Input9] = None - - -class RealtimeTranscriptionSessionCreateResponseGA(BaseModel): - type: Annotated[ - Literal['RealtimeTranscriptionSessionCreateResponseGA'], - Field( - description='The type of session. Always `transcription` for transcription sessions.\n' - ), - ] - id: Annotated[ - str, - Field( - description='Unique identifier for the session that looks like `sess_1234567890abcdef`.\n' - ), - ] - object: Annotated[ - str, - Field(description='The object type. Always `realtime.transcription_session`.'), - ] - expires_at: Annotated[ - Optional[int], - Field( - description='Expiration timestamp for the session, in seconds since epoch.' - ), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' - ), - ] = None - audio: Annotated[ - Optional[Audio9], - Field(description='Configuration for input audio for the session.\n'), - ] = None - - -class TokenLimits(BaseModel): - post_instructions: Annotated[ - Optional[int], - Field( - description="Maximum tokens allowed in the conversation after instructions (which including tool definitions). For example, setting this to 5,000 would mean that truncation would occur when the conversation exceeds 5,000 tokens after instructions. This cannot be higher than the model's context window size minus the maximum output tokens.", - ge=0, - ), - ] = None - - -class RealtimeTruncation1(BaseModel): - type: Annotated[ - Literal['retention_ratio'], Field(description='Use retention ratio truncation.') - ] - retention_ratio: Annotated[ - float, - Field( - description='Fraction of post-instruction conversation tokens to retain (`0.0` - `1.0`) when the conversation exceeds the input token limit. Setting this to `0.8` means that messages will be dropped until 80% of the maximum allowed tokens are used. This helps reduce the frequency of truncations and improve cache rates.\n', - ge=0.0, - le=1.0, - ), - ] - token_limits: Annotated[ - Optional[TokenLimits], - Field( - description="Optional custom token limits for this truncation strategy. If not provided, the model's default token limits will be used." - ), - ] = None - - -class RealtimeTruncation(BaseModel): - __root__: Annotated[ - Union[Literal['auto', 'disabled'], RealtimeTruncation1], - Field( - description="When the number of tokens in a conversation exceeds the model's input token limit, the conversation be truncated, meaning messages (starting from the oldest) will not be included in the model's context. A 32k context model with 4,096 max output tokens can only include 28,224 tokens in the context before truncation occurs.\nClients can configure truncation behavior to truncate with a lower max token limit, which is an effective way to control token usage and cost.\nTruncation will reduce the number of cached tokens on the next turn (busting the cache), since messages are dropped from the beginning of the context. However, clients can also configure truncation to retain messages up to a fraction of the maximum context size, which will reduce the need for future truncations and thus improve the cache rate.\nTruncation can be disabled entirely, which means the server will never truncate but would instead return an error if the conversation exceeds the model's input token limit.\n", - title='Realtime Truncation Controls', - ), - ] - - -class IdleTimeoutMs(BaseModel): - __root__: Annotated[ - int, - Field( - description="Optional timeout after which a model response will be triggered automatically. This is\nuseful for situations in which a long pause from the user is unexpected, such as a phone\ncall. The model will effectively prompt the user to continue the conversation based\non the current context.\n\nThe timeout value will be applied after the last model response's audio has finished playing,\ni.e. it's set to the `response.done` time plus audio playback duration.\n\nAn `input_audio_buffer.timeout_triggered` event (plus events\nassociated with the Response) will be emitted when the timeout is reached.\nIdle timeout is currently only supported for `server_vad` mode.\n", - ge=5000, - le=30000, - ), - ] - - -class RealtimeTurnDetection1(BaseModel): - type: Annotated[ - str, - Field( - const=True, - description='Type of turn detection, `server_vad` to turn on simple Server VAD.\n', - ), - ] = 'server_vad' - threshold: Annotated[ - Optional[float], - Field( - description='Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - create_response: Annotated[ - bool, - Field( - description='Whether or not to automatically generate a response when a VAD stop event occurs.\n' - ), - ] = True - interrupt_response: Annotated[ - bool, - Field( - description='Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n' - ), - ] = True - idle_timeout_ms: Optional[IdleTimeoutMs] = None - - -class RealtimeTurnDetection2(BaseModel): - type: Annotated[ - str, - Field( - const=True, - description='Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n', - ), - ] = 'semantic_vad' - eagerness: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field( - description='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`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n' - ), - ] = 'auto' - create_response: Annotated[ - bool, - Field( - description='Whether or not to automatically generate a response when a VAD stop event occurs.\n' - ), - ] = True - interrupt_response: Annotated[ - bool, - Field( - description='Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n' - ), - ] = True - - -class RealtimeTurnDetection(BaseModel): - __root__: Optional[Union[RealtimeTurnDetection1, RealtimeTurnDetection2]] - - -class ReasoningEffort(BaseModel): - __root__: Optional[Literal['none', 'minimal', 'low', 'medium', 'high']] - - -class IncompleteDetails1(BaseModel): - reason: Annotated[ - Optional[Literal['max_output_tokens', 'content_filter']], - Field(description='The reason why the response is incomplete.'), - ] = None - - -class ResponseAudioDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioDeltaEvent'], - Field(description='The type of the event. Always `response.audio.delta`.\n'), - ] - sequence_number: Annotated[ - int, - Field(description='A sequence number for this chunk of the stream response.\n'), - ] - delta: Annotated[ - str, Field(description='A chunk of Base64 encoded response audio bytes.\n') - ] - - -class ResponseAudioDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioDoneEvent'], - Field(description='The type of the event. Always `response.audio.done`.\n'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of the delta.\n') - ] - - -class ResponseAudioTranscriptDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioTranscriptDeltaEvent'], - Field( - description='The type of the event. Always `response.audio.transcript.delta`.\n' - ), - ] - delta: Annotated[ - str, Field(description='The partial transcript of the audio response.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseAudioTranscriptDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioTranscriptDoneEvent'], - Field( - description='The type of the event. Always `response.audio.transcript.done`.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseCodeInterpreterCallCodeDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallCodeDeltaEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call_code.delta`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code is being streamed.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - delta: Annotated[ - str, - Field( - description='The partial code snippet being streamed by the code interpreter.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallCodeDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallCodeDoneEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call_code.done`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code is finalized.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - code: Annotated[ - str, Field(description='The final code snippet output by the code interpreter.') - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallCompletedEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call.completed`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code interpreter call is completed.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallInProgressEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call.in_progress`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code interpreter call is in progress.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallInterpretingEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallInterpretingEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call.interpreting`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code interpreter is interpreting code.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCustomToolCallInputDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseCustomToolCallInputDeltaEvent'], - Field(description='The event type identifier.'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - output_index: Annotated[ - int, Field(description='The index of the output this delta applies to.') - ] - item_id: Annotated[ - str, - Field( - description='Unique identifier for the API item associated with this event.' - ), - ] - delta: Annotated[ - str, - Field( - description='The incremental input data (delta) for the custom tool call.' - ), - ] - - -class ResponseCustomToolCallInputDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseCustomToolCallInputDoneEvent'], - Field(description='The event type identifier.'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - output_index: Annotated[ - int, Field(description='The index of the output this event applies to.') - ] - item_id: Annotated[ - str, - Field( - description='Unique identifier for the API item associated with this event.' - ), - ] - input: Annotated[ - str, Field(description='The complete input data for the custom tool call.') - ] - - -class ResponseErrorCode(BaseModel): - __root__: Annotated[ - Literal[ - 'server_error', - 'rate_limit_exceeded', - 'invalid_prompt', - 'vector_store_timeout', - 'invalid_image', - 'invalid_image_format', - 'invalid_base64_image', - 'invalid_image_url', - 'image_too_large', - 'image_too_small', - 'image_parse_error', - 'image_content_policy_violation', - 'invalid_image_mode', - 'image_file_too_large', - 'unsupported_image_media_type', - 'empty_image_file', - 'failed_to_download_image', - 'image_file_not_found', - ], - Field(description='The error code for the response.\n'), - ] - - -class ResponseErrorEvent(BaseModel): - type: Annotated[ - Literal['ResponseErrorEvent'], - Field(description='The type of the event. Always `error`.\n'), - ] - code: Optional[str] - message: Annotated[str, Field(description='The error message.\n')] - param: Optional[str] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFileSearchCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseFileSearchCallCompletedEvent'], - Field( - description='The type of the event. Always `response.file_search_call.completed`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the file search call is initiated.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the file search call is initiated.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFileSearchCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseFileSearchCallInProgressEvent'], - Field( - description='The type of the event. Always `response.file_search_call.in_progress`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the file search call is initiated.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the file search call is initiated.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFileSearchCallSearchingEvent(BaseModel): - type: Annotated[ - Literal['ResponseFileSearchCallSearchingEvent'], - Field( - description='The type of the event. Always `response.file_search_call.searching`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the file search call is searching.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the file search call is initiated.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFormatJsonObject(BaseModel): - type: Annotated[ - Literal['ResponseFormatJsonObject'], - Field( - description='The type of response format being defined. Always `json_object`.' - ), - ] - - -class ResponseFormatJsonSchemaSchema(BaseModel): - pass - - class Config: - extra = Extra.allow - - -class ResponseFormatText(BaseModel): - type: Annotated[ - Literal['ResponseFormatText'], - Field(description='The type of response format being defined. Always `text`.'), - ] - - -class ResponseFormatTextGrammar(BaseModel): - type: Annotated[ - Literal['grammar'], - Field( - description='The type of response format being defined. Always `grammar`.' - ), - ] - grammar: Annotated[ - str, Field(description='The custom grammar for the model to follow.') - ] - - -class ResponseFormatTextPython(BaseModel): - type: Annotated[ - Literal['python'], - Field( - description='The type of response format being defined. Always `python`.' - ), - ] - - -class ResponseFunctionCallArgumentsDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseFunctionCallArgumentsDeltaEvent'], - Field( - description='The type of the event. Always `response.function_call_arguments.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the function-call arguments delta is added to.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the function-call arguments delta is added to.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - delta: Annotated[ - str, Field(description='The function-call arguments delta that is added.\n') - ] - - -class ResponseFunctionCallArgumentsDoneEvent(BaseModel): - type: Literal['ResponseFunctionCallArgumentsDoneEvent'] - item_id: Annotated[str, Field(description='The ID of the item.')] - name: Annotated[str, Field(description='The name of the function that was called.')] - output_index: Annotated[int, Field(description='The index of the output item.')] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - arguments: Annotated[str, Field(description='The function-call arguments.')] - - -class ResponseImageGenCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallCompletedEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.completed'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - - -class ResponseImageGenCallGeneratingEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallGeneratingEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.generating'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the image generation item being processed.' - ), - ] - - -class ResponseImageGenCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallInProgressEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.in_progress'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the image generation item being processed.' - ), - ] - - -class ResponseImageGenCallPartialImageEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallPartialImageEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.partial_image'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the image generation item being processed.' - ), - ] - partial_image_index: Annotated[ - int, - Field( - description='0-based index for the partial image (backend is 1-based, but this is 0-based for the user).' - ), - ] - partial_image_b64: Annotated[ - str, - Field( - description='Base64-encoded partial image data, suitable for rendering as an image.' - ), - ] - - -class TopLogprob1(BaseModel): - token: Annotated[Optional[str], Field(description='A possible text token.')] = None - logprob: Annotated[ - Optional[float], Field(description='The log probability of this token.') - ] = None - - -class ResponseLogProb(BaseModel): - token: Annotated[str, Field(description='A possible text token.')] - logprob: Annotated[float, Field(description='The log probability of this token.\n')] - top_logprobs: Annotated[ - Optional[List[TopLogprob1]], - Field(description='The log probability of the top 20 most likely tokens.\n'), - ] = None - - -class ResponseMCPCallArgumentsDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallArgumentsDeltaEvent'], - Field( - description="The type of the event. Always 'response.mcp_call_arguments.delta'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the MCP tool call item being processed.' - ), - ] - delta: Annotated[ - str, - Field( - description='A JSON string containing the partial update to the arguments for the MCP tool call.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallArgumentsDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallArgumentsDoneEvent'], - Field( - description="The type of the event. Always 'response.mcp_call_arguments.done'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the MCP tool call item being processed.' - ), - ] - arguments: Annotated[ - str, - Field( - description='A JSON string containing the finalized arguments for the MCP tool call.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallCompletedEvent'], - Field( - description="The type of the event. Always 'response.mcp_call.completed'." - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the MCP tool call item that completed.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item that completed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallFailedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallFailedEvent'], - Field(description="The type of the event. Always 'response.mcp_call.failed'."), - ] - item_id: Annotated[ - str, Field(description='The ID of the MCP tool call item that failed.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item that failed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallInProgressEvent'], - Field( - description="The type of the event. Always 'response.mcp_call.in_progress'." - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the MCP tool call item being processed.' - ), - ] - - -class ResponseMCPListToolsCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPListToolsCompletedEvent'], - Field( - description="The type of the event. Always 'response.mcp_list_tools.completed'." - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the MCP tool call item that produced this output.' - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item that was processed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPListToolsFailedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPListToolsFailedEvent'], - Field( - description="The type of the event. Always 'response.mcp_list_tools.failed'." - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the MCP tool call item that failed.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item that failed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPListToolsInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPListToolsInProgressEvent'], - Field( - description="The type of the event. Always 'response.mcp_list_tools.in_progress'." - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the MCP tool call item that is being processed.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item that is being processed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseModalities(BaseModel): - __root__: Optional[List[Literal['text', 'audio']]] - - -class ResponseOutputTextAnnotationAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseOutputTextAnnotationAddedEvent'], - Field( - description="The type of the event. Always 'response.output_text.annotation.added'." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the item to which the annotation is being added.' - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - content_index: Annotated[ - int, Field(description='The index of the content part within the output item.') - ] - annotation_index: Annotated[ - int, Field(description='The index of the annotation within the content part.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - annotation: Annotated[ - Dict[str, Any], - Field( - description='The annotation object being added. (See annotation schema for details.)' - ), - ] - - -class Part4(BaseModel): - type: Annotated[ - Literal['summary_text'], - Field(description='The type of the summary part. Always `summary_text`.'), - ] - text: Annotated[str, Field(description='The text of the summary part.')] - - -class ResponseReasoningSummaryPartAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryPartAddedEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_part.added`.\n' - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the item this summary part is associated with.\n'), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary part is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - part: Annotated[Part4, Field(description='The summary part that was added.\n')] - - -class ResponseReasoningSummaryPartDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryPartDoneEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_part.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the item this summary part is associated with.\n'), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary part is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - part: Annotated[Part4, Field(description='The completed summary part.\n')] - - -class ResponseReasoningSummaryTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryTextDeltaEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_text.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item this summary text delta is associated with.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary text delta is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - delta: Annotated[ - str, Field(description='The text delta that was added to the summary.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseReasoningSummaryTextDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryTextDoneEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_text.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the item this summary text is associated with.\n'), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary text is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - text: Annotated[ - str, Field(description='The full text of the completed reasoning summary.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseReasoningTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningTextDeltaEvent'], - Field( - description='The type of the event. Always `response.reasoning_text.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item this reasoning text delta is associated with.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this reasoning text delta is associated with.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the reasoning content part this delta is associated with.\n' - ), - ] - delta: Annotated[ - str, - Field(description='The text delta that was added to the reasoning content.\n'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseReasoningTextDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningTextDoneEvent'], - Field( - description='The type of the event. Always `response.reasoning_text.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item this reasoning text is associated with.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this reasoning text is associated with.\n' - ), - ] - content_index: Annotated[ - int, Field(description='The index of the reasoning content part.\n') - ] - text: Annotated[ - str, Field(description='The full text of the completed reasoning content.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseRefusalDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseRefusalDeltaEvent'], - Field(description='The type of the event. Always `response.refusal.delta`.\n'), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the refusal text is added to.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the refusal text is added to.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the refusal text is added to.\n' - ), - ] - delta: Annotated[str, Field(description='The refusal text that is added.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseRefusalDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseRefusalDoneEvent'], - Field(description='The type of the event. Always `response.refusal.done`.\n'), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the refusal text is finalized.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the refusal text is finalized.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the refusal text is finalized.\n' - ), - ] - refusal: Annotated[str, Field(description='The refusal text that is finalized.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseStreamOptions1(BaseModel): - include_obfuscation: Annotated[ - Optional[bool], - Field( - description='When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n' - ), - ] = None - - -class ResponseStreamOptions(BaseModel): - __root__: Optional[ResponseStreamOptions1] - - -class ResponseTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseTextDeltaEvent'], - Field( - description='The type of the event. Always `response.output_text.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the text delta was added to.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the text delta was added to.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the text delta was added to.\n' - ), - ] - delta: Annotated[str, Field(description='The text delta that was added.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] - logprobs: Annotated[ - List[ResponseLogProb], - Field(description='The log probabilities of the tokens in the delta.\n'), - ] - - -class ResponseTextDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseTextDoneEvent'], - Field( - description='The type of the event. Always `response.output_text.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the text content is finalized.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the text content is finalized.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the text content is finalized.\n' - ), - ] - text: Annotated[str, Field(description='The text content that is finalized.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] - logprobs: Annotated[ - List[ResponseLogProb], - Field(description='The log probabilities of the tokens in the delta.\n'), - ] - - -class InputTokensDetails2(BaseModel): - cached_tokens: Annotated[ - int, - Field( - description='The number of tokens that were retrieved from the cache. \n[More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n' - ), - ] - - -class ResponseUsage(BaseModel): - input_tokens: Annotated[int, Field(description='The number of input tokens.')] - input_tokens_details: Annotated[ - InputTokensDetails2, - Field(description='A detailed breakdown of the input tokens.'), - ] - output_tokens: Annotated[int, Field(description='The number of output tokens.')] - output_tokens_details: Annotated[ - OutputTokensDetails, - Field(description='A detailed breakdown of the output tokens.'), - ] - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - - -class ResponseWebSearchCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseWebSearchCallCompletedEvent'], - Field( - description='The type of the event. Always `response.web_search_call.completed`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the web search call is associated with.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='Unique ID for the output item associated with the web search call.\n' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the web search call being processed.' - ), - ] - - -class ResponseWebSearchCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseWebSearchCallInProgressEvent'], - Field( - description='The type of the event. Always `response.web_search_call.in_progress`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the web search call is associated with.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='Unique ID for the output item associated with the web search call.\n' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the web search call being processed.' - ), - ] - - -class ResponseWebSearchCallSearchingEvent(BaseModel): - type: Annotated[ - Literal['ResponseWebSearchCallSearchingEvent'], - Field( - description='The type of the event. Always `response.web_search_call.searching`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the web search call is associated with.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='Unique ID for the output item associated with the web search call.\n' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the web search call being processed.' - ), - ] - - -class Role(BaseModel): - object: Annotated[Literal['role'], Field(description='Always `role`.')] - id: Annotated[str, Field(description='Identifier for the role.')] - name: Annotated[str, Field(description='Unique name for the role.')] - description: Annotated[ - Optional[str], Field(description='Optional description of the role.') - ] - permissions: Annotated[ - List[str], Field(description='Permissions granted by the role.') - ] - resource_type: Annotated[ - str, - Field( - description='Resource type the role is bound to (for example `api.organization` or `api.project`).' - ), - ] - predefined_role: Annotated[ - bool, Field(description='Whether the role is predefined and managed by OpenAI.') - ] - - -class RoleDeletedResource(BaseModel): - object: Annotated[ - Literal['role.deleted'], Field(description='Always `role.deleted`.') - ] - id: Annotated[str, Field(description='Identifier of the deleted role.')] - deleted: Annotated[bool, Field(description='Whether the role was deleted.')] - - -class RoleListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[AssignedRoleDetails], - Field(description='Role assignments returned in the current page.'), - ] - has_more: Annotated[ - bool, - Field( - description='Whether additional assignments are available when paginating.' - ), - ] - next: Annotated[ - Optional[str], - Field( - description='Cursor to fetch the next page of results, or `null` when there are no more assignments.' - ), - ] - - -class RunCompletionUsage1(BaseModel): - completion_tokens: Annotated[ - int, - Field( - description='Number of completion tokens used over the course of the run.' - ), - ] - prompt_tokens: Annotated[ - int, - Field(description='Number of prompt tokens used over the course of the run.'), - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (prompt + completion).') - ] - - -class RunCompletionUsage(BaseModel): - __root__: Optional[RunCompletionUsage1] - - -class Errors1(BaseModel): - formula_parse_error: bool - sample_parse_error: bool - truncated_observation_error: bool - unresponsive_reward_error: bool - invalid_variable_error: bool - other_error: bool - python_grader_server_error: bool - python_grader_server_error_type: Optional[str] - python_grader_runtime_error: bool - python_grader_runtime_error_details: Optional[str] - model_grader_server_error: bool - model_grader_refusal_error: bool - model_grader_parse_error: bool - model_grader_server_error_details: Optional[str] - - -class Metadata1(BaseModel): - name: str - type: str - errors: Errors1 - execution_time: float - scores: Dict[str, Any] - token_usage: Optional[int] - sampled_model_name: Optional[str] - - -class RunGraderResponse(BaseModel): - reward: float - metadata: Metadata1 - sub_rewards: Dict[str, Any] - model_grader_token_usage_per_model: Dict[str, Any] - - -class LastError(BaseModel): - code: Annotated[ - Literal['server_error', 'rate_limit_exceeded', 'invalid_prompt'], - Field( - description='One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.' - ), - ] - message: Annotated[ - str, Field(description='A human-readable description of the error.') - ] - - -class IncompleteDetails2(BaseModel): - reason: Annotated[ - Optional[Literal['max_completion_tokens', 'max_prompt_tokens']], - Field( - description='The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run.' - ), - ] = None - - -class RunStepCompletionUsage1(BaseModel): - completion_tokens: Annotated[ - int, - Field( - description='Number of completion tokens used over the course of the run step.' - ), - ] - prompt_tokens: Annotated[ - int, - Field( - description='Number of prompt tokens used over the course of the run step.' - ), - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (prompt + completion).') - ] - - -class RunStepCompletionUsage(BaseModel): - __root__: Optional[RunStepCompletionUsage1] - - -class MessageCreation(BaseModel): - message_id: Annotated[ - Optional[str], - Field(description='The ID of the message that was created by this run step.'), - ] = None - - -class RunStepDeltaStepDetailsMessageCreationObject(BaseModel): - type: Annotated[ - Literal['RunStepDeltaStepDetailsMessageCreationObject'], - Field(description='Always `message_creation`.'), - ] - message_creation: Optional[MessageCreation] = None - - -class Image2(BaseModel): - file_id: Annotated[ - Optional[str], - Field( - description='The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.' - ), - ] = None - - -class RunStepDeltaStepDetailsToolCallsCodeOutputImageObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the output in the outputs array.') - ] - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsCodeOutputImageObject'], - Field(description='Always `image`.'), - ] - image: Optional[Image2] = None - - -class RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the output in the outputs array.') - ] - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject'], - Field(description='Always `logs`.'), - ] - logs: Annotated[ - Optional[str], - Field(description='The text output from the Code Interpreter tool call.'), - ] = None - - -class RunStepDeltaStepDetailsToolCallsFileSearchObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the tool call in the tool calls array.') - ] - id: Annotated[ - Optional[str], Field(description='The ID of the tool call object.') - ] = None - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsFileSearchObject'], - Field( - description='The type of tool call. This is always going to be `file_search` for this type of tool call.' - ), - ] - file_search: Annotated[ - Dict[str, Any], - Field(description='For now, this is always going to be an empty object.'), - ] - - -class Function4(BaseModel): - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - arguments: Annotated[ - Optional[str], Field(description='The arguments passed to the function.') - ] = None - output: Optional[str] = None - - -class RunStepDeltaStepDetailsToolCallsFunctionObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the tool call in the tool calls array.') - ] - id: Annotated[ - Optional[str], Field(description='The ID of the tool call object.') - ] = None - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsFunctionObject'], - Field( - description='The type of tool call. This is always going to be `function` for this type of tool call.' - ), - ] - function: Annotated[ - Optional[Function4], - Field(description='The definition of the function that was called.'), - ] = None - - -class MessageCreation1(BaseModel): - message_id: Annotated[ - str, - Field(description='The ID of the message that was created by this run step.'), - ] - - -class RunStepDetailsMessageCreationObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsMessageCreationObject'], - Field(description='Always `message_creation`.'), - ] - message_creation: MessageCreation1 - - -class Image3(BaseModel): - file_id: Annotated[ - str, - Field( - description='The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.' - ), - ] - - -class RunStepDetailsToolCallsCodeOutputImageObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsToolCallsCodeOutputImageObject'], - Field(description='Always `image`.'), - ] - image: Image3 - - -class RunStepDetailsToolCallsCodeOutputLogsObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsToolCallsCodeOutputLogsObject'], - Field(description='Always `logs`.'), - ] - logs: Annotated[ - str, Field(description='The text output from the Code Interpreter tool call.') - ] - - -class RunStepDetailsToolCallsFileSearchRankingOptionsObject(BaseModel): - ranker: FileSearchRanker - score_threshold: Annotated[ - float, - Field( - description='The score threshold for the file search. All values must be a floating point number between 0 and 1.', - ge=0.0, - le=1.0, - ), - ] - - -class ContentItem5(BaseModel): - type: Annotated[ - Optional[Literal['text']], Field(description='The type of the content.') - ] = None - text: Annotated[ - Optional[str], Field(description='The text content of the file.') - ] = None - - -class RunStepDetailsToolCallsFileSearchResultObject(BaseModel): - file_id: Annotated[ - str, Field(description='The ID of the file that result was found in.') - ] - file_name: Annotated[ - str, Field(description='The name of the file that result was found in.') - ] - score: Annotated[ - float, - Field( - description='The score of the result. All values must be a floating point number between 0 and 1.', - ge=0.0, - le=1.0, - ), - ] - content: Annotated[ - Optional[List[ContentItem5]], - Field( - description='The content of the result that was found. The content is only included if requested via the include query parameter.' - ), - ] = None - - -class Function5(BaseModel): - name: Annotated[str, Field(description='The name of the function.')] - arguments: Annotated[ - str, Field(description='The arguments passed to the function.') - ] - output: Optional[str] - - -class RunStepDetailsToolCallsFunctionObject(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call object.')] - type: Annotated[ - Literal['RunStepDetailsToolCallsFunctionObject'], - Field( - description='The type of tool call. This is always going to be `function` for this type of tool call.' - ), - ] - function: Annotated[ - Function5, Field(description='The definition of the function that was called.') - ] - - -class LastError1(BaseModel): - code: Annotated[ - Literal['server_error', 'rate_limit_exceeded'], - Field(description='One of `server_error` or `rate_limit_exceeded`.'), - ] - message: Annotated[ - str, Field(description='A human-readable description of the error.') - ] - - -class Function6(BaseModel): - name: Annotated[str, Field(description='The name of the function.')] - arguments: Annotated[ - str, - Field( - description='The arguments that the model expects you to pass to the function.' - ), - ] - - -class RunToolCallObject(BaseModel): - id: Annotated[ - str, - Field( - description='The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint.' - ), - ] - type: Annotated[ - Literal['function'], - Field( - description='The type of tool call the output is required for. For now, this is always `function`.' - ), - ] - function: Annotated[Function6, Field(description='The function definition.')] - - -class Screenshot(BaseModel): - type: Annotated[ - Literal['Screenshot'], - Field( - description='Specifies the event type. For a screenshot action, this property is \nalways set to `screenshot`.\n' - ), - ] - - -class Scroll(BaseModel): - type: Annotated[ - Literal['Scroll'], - Field( - description='Specifies the event type. For a scroll action, this property is \nalways set to `scroll`.\n' - ), - ] - x: Annotated[ - int, Field(description='The x-coordinate where the scroll occurred.\n') - ] - y: Annotated[ - int, Field(description='The y-coordinate where the scroll occurred.\n') - ] - scroll_x: Annotated[int, Field(description='The horizontal scroll distance.\n')] - scroll_y: Annotated[int, Field(description='The vertical scroll distance.\n')] - - -class ServiceTier(BaseModel): - __root__: Optional[Literal['auto', 'default', 'flex', 'scale', 'priority']] - - -class SpeechAudioDeltaEvent(BaseModel): - type: Annotated[ - Literal['SpeechAudioDeltaEvent'], - Field(description='The type of the event. Always `speech.audio.delta`.\n'), - ] - audio: Annotated[str, Field(description='A chunk of Base64-encoded audio data.\n')] - - -class Usage5(BaseModel): - input_tokens: Annotated[ - int, Field(description='Number of input tokens in the prompt.') - ] - output_tokens: Annotated[ - int, Field(description='Number of output tokens generated.') - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (input + output).') - ] - - -class SpeechAudioDoneEvent(BaseModel): - type: Annotated[ - Literal['SpeechAudioDoneEvent'], - Field(description='The type of the event. Always `speech.audio.done`.\n'), - ] - usage: Annotated[ - Usage5, Field(description='Token usage statistics for the request.\n') - ] - - -class StaticChunkingStrategy(BaseModel): - class Config: - extra = Extra.forbid - - max_chunk_size_tokens: Annotated[ - int, - Field( - description='The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.', - ge=100, - le=4096, - ), - ] - chunk_overlap_tokens: Annotated[ - int, - Field( - description='The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n' - ), - ] - - -class StaticChunkingStrategyRequestParam(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['StaticChunkingStrategyRequestParam'], - Field(description='Always `static`.'), - ] - static: StaticChunkingStrategy - - -class StaticChunkingStrategyResponseParam(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['StaticChunkingStrategyResponseParam'], - Field(description='Always `static`.'), - ] - static: StaticChunkingStrategy - - -class StopConfiguration1(BaseModel): - __root__: Annotated[ - Optional[List[str]], - Field( - description='Not supported with latest reasoning models `o3` and `o4-mini`.\n\nUp to 4 sequences where the API will stop generating further tokens. The\nreturned text will not contain the stop sequence.\n', - max_items=4, - min_items=1, - ), - ] = None - - -class StopConfiguration(BaseModel): - __root__: Annotated[ - Optional[Union[Optional[str], StopConfiguration1]], - Field( - description='Not supported with latest reasoning models `o3` and `o4-mini`.\n\nUp to 4 sequences where the API will stop generating further tokens. The\nreturned text will not contain the stop sequence.\n' - ), - ] = None - - -class ToolOutput(BaseModel): - tool_call_id: Annotated[ - Optional[str], - Field( - description='The ID of the tool call in the `required_action` object within the run object the output is being submitted for.' - ), - ] = None - output: Annotated[ - Optional[str], - Field( - description='The output of the tool call to be submitted to continue the run.' - ), - ] = None - - -class SubmitToolOutputsRunRequest(BaseModel): - class Config: - extra = Extra.forbid - - tool_outputs: Annotated[ - List[ToolOutput], - Field(description='A list of tools for which the outputs are being submitted.'), - ] - stream: Optional[bool] = None - - -class TextResponseFormatJsonSchema(BaseModel): - type: Annotated[ - Literal['TextResponseFormatJsonSchema'], - Field( - description='The type of response format being defined. Always `json_schema`.' - ), - ] - description: Annotated[ - Optional[str], - Field( - description='A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n' - ), - ] = None - name: Annotated[ - str, - Field( - description='The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n' - ), - ] - schema_: Annotated[ResponseFormatJsonSchemaSchema, Field(alias='schema')] - strict: Optional[bool] = None - - -class ToolResources6(BaseModel): - code_interpreter: Optional[CodeInterpreter5] = None - file_search: Optional[FileSearch8] = None - - -class ThreadObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['thread'], - Field(description='The object type, which is always `thread`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the thread was created.' - ), - ] - tool_resources: Optional[ToolResources6] - metadata: Metadata - - -class ThreadStreamEvent1(BaseModel): - enabled: Annotated[ - Optional[bool], - Field(description='Whether to enable input audio transcription.'), - ] = None - event: Literal['thread.created'] - data: ThreadObject - - -class ThreadStreamEvent(BaseModel): - __root__: Annotated[ThreadStreamEvent1, Field(discriminator='event')] - - -class ToggleCertificatesRequest(BaseModel): - certificate_ids: Annotated[List[str], Field(max_items=10, min_items=1)] - - -class ToolChoiceAllowed(BaseModel): - type: Annotated[ - Literal['ToolChoiceAllowed'], - Field(description='Allowed tool configuration type. Always `allowed_tools`.'), - ] - mode: Annotated[ - Literal['auto', 'required'], - Field( - description='Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n' - ), - ] - tools: Annotated[ - List[Dict[str, Any]], - Field( - description='A list of tool definitions that the model should be allowed to call.\n\nFor the Responses API, the list of tool definitions might look like:\n```json\n[\n { "type": "function", "name": "get_weather" },\n { "type": "mcp", "server_label": "deepwiki" },\n { "type": "image_generation" }\n]\n```\n' - ), - ] - - -class ToolChoiceCustom(BaseModel): - type: Annotated[ - Literal['ToolChoiceCustom'], - Field(description='For custom tool calling, the type is always `custom`.'), - ] - name: Annotated[str, Field(description='The name of the custom tool to call.')] - - -class ToolChoiceFunction(BaseModel): - type: Annotated[ - Literal['ToolChoiceFunction'], - Field(description='For function calling, the type is always `function`.'), - ] - name: Annotated[str, Field(description='The name of the function to call.')] - - -class ToolChoiceMCP(BaseModel): - type: Annotated[ - Literal['ToolChoiceMCP'], - Field(description='For MCP tools, the type is always `mcp`.'), - ] - server_label: Annotated[ - str, Field(description='The label of the MCP server to use.\n') - ] - name: Optional[str] = None - - -class ToolChoiceOptions(BaseModel): - __root__: Annotated[ - Literal['none', 'auto', 'required'], - Field( - description='Controls which (if any) tool is called by the model.\n\n`none` means the model will not call any tool and instead generates a message.\n\n`auto` means the model can pick between generating a message or calling one or\nmore tools.\n\n`required` means the model must call one or more tools.\n', - title='Tool choice mode', - ), - ] - - -class ToolChoiceTypes(BaseModel): - type: Annotated[ - Literal['ToolChoiceTypes'], - Field( - description='The type of hosted tool the model should to use. Learn more about\n[built-in tools](https://platform.openai.com/docs/guides/tools).\n\nAllowed values are:\n- `file_search`\n- `web_search_preview`\n- `computer_use_preview`\n- `code_interpreter`\n- `image_generation`\n' - ), - ] - - -class Logprob1(BaseModel): - token: Annotated[ - Optional[str], - Field(description='The token that was used to generate the log probability.\n'), - ] = None - logprob: Annotated[ - Optional[float], Field(description='The log probability of the token.\n') - ] = None - bytes: Annotated[ - Optional[List[int]], - Field( - description='The bytes that were used to generate the log probability.\n' - ), - ] = None - - -class TranscriptTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['TranscriptTextDeltaEvent'], - Field(description='The type of the event. Always `transcript.text.delta`.\n'), - ] - delta: Annotated[ - str, Field(description='The text delta that was additionally transcribed.\n') - ] - logprobs: Annotated[ - Optional[List[Logprob1]], - Field( - description='The log probabilities of the delta. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n' - ), - ] = None - segment_id: Annotated[ - Optional[str], - Field( - description='Identifier of the diarized segment that this delta belongs to. Only present when using `gpt-4o-transcribe-diarize`.\n' - ), - ] = None - - -class TranscriptTextSegmentEvent(BaseModel): - type: Annotated[ - Literal['TranscriptTextSegmentEvent'], - Field(description='The type of the event. Always `transcript.text.segment`.'), - ] - id: Annotated[str, Field(description='Unique identifier for the segment.')] - start: Annotated[ - float, Field(description='Start timestamp of the segment in seconds.') - ] - end: Annotated[float, Field(description='End timestamp of the segment in seconds.')] - text: Annotated[str, Field(description='Transcript text for this segment.')] - speaker: Annotated[str, Field(description='Speaker label for this segment.')] - - -class TranscriptTextUsageDuration(BaseModel): - type: Annotated[ - Literal['TranscriptTextUsageDuration'], - Field( - description='The type of the usage object. Always `duration` for this variant.' - ), - ] - seconds: Annotated[ - float, Field(description='Duration of the input audio in seconds.') - ] - - -class InputTokenDetails2(BaseModel): - text_tokens: Annotated[ - Optional[int], - Field(description='Number of text tokens billed for this request.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='Number of audio tokens billed for this request.'), - ] = None - - -class TranscriptTextUsageTokens(BaseModel): - type: Annotated[ - Literal['TranscriptTextUsageTokens'], - Field( - description='The type of the usage object. Always `tokens` for this variant.' - ), - ] - input_tokens: Annotated[ - int, Field(description='Number of input tokens billed for this request.') - ] - input_token_details: Annotated[ - Optional[InputTokenDetails2], - Field(description='Details about the input tokens billed for this request.'), - ] = None - output_tokens: Annotated[ - int, Field(description='Number of output tokens generated.') - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (input + output).') - ] - - -class TranscriptionDiarizedSegment(BaseModel): - type: Annotated[ - Literal['transcript.text.segment'], - Field( - description='The type of the segment. Always `transcript.text.segment`.\n' - ), - ] - id: Annotated[str, Field(description='Unique identifier for the segment.')] - start: Annotated[ - float, Field(description='Start timestamp of the segment in seconds.') - ] - end: Annotated[float, Field(description='End timestamp of the segment in seconds.')] - text: Annotated[str, Field(description='Transcript text for this segment.')] - speaker: Annotated[ - str, - Field( - description='Speaker label for this segment. When known speakers are provided, the label matches `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, `B`, ...).\n' - ), - ] - - -class TranscriptionInclude(BaseModel): - __root__: Literal['logprobs'] - - -class TranscriptionSegment(BaseModel): - id: Annotated[int, Field(description='Unique identifier of the segment.')] - seek: Annotated[int, Field(description='Seek offset of the segment.')] - start: Annotated[float, Field(description='Start time of the segment in seconds.')] - end: Annotated[float, Field(description='End time of the segment in seconds.')] - text: Annotated[str, Field(description='Text content of the segment.')] - tokens: Annotated[ - List[int], Field(description='Array of token IDs for the text content.') - ] - temperature: Annotated[ - float, - Field(description='Temperature parameter used for generating the segment.'), - ] - avg_logprob: Annotated[ - float, - Field( - description='Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.' - ), - ] - compression_ratio: Annotated[ - float, - Field( - description='Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.' - ), - ] - no_speech_prob: Annotated[ - float, - Field( - description='Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent.' - ), - ] - - -class TranscriptionWord(BaseModel): - word: Annotated[str, Field(description='The text content of the word.')] - start: Annotated[float, Field(description='Start time of the word in seconds.')] - end: Annotated[float, Field(description='End time of the word in seconds.')] - - -class LastMessages(BaseModel): - __root__: Annotated[ - int, - Field( - description='The number of most recent messages from the thread when constructing the context for the run.', - ge=1, - ), - ] - - -class TruncationObject(BaseModel): - type: Annotated[ - Literal['auto', 'last_messages'], - Field( - description='The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.' - ), - ] - last_messages: Optional[LastMessages] = None - - -class Type(BaseModel): - type: Annotated[ - Literal['Type'], - Field( - description='Specifies the event type. For a type action, this property is \nalways set to `type`.\n' - ), - ] - text: Annotated[str, Field(description='The text to type.\n')] - - -class UpdateGroupBody(BaseModel): - name: Annotated[ - str, - Field( - description='New display name for the group.', max_length=255, min_length=1 - ), - ] - - -class Upload(BaseModel): - id: Annotated[ - str, - Field( - description='The Upload unique identifier, which can be referenced in API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the Upload was created.' - ), - ] - filename: Annotated[str, Field(description='The name of the file to be uploaded.')] - bytes: Annotated[ - int, Field(description='The intended number of bytes to be uploaded.') - ] - purpose: Annotated[ - str, - Field( - description='The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values.' - ), - ] - status: Annotated[ - Literal['pending', 'completed', 'cancelled', 'expired'], - Field(description='The status of the Upload.'), - ] - expires_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the Upload will expire.' - ), - ] - object: Annotated[ - Literal['upload'], - Field(description='The object type, which is always "upload".'), - ] - file: Optional[OpenAIFile] = None - - -class UploadCertificateRequest(BaseModel): - name: Annotated[ - Optional[str], Field(description='An optional name for the certificate') - ] = None - content: Annotated[str, Field(description='The certificate content in PEM format')] - - -class UploadPart(BaseModel): - id: Annotated[ - str, - Field( - description='The upload Part unique identifier, which can be referenced in API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the Part was created.' - ), - ] - upload_id: Annotated[ - str, - Field(description='The ID of the Upload object that this Part was added to.'), - ] - object: Annotated[ - Literal['upload.part'], - Field(description='The object type, which is always `upload.part`.'), - ] - - -class UsageAudioSpeechesResult(BaseModel): - object: Literal['UsageAudioSpeechesResult'] - characters: Annotated[int, Field(description='The number of characters processed.')] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageAudioTranscriptionsResult(BaseModel): - object: Literal['UsageAudioTranscriptionsResult'] - seconds: Annotated[int, Field(description='The number of seconds processed.')] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageCodeInterpreterSessionsResult(BaseModel): - object: Literal['UsageCodeInterpreterSessionsResult'] - num_sessions: Annotated[ - Optional[int], Field(description='The number of code interpreter sessions.') - ] = None - project_id: Optional[str] = None - - -class UsageCompletionsResult(BaseModel): - object: Literal['UsageCompletionsResult'] - input_tokens: Annotated[ - int, - Field( - description='The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens.' - ), - ] - input_cached_tokens: Annotated[ - Optional[int], - Field( - description='The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens.' - ), - ] = None - output_tokens: Annotated[ - int, - Field( - description='The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens.' - ), - ] - input_audio_tokens: Annotated[ - Optional[int], - Field( - description='The aggregated number of audio input tokens used, including cached tokens.' - ), - ] = None - output_audio_tokens: Annotated[ - Optional[int], - Field(description='The aggregated number of audio output tokens used.'), - ] = None - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - batch: Optional[bool] = None - service_tier: Optional[str] = None - - -class UsageEmbeddingsResult(BaseModel): - object: Literal['UsageEmbeddingsResult'] - input_tokens: Annotated[ - int, Field(description='The aggregated number of input tokens used.') - ] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageImagesResult(BaseModel): - object: Literal['UsageImagesResult'] - images: Annotated[int, Field(description='The number of images processed.')] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - source: Optional[str] = None - size: Optional[str] = None - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageModerationsResult(BaseModel): - object: Literal['UsageModerationsResult'] - input_tokens: Annotated[ - int, Field(description='The aggregated number of input tokens used.') - ] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageVectorStoresResult(BaseModel): - object: Literal['UsageVectorStoresResult'] - usage_bytes: Annotated[int, Field(description='The vector stores usage in bytes.')] - project_id: Optional[str] = None - - -class User(BaseModel): - object: Annotated[ - Literal['organization.user'], - Field(description='The object type, which is always `organization.user`'), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the user')] - email: Annotated[str, Field(description='The email address of the user')] - role: Annotated[ - Literal['owner', 'reader'], Field(description='`owner` or `reader`') - ] - added_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the user was added.' - ), - ] - - -class UserDeleteResponse(BaseModel): - object: Literal['organization.user.deleted'] - id: str - deleted: bool - - -class UserListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[List[User], Field(description='Users in the current page.')] - has_more: Annotated[ - bool, Field(description='Whether more users are available when paginating.') - ] - next: Annotated[ - Optional[str], - Field( - description='Cursor to fetch the next page of results, or `null` when no further users are available.' - ), - ] - - -class UserListResponse(BaseModel): - object: Literal['list'] - data: List[User] - first_id: str - last_id: str - has_more: bool - - -class UserRoleAssignment(BaseModel): - object: Annotated[Literal['user.role'], Field(description='Always `user.role`.')] - user: User - role: Role - - -class UserRoleUpdateRequest(BaseModel): - role: Annotated[ - Literal['owner', 'reader'], Field(description='`owner` or `reader`') - ] - - -class VadConfig(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['server_vad'], - Field( - description='Must be set to `server_vad` to enable manual chunking using server side VAD.' - ), - ] - prefix_padding_ms: Annotated[ - int, - Field( - description='Amount of audio to include before the VAD detected speech (in \nmilliseconds).\n' - ), - ] = 300 - silence_duration_ms: Annotated[ - int, - Field( - description='Duration of silence to detect speech stop (in milliseconds).\nWith shorter values the model will respond more quickly, \nbut may jump in on short pauses from the user.\n' - ), - ] = 200 - threshold: Annotated[ - float, - Field( - description='Sensitivity threshold (0.0 to 1.0) for voice activity detection. A \nhigher threshold will require louder audio to activate the model, and \nthus might perform better in noisy environments.\n' - ), - ] = 0.5 - - -class VectorStoreExpirationAfter(BaseModel): - anchor: Annotated[ - Literal['last_active_at'], - Field( - description='Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.' - ), - ] - days: Annotated[ - int, - Field( - description='The number of days after the anchor time that the vector store will expire.', - ge=1, - le=365, - ), - ] - - -class VectorStoreFileAttributes1(BaseModel): - __root__: Annotated[str, Field(max_length=512)] - - -class VectorStoreFileAttributes(BaseModel): - __root__: Optional[Dict[str, Union[VectorStoreFileAttributes1, float, bool]]] - - -class FileCounts(BaseModel): - in_progress: Annotated[ - int, - Field(description='The number of files that are currently being processed.'), - ] - completed: Annotated[ - int, Field(description='The number of files that have been processed.') - ] - failed: Annotated[ - int, Field(description='The number of files that have failed to process.') - ] - cancelled: Annotated[ - int, Field(description='The number of files that where cancelled.') - ] - total: Annotated[int, Field(description='The total number of files.')] - - -class VectorStoreFileBatchObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['vector_store.files_batch'], - Field( - description='The object type, which is always `vector_store.file_batch`.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the vector store files batch was created.' - ), - ] - vector_store_id: Annotated[ - str, - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.' - ), - ] - status: Annotated[ - Literal['in_progress', 'completed', 'cancelled', 'failed'], - Field( - description='The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`.' - ), - ] - file_counts: FileCounts - - -class Datum1(BaseModel): - type: Annotated[ - Optional[str], Field(description='The content type (currently only `"text"`)') - ] = None - text: Annotated[Optional[str], Field(description='The text content')] = None - - -class VectorStoreFileContentResponse(BaseModel): - object: Annotated[ - Literal['vector_store.file_content.page'], - Field( - description='The object type, which is always `vector_store.file_content.page`' - ), - ] - data: Annotated[List[Datum1], Field(description='Parsed content of the file.')] - has_more: Annotated[ - bool, Field(description='Indicates if there are more content pages to fetch.') - ] - next_page: Optional[str] - - -class LastError2(BaseModel): - code: Annotated[ - Literal['server_error', 'unsupported_file', 'invalid_file'], - Field( - description='One of `server_error`, `unsupported_file`, or `invalid_file`.' - ), - ] - message: Annotated[ - str, Field(description='A human-readable description of the error.') - ] - - -class FileCounts1(BaseModel): - in_progress: Annotated[ - int, - Field(description='The number of files that are currently being processed.'), - ] - completed: Annotated[ - int, - Field(description='The number of files that have been successfully processed.'), - ] - failed: Annotated[ - int, Field(description='The number of files that have failed to process.') - ] - cancelled: Annotated[ - int, Field(description='The number of files that were cancelled.') - ] - total: Annotated[int, Field(description='The total number of files.')] - - -class VectorStoreObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['vector_store'], - Field(description='The object type, which is always `vector_store`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the vector store was created.' - ), - ] - name: Annotated[str, Field(description='The name of the vector store.')] - usage_bytes: Annotated[ - int, - Field( - description='The total number of bytes used by the files in the vector store.' - ), - ] - file_counts: FileCounts1 - status: Annotated[ - Literal['expired', 'in_progress', 'completed'], - Field( - description='The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use.' - ), - ] - expires_after: Optional[VectorStoreExpirationAfter] = None - expires_at: Optional[int] = None - last_active_at: Optional[int] - metadata: Metadata - - -class QueryItem(BaseModel): - __root__: Annotated[ - str, Field(description='A list of queries to search for.', min_items=1) - ] - - -class RankingOptions(BaseModel): - class Config: - extra = Extra.forbid - - ranker: Annotated[ - Literal['none', 'auto', 'default-2024-11-15'], - Field( - description='Enable re-ranking; set to `none` to disable, which can help reduce latency.' - ), - ] = 'auto' - score_threshold: Annotated[float, Field(ge=0.0, le=1.0)] = 0 - - -class VectorStoreSearchResultContentObject(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[Literal['text'], Field(description='The type of content.')] - text: Annotated[str, Field(description='The text content returned from search.')] - - -class VectorStoreSearchResultItem(BaseModel): - class Config: - extra = Extra.forbid - - file_id: Annotated[str, Field(description='The ID of the vector store file.')] - filename: Annotated[str, Field(description='The name of the vector store file.')] - score: Annotated[ - float, Field(description='The similarity score for the result.', ge=0.0, le=1.0) - ] - attributes: VectorStoreFileAttributes - content: Annotated[ - List[VectorStoreSearchResultContentObject], - Field(description='Content chunks from the file.'), - ] - - -class SearchQueryItem(BaseModel): - __root__: Annotated[ - str, Field(description='The query used for this search.', min_items=1) - ] - - -class VectorStoreSearchResultsPage(BaseModel): - class Config: - extra = Extra.forbid - - object: Annotated[ - Literal['vector_store.search_results.page'], - Field( - description='The object type, which is always `vector_store.search_results.page`' - ), - ] - search_query: List[SearchQueryItem] - data: Annotated[ - List[VectorStoreSearchResultItem], - Field(description='The list of search result items.'), - ] - has_more: Annotated[ - bool, Field(description='Indicates if there are more results to fetch.') - ] - next_page: Optional[str] - - -class Verbosity(BaseModel): - __root__: Optional[Literal['low', 'medium', 'high']] - - -class VoiceIdsShared(BaseModel): - __root__: Annotated[ - Union[ - str, - Literal[ - 'alloy', - 'ash', - 'ballad', - 'coral', - 'echo', - 'sage', - 'shimmer', - 'verse', - 'marin', - 'cedar', - ], - ], - Field(example='ash'), - ] - - -class Wait(BaseModel): - type: Annotated[ - Literal['Wait'], - Field( - description='Specifies the event type. For a wait action, this property is \nalways set to `wait`.\n' - ), - ] - - -class WebSearchActionFind(BaseModel): - type: Annotated[ - Literal['WebSearchActionFind'], Field(description='The action type.\n') - ] - url: Annotated[ - AnyUrl, Field(description='The URL of the page searched for the pattern.\n') - ] - pattern: Annotated[ - str, Field(description='The pattern or text to search for within the page.\n') - ] - - -class WebSearchActionOpenPage(BaseModel): - type: Annotated[ - Literal['WebSearchActionOpenPage'], Field(description='The action type.\n') - ] - url: Annotated[AnyUrl, Field(description='The URL opened by the model.\n')] - - -class Source(BaseModel): - type: Annotated[ - Literal['url'], Field(description='The type of source. Always `url`.\n') - ] - url: Annotated[str, Field(description='The URL of the source.\n')] - - -class WebSearchActionSearch(BaseModel): - type: Annotated[ - Literal['WebSearchActionSearch'], Field(description='The action type.\n') - ] - query: Annotated[str, Field(description='The search query.\n')] - sources: Annotated[ - Optional[List[Source]], - Field( - description='The sources used in the search.\n', title='Web search sources' - ), - ] = None - - -class WebSearchApproximateLocation1(BaseModel): - type: Annotated[ - Literal['approximate'], - Field(description='The type of location approximation. Always `approximate`.'), - ] = 'approximate' - country: Optional[str] = None - region: Optional[str] = None - city: Optional[str] = None - timezone: Optional[str] = None - - -class WebSearchApproximateLocation(BaseModel): - __root__: Optional[WebSearchApproximateLocation1] - - -class WebSearchContextSize(BaseModel): - __root__: Annotated[ - Literal['low', 'medium', 'high'], - Field( - description='High level guidance for the amount of context window space to use for the \nsearch. One of `low`, `medium`, or `high`. `medium` is the default.\n' - ), - ] - - -class WebSearchLocation(BaseModel): - country: Annotated[ - Optional[str], - Field( - description='The two-letter \n[ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user,\ne.g. `US`.\n' - ), - ] = None - region: Annotated[ - Optional[str], - Field( - description='Free text input for the region of the user, e.g. `California`.\n' - ), - ] = None - city: Annotated[ - Optional[str], - Field( - description='Free text input for the city of the user, e.g. `San Francisco`.\n' - ), - ] = None - timezone: Annotated[ - Optional[str], - Field( - description='The [IANA timezone](https://timeapi.io/documentation/iana-timezones) \nof the user, e.g. `America/Los_Angeles`.\n' - ), - ] = None - - -class Filters1(BaseModel): - allowed_domains: Optional[List[str]] = None - - -class WebSearchTool(BaseModel): - type: Annotated[ - Literal['WebSearchTool'], - Field( - description='The type of the web search tool. One of `web_search` or `web_search_2025_08_26`.' - ), - ] - filters: Optional[Filters1] = None - user_location: Optional[WebSearchApproximateLocation] = None - search_context_size: Annotated[ - Literal['low', 'medium', 'high'], - Field( - description='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.' - ), - ] = 'medium' - - -class WebSearchToolCall(BaseModel): - id: Annotated[ - str, Field(description='The unique ID of the web search tool call.\n') - ] - type: Annotated[ - Literal['WebSearchToolCall'], - Field( - description='The type of the web search tool call. Always `web_search_call`.\n' - ), - ] - status: Annotated[ - Literal['in_progress', 'searching', 'completed', 'failed'], - Field(description='The status of the web search tool call.\n'), - ] - action: Annotated[ - Union[WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind], - Field( - description='An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find).\n', - discriminator='type', - ), - ] - - -class Data7(BaseModel): - id: Annotated[str, Field(description='The unique ID of the batch API request.\n')] - - -class WebhookBatchCancelled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request was cancelled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.cancelled'], - Field(description='The type of the event. Always `batch.cancelled`.\n'), - ] - - -class WebhookBatchCompleted(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request was completed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.completed'], - Field(description='The type of the event. Always `batch.completed`.\n'), - ] - - -class WebhookBatchExpired(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request expired.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.expired'], - Field(description='The type of the event. Always `batch.expired`.\n'), - ] - - -class WebhookBatchFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.failed'], - Field(description='The type of the event. Always `batch.failed`.\n'), - ] - - -class Data11(BaseModel): - id: Annotated[str, Field(description='The unique ID of the eval run.\n')] - - -class WebhookEvalRunCanceled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the eval run was canceled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data11, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['eval.run.canceled'], - Field(description='The type of the event. Always `eval.run.canceled`.\n'), - ] - - -class WebhookEvalRunFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the eval run failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data11, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['eval.run.failed'], - Field(description='The type of the event. Always `eval.run.failed`.\n'), - ] - - -class WebhookEvalRunSucceeded(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the eval run succeeded.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data11, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['eval.run.succeeded'], - Field(description='The type of the event. Always `eval.run.succeeded`.\n'), - ] - - -class Data14(BaseModel): - id: Annotated[str, Field(description='The unique ID of the fine-tuning job.\n')] - - -class WebhookFineTuningJobCancelled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the fine-tuning job was cancelled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data14, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['fine_tuning.job.cancelled'], - Field( - description='The type of the event. Always `fine_tuning.job.cancelled`.\n' - ), - ] - - -class WebhookFineTuningJobFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the fine-tuning job failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data14, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['fine_tuning.job.failed'], - Field(description='The type of the event. Always `fine_tuning.job.failed`.\n'), - ] - - -class WebhookFineTuningJobSucceeded(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the fine-tuning job succeeded.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data14, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['fine_tuning.job.succeeded'], - Field( - description='The type of the event. Always `fine_tuning.job.succeeded`.\n' - ), - ] - - -class SipHeader(BaseModel): - name: Annotated[str, Field(description='Name of the SIP Header.\n')] - value: Annotated[str, Field(description='Value of the SIP Header.\n')] - - -class Data17(BaseModel): - call_id: Annotated[str, Field(description='The unique ID of this call.\n')] - sip_headers: Annotated[ - List[SipHeader], Field(description='Headers from the SIP Invite.\n') - ] - - -class WebhookRealtimeCallIncoming(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was completed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data17, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['realtime.call.incoming'], - Field(description='The type of the event. Always `realtime.call.incoming`.\n'), - ] - - -class Data18(BaseModel): - id: Annotated[str, Field(description='The unique ID of the model response.\n')] - - -class WebhookResponseCancelled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was cancelled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.cancelled'], - Field(description='The type of the event. Always `response.cancelled`.\n'), - ] - - -class WebhookResponseCompleted(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was completed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.completed'], - Field(description='The type of the event. Always `response.completed`.\n'), - ] - - -class WebhookResponseFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.failed'], - Field(description='The type of the event. Always `response.failed`.\n'), - ] - - -class WebhookResponseIncomplete(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was interrupted.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.incomplete'], - Field(description='The type of the event. Always `response.incomplete`.\n'), - ] - - -class IncludeEnum(BaseModel): - __root__: Annotated[ - Literal[ - 'file_search_call.results', - 'web_search_call.results', - 'web_search_call.action.sources', - 'message.input_image.image_url', - 'computer_call_output.output.image_url', - 'code_interpreter_call.outputs', - 'reasoning.encrypted_content', - 'message.output_text.logprobs', - ], - Field( - description='Specify additional output data to include in the model response. Currently supported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `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).' - ), - ] - - -class MessageStatus(BaseModel): - __root__: Literal['in_progress', 'completed', 'incomplete'] - - -class MessageRole(BaseModel): - __root__: Literal[ - 'unknown', - 'user', - 'assistant', - 'system', - 'critic', - 'discriminator', - 'developer', - 'tool', - ] - - -class InputTextContent(BaseModel): - type: Annotated[ - Literal['InputTextContent'], - Field(description='The type of the input item. Always `input_text`.'), - ] - text: Annotated[str, Field(description='The text input to the model.')] - - -class FileCitationBody(BaseModel): - type: Annotated[ - Literal['FileCitationBody'], - Field(description='The type of the file citation. Always `file_citation`.'), - ] - file_id: Annotated[str, Field(description='The ID of the file.')] - index: Annotated[ - int, Field(description='The index of the file in the list of files.') - ] - filename: Annotated[str, Field(description='The filename of the file cited.')] - - -class UrlCitationBody(BaseModel): - type: Annotated[ - Literal['UrlCitationBody'], - Field(description='The type of the URL citation. Always `url_citation`.'), - ] - url: Annotated[str, Field(description='The URL of the web resource.')] - start_index: Annotated[ - int, - Field( - description='The index of the first character of the URL citation in the message.' - ), - ] - end_index: Annotated[ - int, - Field( - description='The index of the last character of the URL citation in the message.' - ), - ] - title: Annotated[str, Field(description='The title of the web resource.')] - - -class ContainerFileCitationBody(BaseModel): - type: Annotated[ - Literal['ContainerFileCitationBody'], - Field( - description='The type of the container file citation. Always `container_file_citation`.' - ), - ] - container_id: Annotated[str, Field(description='The ID of the container file.')] - file_id: Annotated[str, Field(description='The ID of the file.')] - start_index: Annotated[ - int, - Field( - description='The index of the first character of the container file citation in the message.' - ), - ] - end_index: Annotated[ - int, - Field( - description='The index of the last character of the container file citation in the message.' - ), - ] - filename: Annotated[ - str, Field(description='The filename of the container file cited.') - ] - - -class Annotation1(BaseModel): - __root__: Annotated[ - Union[FileCitationBody, UrlCitationBody, ContainerFileCitationBody, FilePath], - Field(discriminator='type'), - ] - - -class TopLogProb(BaseModel): - token: str - logprob: float - bytes: List[int] - - -class LogProb(BaseModel): - token: str - logprob: float - bytes: List[int] - top_logprobs: List[TopLogProb] - - -class OutputTextContent(BaseModel): - type: Annotated[ - Literal['OutputTextContent'], - Field(description='The type of the output text. Always `output_text`.'), - ] - text: Annotated[str, Field(description='The text output from the model.')] - annotations: Annotated[ - List[Annotation1], Field(description='The annotations of the text output.') - ] - logprobs: Optional[List[LogProb]] = None - - -class TextContent(BaseModel): - type: Literal['TextContent'] - text: str - - -class SummaryTextContent(BaseModel): - type: Annotated[ - Literal['SummaryTextContent'], - Field(description='The type of the object. Always `summary_text`.'), - ] - text: Annotated[ - str, - Field(description='A summary of the reasoning output from the model so far.'), - ] - - -class ReasoningTextContent(BaseModel): - type: Annotated[ - Literal['ReasoningTextContent'], - Field(description='The type of the reasoning text. Always `reasoning_text`.'), - ] - text: Annotated[str, Field(description='The reasoning text from the model.')] - - -class RefusalContent(BaseModel): - type: Annotated[ - Literal['RefusalContent'], - Field(description='The type of the refusal. Always `refusal`.'), - ] - refusal: Annotated[ - str, Field(description='The refusal explanation from the model.') - ] - - -class ImageDetail(BaseModel): - __root__: Literal['low', 'high', 'auto'] - - -class InputImageContent(BaseModel): - type: Annotated[ - Literal['InputImageContent'], - Field(description='The type of the input item. Always `input_image`.'), - ] - image_url: Optional[str] = None - file_id: Optional[str] = None - detail: Annotated[ - ImageDetail, - Field( - description='The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.' - ), - ] - - -class ComputerScreenshotContent(BaseModel): - type: Annotated[ - Literal['ComputerScreenshotContent'], - Field( - description='Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`.' - ), - ] - image_url: Optional[str] - file_id: Optional[str] - - -class InputFileContent(BaseModel): - type: Annotated[ - Literal['InputFileContent'], - Field(description='The type of the input item. Always `input_file`.'), - ] - file_id: Optional[str] = None - filename: Annotated[ - Optional[str], - Field(description='The name of the file to be sent to the model.'), - ] = None - file_url: Annotated[ - Optional[str], Field(description='The URL of the file to be sent to the model.') - ] = None - file_data: Annotated[ - Optional[str], - Field(description='The content of the file to be sent to the model.\n'), - ] = None - - -class Content10(BaseModel): - __root__: Annotated[ - Union[ - InputTextContent, - OutputTextContent, - TextContent, - SummaryTextContent, - ReasoningTextContent, - RefusalContent, - InputImageContent, - ComputerScreenshotContent, - InputFileContent, - ], - Field(discriminator='type'), - ] - - -class Message(BaseModel): - type: Annotated[ - Literal['Message'], - Field(description='The type of the message. Always set to `message`.'), - ] - id: Annotated[str, Field(description='The unique ID of the message.')] - status: Annotated[ - MessageStatus, - Field( - description='The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API.' - ), - ] - role: Annotated[ - MessageRole, - Field( - description='The role of the message. One of `unknown`, `user`, `assistant`, `system`, `critic`, `discriminator`, `developer`, or `tool`.' - ), - ] - content: Annotated[List[Content10], Field(description='The content of the message')] - - -class ClickButtonType(BaseModel): - __root__: Literal['left', 'right', 'wheel', 'back', 'forward'] - - -class ClickParam(BaseModel): - type: Annotated[ - Literal['ClickParam'], - Field( - description='Specifies the event type. For a click action, this property is always `click`.' - ), - ] - button: Annotated[ - ClickButtonType, - Field( - description='Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`.' - ), - ] - x: Annotated[int, Field(description='The x-coordinate where the click occurred.')] - y: Annotated[int, Field(description='The y-coordinate where the click occurred.')] - - -class DoubleClickAction(BaseModel): - type: Annotated[ - Literal['DoubleClickAction'], - Field( - description='Specifies the event type. For a double click action, this property is always set to `double_click`.' - ), - ] - x: Annotated[ - int, Field(description='The x-coordinate where the double click occurred.') - ] - y: Annotated[ - int, Field(description='The y-coordinate where the double click occurred.') - ] - - -class DragPoint(BaseModel): - x: Annotated[int, Field(description='The x-coordinate.')] - y: Annotated[int, Field(description='The y-coordinate.')] - - -class KeyPressAction(BaseModel): - type: Annotated[ - Literal['KeyPressAction'], - Field( - description='Specifies the event type. For a keypress action, this property is always set to `keypress`.' - ), - ] - keys: Annotated[ - List[str], - Field( - description='The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key.' - ), - ] - - -class ComputerCallSafetyCheckParam(BaseModel): - id: Annotated[str, Field(description='The ID of the pending safety check.')] - code: Optional[str] = None - message: Optional[str] = None - - -class CodeInterpreterOutputLogs(BaseModel): - type: Annotated[ - Literal['CodeInterpreterOutputLogs'], - Field(description='The type of the output. Always `logs`.'), - ] - logs: Annotated[ - str, Field(description='The logs output from the code interpreter.') - ] - - -class CodeInterpreterOutputImage(BaseModel): - type: Annotated[ - Literal['CodeInterpreterOutputImage'], - Field(description='The type of the output. Always `image`.'), - ] - url: Annotated[ - str, Field(description='The URL of the image output from the code interpreter.') - ] - - -class LocalShellExecAction(BaseModel): - type: Annotated[ - Literal['exec'], - Field(description='The type of the local shell action. Always `exec`.'), - ] - command: Annotated[List[str], Field(description='The command to run.')] - timeout_ms: Optional[int] = None - working_directory: Optional[str] = None - env: Annotated[ - Dict[str, str], - Field(description='Environment variables to set for the command.'), - ] - user: Optional[str] = None - - -class FunctionShellAction(BaseModel): - commands: List[str] - timeout_ms: Optional[int] - max_output_length: Optional[int] - - -class LocalShellCallStatus(BaseModel): - __root__: Literal['in_progress', 'completed', 'incomplete'] - - -class FunctionShellCall(BaseModel): - type: Annotated[ - Literal['FunctionShellCall'], - Field(description='The type of the item. Always `shell_call`.'), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call generated by the model.' - ), - ] - action: Annotated[ - FunctionShellAction, - Field( - description='The shell commands and limits that describe how to run the tool call.' - ), - ] - status: Annotated[ - LocalShellCallStatus, - Field( - description='The status of the shell call. One of `in_progress`, `completed`, or `incomplete`.' - ), - ] - created_by: Annotated[ - Optional[str], - Field(description='The ID of the entity that created this tool call.'), - ] = None - - -class FunctionShellCallOutputTimeoutOutcome(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputTimeoutOutcome'], - Field(description='The outcome type. Always `timeout`.'), - ] - - -class FunctionShellCallOutputExitOutcome(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputExitOutcome'], - Field(description='The outcome type. Always `exit`.'), - ] - exit_code: Annotated[int, Field(description='Exit code from the shell process.')] - - -class FunctionShellCallOutputContent(BaseModel): - stdout: str - stderr: str - outcome: Annotated[ - Union[ - FunctionShellCallOutputTimeoutOutcome, FunctionShellCallOutputExitOutcome - ], - Field( - description='Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk.', - discriminator='type', - title='Function shell call outcome', - ), - ] - created_by: Optional[str] = None - - -class FunctionShellCallOutput(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutput'], - Field( - description='The type of the shell call output. Always `shell_call_output`.' - ), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the shell call output. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the shell tool call generated by the model.' - ), - ] - output: Annotated[ - List[FunctionShellCallOutputContent], - Field(description='An array of shell call output contents'), - ] - max_output_length: Optional[int] - created_by: Optional[str] = None - - -class ApplyPatchCallStatus(BaseModel): - __root__: Literal['in_progress', 'completed'] - - -class ApplyPatchCreateFileOperation(BaseModel): - type: Annotated[ - Literal['ApplyPatchCreateFileOperation'], - Field(description='Create a new file with the provided diff.'), - ] - path: Annotated[str, Field(description='Path of the file to create.')] - diff: Annotated[str, Field(description='Diff to apply.')] - - -class ApplyPatchDeleteFileOperation(BaseModel): - type: Annotated[ - Literal['ApplyPatchDeleteFileOperation'], - Field(description='Delete the specified file.'), - ] - path: Annotated[str, Field(description='Path of the file to delete.')] - - -class ApplyPatchUpdateFileOperation(BaseModel): - type: Annotated[ - Literal['ApplyPatchUpdateFileOperation'], - Field(description='Update an existing file with the provided diff.'), - ] - path: Annotated[str, Field(description='Path of the file to update.')] - diff: Annotated[str, Field(description='Diff to apply.')] - - -class ApplyPatchToolCall(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCall'], - Field(description='The type of the item. Always `apply_patch_call`.'), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.' - ), - ] - status: Annotated[ - ApplyPatchCallStatus, - Field( - description='The status of the apply patch tool call. One of `in_progress` or `completed`.' - ), - ] - operation: Annotated[ - Union[ - ApplyPatchCreateFileOperation, - ApplyPatchDeleteFileOperation, - ApplyPatchUpdateFileOperation, - ], - Field( - description='One of the create_file, delete_file, or update_file operations applied via apply_patch.', - discriminator='type', - title='Apply patch operation', - ), - ] - created_by: Annotated[ - Optional[str], - Field(description='The ID of the entity that created this tool call.'), - ] = None - - -class ApplyPatchCallOutputStatus(BaseModel): - __root__: Literal['completed', 'failed'] - - -class ApplyPatchToolCallOutput(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCallOutput'], - Field(description='The type of the item. Always `apply_patch_call_output`.'), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call output. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.' - ), - ] - status: Annotated[ - ApplyPatchCallOutputStatus, - Field( - description='The status of the apply patch tool call output. One of `completed` or `failed`.' - ), - ] - output: Optional[str] = None - created_by: Annotated[ - Optional[str], - Field(description='The ID of the entity that created this tool call output.'), - ] = None - - -class MCPToolCallStatus(BaseModel): - __root__: Literal['in_progress', 'completed', 'incomplete', 'calling', 'failed'] - - -class DetailEnum(BaseModel): - __root__: Literal['low', 'high', 'auto'] - - -class FunctionCallItemStatus(BaseModel): - __root__: Literal['in_progress', 'completed', 'incomplete'] - - -class ComputerCallOutputItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The ID of the computer tool call that produced the output.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['ComputerCallOutputItemParam'], - Field( - description='The type of the computer tool call output. Always `computer_call_output`.' - ), - ] - output: ComputerScreenshotImage - acknowledged_safety_checks: Optional[List[ComputerCallSafetyCheckParam]] = None - status: Optional[FunctionCallItemStatus] = None - - -class InputTextContentParam(BaseModel): - type: Annotated[ - Literal['InputTextContentParam'], - Field(description='The type of the input item. Always `input_text`.'), - ] - text: Annotated[ - str, Field(description='The text input to the model.', max_length=10485760) - ] - - -class ImageUrl3(BaseModel): - __root__: Annotated[ - str, - Field( - description='The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL.', - max_length=20971520, - ), - ] - - -class InputImageContentParamAutoParam(BaseModel): - type: Annotated[ - Literal['InputImageContentParamAutoParam'], - Field(description='The type of the input item. Always `input_image`.'), - ] - image_url: Optional[ImageUrl3] = None - file_id: Optional[str] = None - detail: Optional[DetailEnum] = None - - -class FileData(BaseModel): - __root__: Annotated[ - str, - Field( - description='The base64-encoded data of the file to be sent to the model.', - max_length=33554432, - ), - ] - - -class InputFileContentParam(BaseModel): - type: Annotated[ - Literal['InputFileContentParam'], - Field(description='The type of the input item. Always `input_file`.'), - ] - file_id: Optional[str] = None - filename: Optional[str] = None - file_data: Optional[FileData] = None - file_url: Optional[str] = None - - -class Output5(BaseModel): - __root__: Annotated[ - str, - Field( - description='A JSON string of the output of the function tool call.', - max_length=10485760, - ), - ] - - -class Output6(BaseModel): - __root__: Annotated[ - Union[ - InputTextContentParam, - InputImageContentParamAutoParam, - InputFileContentParam, - ], - Field(discriminator='type'), - ] - - -class FunctionCallOutputItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the function tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['FunctionCallOutputItemParam'], - Field( - description='The type of the function tool call output. Always `function_call_output`.' - ), - ] - output: Annotated[ - Union[Output5, List[Output6]], - Field(description='Text, image, or file output of the function tool call.'), - ] - status: Optional[FunctionCallItemStatus] = None - - -class FunctionShellActionParam(BaseModel): - commands: Annotated[ - List[str], - Field( - description='Ordered shell commands for the execution environment to run.' - ), - ] - timeout_ms: Optional[int] = None - max_output_length: Optional[int] = None - - -class FunctionShellCallItemStatus(BaseModel): - __root__: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], - Field( - description='Status values reported for function shell tool calls.', - title='Function shell call status', - ), - ] - - -class FunctionShellCallItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['FunctionShellCallItemParam'], - Field(description='The type of the item. Always `function_shell_call`.'), - ] - action: Annotated[ - FunctionShellActionParam, - Field( - description='The shell commands and limits that describe how to run the tool call.' - ), - ] - status: Optional[FunctionShellCallItemStatus] = None - - -class FunctionShellCallOutputTimeoutOutcomeParam(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputTimeoutOutcomeParam'], - Field(description='The outcome type. Always `timeout`.'), - ] - - -class FunctionShellCallOutputExitOutcomeParam(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputExitOutcomeParam'], - Field(description='The outcome type. Always `exit`.'), - ] - exit_code: Annotated[ - int, Field(description='The exit code returned by the shell process.') - ] - - -class FunctionShellCallOutputOutcomeParam(BaseModel): - __root__: Annotated[ - Union[ - FunctionShellCallOutputTimeoutOutcomeParam, - FunctionShellCallOutputExitOutcomeParam, - ], - Field( - description='The exit or timeout outcome associated with this chunk.', - discriminator='type', - title='Function shell call outcome', - ), - ] - - -class FunctionShellCallOutputContentParam(BaseModel): - stdout: Annotated[ - str, - Field( - description='Captured stdout output for this chunk of the shell call.', - max_length=10485760, - ), - ] - stderr: Annotated[ - str, - Field( - description='Captured stderr output for this chunk of the shell call.', - max_length=10485760, - ), - ] - outcome: Annotated[ - FunctionShellCallOutputOutcomeParam, - Field(description='The exit or timeout outcome associated with this chunk.'), - ] - - -class FunctionShellCallOutputItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['FunctionShellCallOutputItemParam'], - Field(description='The type of the item. Always `function_shell_call_output`.'), - ] - output: Annotated[ - List[FunctionShellCallOutputContentParam], - Field( - description='Captured chunks of stdout and stderr output, along with their associated outcomes.' - ), - ] - max_output_length: Optional[int] = None - - -class ApplyPatchCallStatusParam(BaseModel): - __root__: Annotated[ - Literal['in_progress', 'completed'], - Field( - description='Status values reported for apply_patch tool calls.', - title='Apply patch call status', - ), - ] - - -class ApplyPatchCreateFileOperationParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchCreateFileOperationParam'], - Field(description='The operation type. Always `create_file`.'), - ] - path: Annotated[ - str, - Field( - description='Path of the file to create relative to the workspace root.', - min_length=1, - ), - ] - diff: Annotated[ - str, - Field( - description='Unified diff content to apply when creating the file.', - max_length=10485760, - ), - ] - - -class ApplyPatchDeleteFileOperationParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchDeleteFileOperationParam'], - Field(description='The operation type. Always `delete_file`.'), - ] - path: Annotated[ - str, - Field( - description='Path of the file to delete relative to the workspace root.', - min_length=1, - ), - ] - - -class ApplyPatchUpdateFileOperationParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchUpdateFileOperationParam'], - Field(description='The operation type. Always `update_file`.'), - ] - path: Annotated[ - str, - Field( - description='Path of the file to update relative to the workspace root.', - min_length=1, - ), - ] - diff: Annotated[ - str, - Field( - description='Unified diff content to apply to the existing file.', - max_length=10485760, - ), - ] - - -class ApplyPatchOperationParam(BaseModel): - __root__: Annotated[ - Union[ - ApplyPatchCreateFileOperationParam, - ApplyPatchDeleteFileOperationParam, - ApplyPatchUpdateFileOperationParam, - ], - Field( - description='One of the create_file, delete_file, or update_file operations supplied to the apply_patch tool.', - discriminator='type', - title='Apply patch operation', - ), - ] - - -class ApplyPatchToolCallItemParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCallItemParam'], - Field(description='The type of the item. Always `apply_patch_call`.'), - ] - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - status: Annotated[ - ApplyPatchCallStatusParam, - Field( - description='The status of the apply patch tool call. One of `in_progress` or `completed`.' - ), - ] - operation: Annotated[ - ApplyPatchOperationParam, - Field( - description='The specific create, delete, or update instruction for the apply_patch tool call.' - ), - ] - - -class ApplyPatchCallOutputStatusParam(BaseModel): - __root__: Annotated[ - Literal['completed', 'failed'], - Field( - description='Outcome values reported for apply_patch tool call outputs.', - title='Apply patch call output status', - ), - ] - - -class Output7(BaseModel): - __root__: Annotated[ - str, - Field( - description='Optional human-readable log text from the apply patch tool (e.g., patch results or errors).', - max_length=10485760, - ), - ] - - -class ApplyPatchToolCallOutputItemParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCallOutputItemParam'], - Field(description='The type of the item. Always `apply_patch_call_output`.'), - ] - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - status: Annotated[ - ApplyPatchCallOutputStatusParam, - Field( - description='The status of the apply patch tool call output. One of `completed` or `failed`.' - ), - ] - output: Optional[Output7] = None - - -class ItemReferenceParam(BaseModel): - type: Literal['ItemReferenceParam'] - id: Annotated[str, Field(description='The ID of the item to reference.')] - - -class ConversationResource(BaseModel): - id: Annotated[str, Field(description='The unique ID of the conversation.')] - object: Annotated[ - Literal['conversation'], - Field(description='The object type, which is always `conversation`.'), - ] - metadata: Annotated[ - Any, - Field( - description='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.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The time at which the conversation was created, measured in seconds since the Unix epoch.' - ), - ] - - -class FunctionTool(BaseModel): - type: Annotated[ - Literal['FunctionTool'], - Field(description='The type of the function tool. Always `function`.'), - ] - name: Annotated[str, Field(description='The name of the function to call.')] - description: Optional[str] = None - parameters: Optional[Dict[str, Any]] - strict: Optional[bool] - - -class RankerVersionType(BaseModel): - __root__: Literal['auto', 'default-2024-11-15'] - - -class HybridSearchOptions(BaseModel): - embedding_weight: Annotated[ - float, - Field( - description='The weight of the embedding in the reciprocal ranking fusion.' - ), - ] - text_weight: Annotated[ - float, - Field(description='The weight of the text in the reciprocal ranking fusion.'), - ] - - -class RankingOptions1(BaseModel): - ranker: Annotated[ - Optional[RankerVersionType], - Field(description='The ranker to use for the file search.'), - ] = None - score_threshold: Annotated[ - Optional[float], - Field( - description='The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results.' - ), - ] = None - hybrid_search: Annotated[ - Optional[HybridSearchOptions], - Field( - description='Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse keyword matches when hybrid search is enabled.' - ), - ] = None - - -class ComputerEnvironment(BaseModel): - __root__: Literal['windows', 'mac', 'linux', 'ubuntu', 'browser'] - - -class ComputerUsePreviewTool(BaseModel): - type: Annotated[ - Literal['ComputerUsePreviewTool'], - Field( - description='The type of the computer use tool. Always `computer_use_preview`.' - ), - ] - environment: Annotated[ - ComputerEnvironment, - Field(description='The type of computer environment to control.'), - ] - display_width: Annotated[ - int, Field(description='The width of the computer display.') - ] - display_height: Annotated[ - int, Field(description='The height of the computer display.') - ] - - -class ContainerMemoryLimit(BaseModel): - __root__: Literal['1g', '4g', '16g', '64g'] - - -class InputFidelity(BaseModel): - __root__: Annotated[ - Literal['high', 'low'], - Field( - description='Control how much effort the model will exert to match the style and features, especially facial features, of input images. This parameter is only supported for `gpt-image-1`. Unsupported for `gpt-image-1-mini`. Supports `high` and `low`. Defaults to `low`.' - ), - ] - - -class LocalShellToolParam(BaseModel): - type: Annotated[ - Literal['LocalShellToolParam'], - Field(description='The type of the local shell tool. Always `local_shell`.'), - ] - - -class FunctionShellToolParam(BaseModel): - type: Annotated[ - Literal['FunctionShellToolParam'], - Field(description='The type of the shell tool. Always `shell`.'), - ] - - -class CustomTextFormatParam(BaseModel): - type: Annotated[ - Literal['CustomTextFormatParam'], - Field(description='Unconstrained text format. Always `text`.'), - ] - - -class GrammarSyntax1(BaseModel): - __root__: Literal['lark', 'regex'] - - -class CustomGrammarFormatParam(BaseModel): - type: Annotated[ - Literal['CustomGrammarFormatParam'], - Field(description='Grammar format. Always `grammar`.'), - ] - syntax: Annotated[ - GrammarSyntax1, - Field( - description='The syntax of the grammar definition. One of `lark` or `regex`.' - ), - ] - definition: Annotated[str, Field(description='The grammar definition.')] - - -class CustomToolParam(BaseModel): - type: Annotated[ - Literal['CustomToolParam'], - Field(description='The type of the custom tool. Always `custom`.'), - ] - name: Annotated[ - str, - Field( - description='The name of the custom tool, used to identify it in tool calls.' - ), - ] - description: Annotated[ - Optional[str], - Field( - description='Optional description of the custom tool, used to provide more context.' - ), - ] = None - format: Annotated[ - Optional[Union[CustomTextFormatParam, CustomGrammarFormatParam]], - Field( - description='The input format for the custom tool. Default is unconstrained text.', - discriminator='type', - ), - ] = None - - -class ApproximateLocation(BaseModel): - type: Annotated[ - Literal['approximate'], - Field(description='The type of location approximation. Always `approximate`.'), - ] - country: Optional[str] = None - region: Optional[str] = None - city: Optional[str] = None - timezone: Optional[str] = None - - -class SearchContextSize(BaseModel): - __root__: Literal['low', 'medium', 'high'] - - -class WebSearchPreviewTool(BaseModel): - type: Annotated[ - Literal['WebSearchPreviewTool'], - Field( - description='The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`.' - ), - ] - user_location: Optional[ApproximateLocation] = None - search_context_size: Annotated[ - Optional[SearchContextSize], - Field( - description='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.' - ), - ] = None - - -class ApplyPatchToolParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolParam'], - Field(description='The type of the tool. Always `apply_patch`.'), - ] - - -class ImageGenInputUsageDetails(BaseModel): - text_tokens: Annotated[ - int, Field(description='The number of text tokens in the input prompt.') - ] - image_tokens: Annotated[ - int, Field(description='The number of image tokens in the input prompt.') - ] - - -class ImageGenUsage(BaseModel): - input_tokens: Annotated[ - int, - Field( - description='The number of tokens (images and text) in the input prompt.' - ), - ] - total_tokens: Annotated[ - int, - Field( - description='The total number of tokens (images and text) used for the image generation.' - ), - ] - output_tokens: Annotated[ - int, Field(description='The number of output tokens generated by the model.') - ] - input_tokens_details: ImageGenInputUsageDetails - - -class SpecificApplyPatchParam(BaseModel): - type: Annotated[ - Literal['SpecificApplyPatchParam'], - Field(description='The tool to call. Always `apply_patch`.'), - ] - - -class SpecificFunctionShellParam(BaseModel): - type: Annotated[ - Literal['SpecificFunctionShellParam'], - Field(description='The tool to call. Always `shell`.'), - ] - - -class ConversationParam2(BaseModel): - id: Annotated[ - str, Field(description='The unique ID of the conversation.', example='conv_123') - ] - - -class Conversation2(BaseModel): - id: Annotated[str, Field(description='The unique ID of the conversation.')] - - -class UpdateConversationBody(BaseModel): - metadata: Annotated[ - Metadata, - Field( - description='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.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.' - ), - ] - - -class DeletedConversationResource(BaseModel): - object: Literal['conversation.deleted'] - deleted: bool - id: str - - -class OrderEnum(BaseModel): - __root__: Literal['asc', 'desc'] - - -class VideoModel(BaseModel): - __root__: Literal['sora-2', 'sora-2-pro'] - - -class VideoStatus(BaseModel): - __root__: Literal['queued', 'in_progress', 'completed', 'failed'] - - -class VideoSize(BaseModel): - __root__: Literal['720x1280', '1280x720', '1024x1792', '1792x1024'] - - -class VideoSeconds(BaseModel): - __root__: Literal['4', '8', '12'] - - -class Error21(BaseModel): - code: str - message: str - - -class VideoResource(BaseModel): - id: Annotated[str, Field(description='Unique identifier for the video job.')] - object: Annotated[ - Literal['video'], Field(description='The object type, which is always `video`.') - ] - model: Annotated[ - VideoModel, - Field(description='The video generation model that produced the job.'), - ] - status: Annotated[ - VideoStatus, Field(description='Current lifecycle status of the video job.') - ] - progress: Annotated[ - int, - Field(description='Approximate completion percentage for the generation task.'), - ] - created_at: Annotated[ - int, Field(description='Unix timestamp (seconds) for when the job was created.') - ] - completed_at: Optional[int] - expires_at: Optional[int] - prompt: Optional[str] - size: Annotated[ - VideoSize, Field(description='The resolution of the generated video.') - ] - seconds: Annotated[ - VideoSeconds, Field(description='Duration of the generated clip in seconds.') - ] - remixed_from_video_id: Optional[str] - error: Optional[Error21] - - -class VideoListResource(BaseModel): - object: Annotated[ - str, - Field(const=True, description='The type of object returned, must be `list`.'), - ] = 'list' - data: Annotated[List[VideoResource], Field(description='A list of items')] - first_id: Optional[str] - last_id: Optional[str] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - - -class CreateVideoBody(BaseModel): - model: Annotated[ - Optional[VideoModel], - Field(description='The video generation model to use. Defaults to `sora-2`.'), - ] = None - prompt: Annotated[ - str, - Field( - description='Text prompt that describes the video to generate.', - max_length=32000, - min_length=1, - ), - ] - input_reference: Annotated[ - Optional[bytes], - Field(description='Optional image reference that guides generation.'), - ] = None - seconds: Annotated[ - Optional[VideoSeconds], - Field(description='Clip duration in seconds. Defaults to 4 seconds.'), - ] = None - size: Annotated[ - Optional[VideoSize], - Field( - description='Output resolution formatted as width x height. Defaults to 720x1280.' - ), - ] = None - - -class DeletedVideoResource(BaseModel): - object: Annotated[ - Literal['video.deleted'], - Field(description='The object type that signals the deletion response.'), - ] - deleted: Annotated[ - bool, Field(description='Indicates that the video resource was deleted.') - ] - id: Annotated[str, Field(description='Identifier of the deleted video.')] - - -class VideoContentVariant(BaseModel): - __root__: Literal['video', 'thumbnail', 'spritesheet'] - - -class CreateVideoRemixBody(BaseModel): - prompt: Annotated[ - str, - Field( - description='Updated text prompt that directs the remix generation.', - max_length=32000, - min_length=1, - ), - ] - - -class TruncationEnum(BaseModel): - __root__: Literal['auto', 'disabled'] - - -class Input10(BaseModel): - __root__: Annotated[ - str, - Field( - description='A text input to the model, equivalent to a text input with the `user` role.', - max_length=10485760, - ), - ] - - -class TokenCountsResource(BaseModel): - object: Literal['response.input_tokens'] - input_tokens: int - - -class ChatkitWorkflowTracing(BaseModel): - enabled: Annotated[bool, Field(description='Indicates whether tracing is enabled.')] - - -class ChatkitWorkflow(BaseModel): - id: Annotated[ - str, Field(description='Identifier of the workflow backing the session.') - ] - version: Optional[str] - state_variables: Optional[Dict[str, Union[str, int, bool, float]]] - tracing: Annotated[ - ChatkitWorkflowTracing, - Field(description='Tracing settings applied to the workflow.'), - ] - - -class ChatSessionRateLimits(BaseModel): - max_requests_per_1_minute: Annotated[ - int, Field(description='Maximum allowed requests per one-minute window.') - ] - - -class ChatSessionStatus(BaseModel): - __root__: Literal['active', 'expired', 'cancelled'] - - -class ChatSessionAutomaticThreadTitling(BaseModel): - enabled: Annotated[ - bool, Field(description='Whether automatic thread titling is enabled.') - ] - - -class ChatSessionFileUpload(BaseModel): - enabled: Annotated[ - bool, Field(description='Indicates if uploads are enabled for the session.') - ] - max_file_size: Optional[int] - max_files: Optional[int] - - -class ChatSessionHistory(BaseModel): - enabled: Annotated[ - bool, - Field(description='Indicates if chat history is persisted for the session.'), - ] - recent_threads: Optional[int] - - -class ChatSessionChatkitConfiguration(BaseModel): - automatic_thread_titling: Annotated[ - ChatSessionAutomaticThreadTitling, - Field(description='Automatic thread titling preferences.'), - ] - file_upload: Annotated[ - ChatSessionFileUpload, Field(description='Upload settings for the session.') - ] - history: Annotated[ - ChatSessionHistory, Field(description='History retention configuration.') - ] - - -class ChatSessionResource(BaseModel): - id: Annotated[str, Field(description='Identifier for the ChatKit session.')] - object: Annotated[ - Literal['chatkit.session'], - Field(description='Type discriminator that is always `chatkit.session`.'), - ] - expires_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the session expires.'), - ] - client_secret: Annotated[ - str, - Field( - description='Ephemeral client secret that authenticates session requests.' - ), - ] - workflow: Annotated[ - ChatkitWorkflow, Field(description='Workflow metadata for the session.') - ] - user: Annotated[ - str, Field(description='User identifier associated with the session.') - ] - rate_limits: Annotated[ - ChatSessionRateLimits, Field(description='Resolved rate limit values.') - ] - max_requests_per_1_minute: Annotated[ - int, Field(description='Convenience copy of the per-minute request limit.') - ] - status: Annotated[ - ChatSessionStatus, Field(description='Current lifecycle state of the session.') - ] - chatkit_configuration: Annotated[ - ChatSessionChatkitConfiguration, - Field(description='Resolved ChatKit feature configuration for the session.'), - ] - - -class WorkflowTracingParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field( - description='Whether tracing is enabled during the session. Defaults to true.' - ), - ] = None - - -class StateVariables(BaseModel): - __root__: Annotated[str, Field(max_length=10485760)] - - -class WorkflowParam(BaseModel): - id: Annotated[ - str, Field(description='Identifier for the workflow invoked by the session.') - ] - version: Annotated[ - Optional[str], - Field( - description='Specific workflow version to run. Defaults to the latest deployed version.' - ), - ] = None - state_variables: Annotated[ - Optional[Dict[str, Union[StateVariables, int, bool, float]]], - Field( - description='State variables forwarded to the workflow. Keys may be up to 64 characters, values must be primitive types, and the map defaults to an empty object.' - ), - ] = None - tracing: Annotated[ - Optional[WorkflowTracingParam], - Field( - description='Optional tracing overrides for the workflow invocation. When omitted, tracing is enabled by default.' - ), - ] = None - - -class ExpiresAfterParam(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='Base timestamp used to calculate expiration. Currently fixed to `created_at`.' - ), - ] - seconds: Annotated[ - int, - Field( - description='Number of seconds after the anchor when the session expires.', - ge=1, - le=600, - ), - ] - - -class RateLimitsParam(BaseModel): - max_requests_per_1_minute: Annotated[ - Optional[int], - Field( - description='Maximum number of requests allowed per minute for the session. Defaults to 10.', - ge=1, - ), - ] = None - - -class AutomaticThreadTitlingParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field( - description='Enable automatic thread title generation. Defaults to true.' - ), - ] = None - - -class FileUploadParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field(description='Enable uploads for this session. Defaults to false.'), - ] = None - max_file_size: Annotated[ - Optional[int], - Field( - description='Maximum size in megabytes for each uploaded file. Defaults to 512 MB, which is the maximum allowable size.', - ge=1, - le=512, - ), - ] = None - max_files: Annotated[ - Optional[int], - Field( - description='Maximum number of files that can be uploaded to the session. Defaults to 10.', - ge=1, - ), - ] = None - - -class HistoryParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field( - description='Enables chat users to access previous ChatKit threads. Defaults to true.' - ), - ] = None - recent_threads: Annotated[ - Optional[int], - Field( - description='Number of recent ChatKit threads users have access to. Defaults to unlimited when unset.', - ge=1, - ), - ] = None - - -class ChatkitConfigurationParam(BaseModel): - automatic_thread_titling: Annotated[ - Optional[AutomaticThreadTitlingParam], - Field( - description='Configuration for automatic thread titling. When omitted, automatic thread titling is enabled by default.' - ), - ] = None - file_upload: Annotated[ - Optional[FileUploadParam], - Field( - description='Configuration for upload enablement and limits. When omitted, uploads are disabled by default (max_files 10, max_file_size 512 MB).' - ), - ] = None - history: Annotated[ - Optional[HistoryParam], - Field( - description='Configuration for chat history retention. When omitted, history is enabled by default with no limit on recent_threads (null).' - ), - ] = None - - -class CreateChatSessionBody(BaseModel): - workflow: Annotated[ - WorkflowParam, Field(description='Workflow that powers the session.') - ] - user: Annotated[ - str, - Field( - description='A free-form string that identifies your end user; ensures this Session can access other objects that have the same `user` scope.', - min_length=1, - ), - ] - expires_after: Annotated[ - Optional[ExpiresAfterParam], - Field( - description='Optional override for session expiration timing in seconds from creation. Defaults to 10 minutes.' - ), - ] = None - rate_limits: Annotated[ - Optional[RateLimitsParam], - Field( - description='Optional override for per-minute request limits. When omitted, defaults to 10.' - ), - ] = None - chatkit_configuration: Annotated[ - Optional[ChatkitConfigurationParam], - Field( - description='Optional overrides for ChatKit runtime configuration features' - ), - ] = None - - -class UserMessageInputText(BaseModel): - type: Annotated[ - Literal['UserMessageInputText'], - Field(description='Type discriminator that is always `input_text`.'), - ] - text: Annotated[str, Field(description='Plain-text content supplied by the user.')] - - -class UserMessageQuotedText(BaseModel): - type: Annotated[ - Literal['UserMessageQuotedText'], - Field(description='Type discriminator that is always `quoted_text`.'), - ] - text: Annotated[str, Field(description='Quoted text content.')] - - -class AttachmentType(BaseModel): - __root__: Literal['image', 'file'] - - -class Attachment2(BaseModel): - type: Annotated[AttachmentType, Field(description='Attachment discriminator.')] - id: Annotated[str, Field(description='Identifier for the attachment.')] - name: Annotated[str, Field(description='Original display name for the attachment.')] - mime_type: Annotated[str, Field(description='MIME type of the attachment.')] - preview_url: Optional[str] - - -class ToolChoice(BaseModel): - id: Annotated[str, Field(description='Identifier of the requested tool.')] - - -class InferenceOptions(BaseModel): - tool_choice: Optional[ToolChoice] - model: Optional[str] - - -class Content11(BaseModel): - __root__: Annotated[ - Union[UserMessageInputText, UserMessageQuotedText], - Field( - description='Content blocks that comprise a user message.', - discriminator='type', - ), - ] - - -class UserMessageItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Literal['UserMessageItem'] - content: Annotated[ - List[Content11], - Field(description='Ordered content elements supplied by the user.'), - ] - attachments: Annotated[ - List[Attachment2], - Field( - description='Attachments associated with the user message. Defaults to an empty list.' - ), - ] - inference_options: Optional[InferenceOptions] - - -class FileAnnotationSource(BaseModel): - type: Annotated[ - Literal['file'], Field(description='Type discriminator that is always `file`.') - ] - filename: Annotated[ - str, Field(description='Filename referenced by the annotation.') - ] - - -class FileAnnotation(BaseModel): - type: Annotated[ - Literal['FileAnnotation'], - Field( - description='Type discriminator that is always `file` for this annotation.' - ), - ] - source: Annotated[ - FileAnnotationSource, - Field(description='File attachment referenced by the annotation.'), - ] - - -class UrlAnnotationSource(BaseModel): - type: Annotated[ - Literal['url'], Field(description='Type discriminator that is always `url`.') - ] - url: Annotated[str, Field(description='URL referenced by the annotation.')] - - -class UrlAnnotation(BaseModel): - type: Annotated[ - Literal['UrlAnnotation'], - Field( - description='Type discriminator that is always `url` for this annotation.' - ), - ] - source: Annotated[ - UrlAnnotationSource, Field(description='URL referenced by the annotation.') - ] - - -class Annotations(BaseModel): - __root__: Annotated[ - Union[FileAnnotation, UrlAnnotation], - Field( - description='Annotation object describing a cited source.', - discriminator='type', - ), - ] - - -class ResponseOutputText(BaseModel): - type: Annotated[ - Literal['output_text'], - Field(description='Type discriminator that is always `output_text`.'), - ] - text: Annotated[str, Field(description='Assistant generated text.')] - annotations: Annotated[ - List[Annotations], - Field(description='Ordered list of annotations attached to the response text.'), - ] - - -class AssistantMessageItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['AssistantMessageItem'], - Field( - description='Type discriminator that is always `chatkit.assistant_message`.' - ), - ] - content: Annotated[ - List[ResponseOutputText], - Field(description='Ordered assistant response segments.'), - ] - - -class WidgetMessageItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['WidgetMessageItem'], - Field(description='Type discriminator that is always `chatkit.widget`.'), - ] - widget: Annotated[ - str, Field(description='Serialized widget payload rendered in the UI.') - ] - - -class ClientToolCallStatus(BaseModel): - __root__: Literal['in_progress', 'completed'] - - -class ClientToolCallItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['ClientToolCallItem'], - Field( - description='Type discriminator that is always `chatkit.client_tool_call`.' - ), - ] - status: Annotated[ - ClientToolCallStatus, Field(description='Execution status for the tool call.') - ] - call_id: Annotated[str, Field(description='Identifier for the client tool call.')] - name: Annotated[str, Field(description='Tool name that was invoked.')] - arguments: Annotated[ - str, Field(description='JSON-encoded arguments that were sent to the tool.') - ] - output: Optional[str] - - -class TaskType(BaseModel): - __root__: Literal['custom', 'thought'] - - -class TaskItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['TaskItem'], - Field(description='Type discriminator that is always `chatkit.task`.'), - ] - task_type: Annotated[TaskType, Field(description='Subtype for the task.')] - heading: Optional[str] - summary: Optional[str] - - -class TaskGroupTask(BaseModel): - type: Annotated[TaskType, Field(description='Subtype for the grouped task.')] - heading: Optional[str] - summary: Optional[str] - - -class TaskGroupItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['TaskGroupItem'], - Field(description='Type discriminator that is always `chatkit.task_group`.'), - ] - tasks: Annotated[ - List[TaskGroupTask], Field(description='Tasks included in the group.') - ] - - -class ThreadItem(BaseModel): - __root__: Annotated[ - Union[ - UserMessageItem, - AssistantMessageItem, - WidgetMessageItem, - ClientToolCallItem, - TaskItem, - TaskGroupItem, - ], - Field(discriminator='type', title='The thread item'), - ] - - -class ThreadItemListResource(BaseModel): - object: Annotated[ - str, - Field(const=True, description='The type of object returned, must be `list`.'), - ] = 'list' - data: Annotated[List[ThreadItem], Field(description='A list of items')] - first_id: Optional[str] - last_id: Optional[str] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - - -class ActiveStatus(BaseModel): - type: Annotated[ - Literal['ActiveStatus'], - Field(description='Status discriminator that is always `active`.'), - ] - - -class LockedStatus(BaseModel): - type: Annotated[ - Literal['LockedStatus'], - Field(description='Status discriminator that is always `locked`.'), - ] - reason: Optional[str] - - -class ClosedStatus(BaseModel): - type: Annotated[ - Literal['ClosedStatus'], - Field(description='Status discriminator that is always `closed`.'), - ] - reason: Optional[str] - - -class ThreadResource(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread.')] - object: Annotated[ - Literal['chatkit.thread'], - Field(description='Type discriminator that is always `chatkit.thread`.'), - ] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) for when the thread was created.' - ), - ] - title: Optional[str] - status: Annotated[ - Union[ActiveStatus, LockedStatus, ClosedStatus], - Field( - description='Current status for the thread. Defaults to `active` for newly created threads.', - discriminator='type', - ), - ] - user: Annotated[ - str, - Field( - description='Free-form string that identifies your end user who owns the thread.' - ), - ] - - -class DeletedThreadResource(BaseModel): - id: Annotated[str, Field(description='Identifier of the deleted thread.')] - object: Annotated[ - Literal['chatkit.thread.deleted'], - Field( - description='Type discriminator that is always `chatkit.thread.deleted`.' - ), - ] - deleted: Annotated[ - bool, Field(description='Indicates that the thread has been deleted.') - ] - - -class ThreadListResource(BaseModel): - object: Annotated[ - str, - Field(const=True, description='The type of object returned, must be `list`.'), - ] = 'list' - data: Annotated[List[ThreadResource], Field(description='A list of items')] - first_id: Optional[str] - last_id: Optional[str] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - - -class RealtimeConnectParams(BaseModel): - model: Optional[str] = None - call_id: Optional[str] = None - - -class ImageUrl4(BaseModel): - url: Annotated[ - AnyUrl, - Field( - description='Either a URL of the image or the base64 encoded image data.', - example='https://example.com/image.jpg', - ), - ] - - -class ModerationImageURLInput(BaseModel): - type: Annotated[ - Literal['ModerationImageURLInput'], Field(description='Always `image_url`.') - ] - image_url: Annotated[ - ImageUrl4, - Field( - description='Contains either an image URL or a data URL for a base64 encoded image.' - ), - ] - - -class ModerationTextInput(BaseModel): - type: Annotated[Literal['ModerationTextInput'], Field(description='Always `text`.')] - text: Annotated[ - str, - Field( - description='A string of text to classify.', example='I want to kill them' - ), - ] - - -class ComparisonFilterValueItems(BaseModel): - __root__: Union[str, float] - - -class ChunkingStrategyResponse(BaseModel): - __root__: Annotated[ - Union[StaticChunkingStrategyResponseParam, OtherChunkingStrategyResponseParam], - Field(description='The strategy used to chunk the file.', discriminator='type'), - ] - - -class FilePurpose(BaseModel): - __root__: Annotated[ - Literal['assistants', 'batch', 'fine-tune', 'vision', 'user_data', 'evals'], - Field( - description='The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets\n' - ), - ] - - -class BatchError(BaseModel): - code: Annotated[ - Optional[str], Field(description='An error code identifying the error type.') - ] = None - message: Annotated[ - Optional[str], - Field( - description='A human-readable message providing more details about the error.' - ), - ] = None - param: Optional[str] = None - line: Optional[int] = None - - -class BatchRequestCounts(BaseModel): - total: Annotated[int, Field(description='Total number of requests in the batch.')] - completed: Annotated[ - int, - Field(description='Number of requests that have been completed successfully.'), - ] - failed: Annotated[int, Field(description='Number of requests that have failed.')] - - -class TextAnnotationDelta(BaseModel): - __root__: Annotated[ - Union[ - MessageDeltaContentTextAnnotationsFileCitationObject, - MessageDeltaContentTextAnnotationsFilePathObject, - ], - Field(discriminator='type'), - ] - - -class TextAnnotation(BaseModel): - __root__: Annotated[ - Union[ - MessageContentTextAnnotationsFileCitationObject, - MessageContentTextAnnotationsFilePathObject, - ], - Field(discriminator='type'), - ] - - -class ChatModel(BaseModel): - __root__: Literal[ - 'gpt-5.1', - 'gpt-5.1-2025-11-13', - 'gpt-5.1-codex', - 'gpt-5.1-mini', - 'gpt-5.1-chat-latest', - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-5-chat-latest', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'o4-mini', - 'o4-mini-2025-04-16', - 'o3', - 'o3-2025-04-16', - 'o3-mini', - 'o3-mini-2025-01-31', - 'o1', - 'o1-2024-12-17', - 'o1-preview', - 'o1-preview-2024-09-12', - 'o1-mini', - 'o1-mini-2024-09-12', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-audio-preview', - 'gpt-4o-audio-preview-2024-10-01', - 'gpt-4o-audio-preview-2024-12-17', - 'gpt-4o-audio-preview-2025-06-03', - 'gpt-4o-mini-audio-preview', - 'gpt-4o-mini-audio-preview-2024-12-17', - 'gpt-4o-search-preview', - 'gpt-4o-mini-search-preview', - 'gpt-4o-search-preview-2025-03-11', - 'gpt-4o-mini-search-preview-2025-03-11', - 'chatgpt-4o-latest', - 'codex-mini-latest', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0301', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ] - - -class Summary(BaseModel): - type: Annotated[ - Literal['summary_text'], - Field(description='The type of the object. Always `summary_text`.'), - ] - text: Annotated[ - str, - Field(description='A summary of the reasoning output from the model so far.'), - ] - - -class FileSearch11(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] = None - - -class ToolResources7(BaseModel): - code_interpreter: Optional[CodeInterpreter5] = None - file_search: Optional[FileSearch11] = None - - -class SubmitToolOutputsRunRequestWithoutStream(BaseModel): - class Config: - extra = Extra.forbid - - tool_outputs: Annotated[ - List[ToolOutput], - Field(description='A list of tools for which the outputs are being submitted.'), - ] - - -class RunStatus(BaseModel): - __root__: Annotated[ - Literal[ - 'queued', - 'in_progress', - 'requires_action', - 'cancelling', - 'cancelled', - 'failed', - 'completed', - 'incomplete', - 'expired', - ], - Field( - description='The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`.' - ), - ] - - -class CodeInterpreterContainerAuto(BaseModel): - type: Annotated[Literal['auto'], Field(description='Always `auto`.')] - file_ids: Annotated[ - Optional[List[str]], - Field( - description='An optional list of uploaded files to make available to your code.', - max_items=50, - ), - ] = None - memory_limit: Optional[ContainerMemoryLimit] = None - - -class FileSearch1(BaseModel): - max_num_results: Annotated[ - Optional[int], - Field( - description='The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n\nNote that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n', - ge=1, - le=50, - ), - ] = None - ranking_options: Optional[FileSearchRankingOptions] = None - - -class AssistantToolsFileSearch(BaseModel): - type: Annotated[ - Literal['AssistantToolsFileSearch'], - Field(description='The type of tool being defined: `file_search`'), - ] - file_search: Annotated[ - Optional[FileSearch1], Field(description='Overrides for the file search tool.') - ] = None - - -class AssistantsApiToolChoiceOption(BaseModel): - __root__: Annotated[ - Union[Literal['none', 'auto', 'required'], AssistantsNamedToolChoice], - Field( - description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n' - ), - ] - - -class AuditLogActorApiKey(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking id of the API key.') - ] = None - type: Annotated[ - Optional[Literal['user', 'service_account']], - Field( - description='The type of API key. Can be either `user` or `service_account`.' - ), - ] = None - user: Optional[AuditLogActorUser] = None - service_account: Optional[AuditLogActorServiceAccount] = None - - -class AuditLogActorSession(BaseModel): - user: Optional[AuditLogActorUser] = None - ip_address: Annotated[ - Optional[str], - Field(description='The IP address from which the action was performed.'), - ] = None - - -class Errors(BaseModel): - object: Annotated[ - Optional[str], Field(description='The object type, which is always `list`.') - ] = None - data: Optional[List[BatchError]] = None - - -class Batch(BaseModel): - id: str - object: Annotated[ - Literal['batch'], Field(description='The object type, which is always `batch`.') - ] - endpoint: Annotated[ - str, Field(description='The OpenAI API endpoint used by the batch.') - ] - model: Annotated[ - Optional[str], - Field( - description='Model ID used to process the batch, like `gpt-5-2025-08-07`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model\nguide](https://platform.openai.com/docs/models) to browse and compare available models.\n' - ), - ] = None - errors: Optional[Errors] = None - input_file_id: Annotated[ - str, Field(description='The ID of the input file for the batch.') - ] - completion_window: Annotated[ - str, - Field(description='The time frame within which the batch should be processed.'), - ] - status: Annotated[ - Literal[ - 'validating', - 'failed', - 'in_progress', - 'finalizing', - 'completed', - 'expired', - 'cancelling', - 'cancelled', - ], - Field(description='The current status of the batch.'), - ] - output_file_id: Annotated[ - Optional[str], - Field( - description='The ID of the file containing the outputs of successfully executed requests.' - ), - ] = None - error_file_id: Annotated[ - Optional[str], - Field( - description='The ID of the file containing the outputs of requests with errors.' - ), - ] = None - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the batch was created.' - ), - ] - in_progress_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch started processing.' - ), - ] = None - expires_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch will expire.' - ), - ] = None - finalizing_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch started finalizing.' - ), - ] = None - completed_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch was completed.' - ), - ] = None - failed_at: Annotated[ - Optional[int], - Field(description='The Unix timestamp (in seconds) for when the batch failed.'), - ] = None - expired_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch expired.' - ), - ] = None - cancelling_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch started cancelling.' - ), - ] = None - cancelled_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch was cancelled.' - ), - ] = None - request_counts: Optional[BatchRequestCounts] = None - usage: Annotated[ - Optional[Usage], - Field( - description='Represents token usage details including input tokens, output tokens, a\nbreakdown of output tokens, and the total tokens used. Only populated on\nbatches created after September 7, 2025.\n' - ), - ] = None - metadata: Optional[Metadata] = None - - -class ChatCompletionFunctions(BaseModel): - description: Annotated[ - Optional[str], - Field( - description='A description of what the function does, used by the model to choose when and how to call the function.' - ), - ] = None - name: Annotated[ - str, - Field( - description='The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.' - ), - ] - parameters: Optional[FunctionParameters] = None - - -class Datum(ChatCompletionResponseMessage): - id: Annotated[str, Field(description='The identifier of the chat message.')] - content_parts: Optional[ - List[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartImage, - ] - ] - ] = None - - -class ChatCompletionMessageList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[ - List[Datum], Field(description='An array of chat completion message objects.\n') - ] - first_id: Annotated[ - str, - Field( - description='The identifier of the first chat message in the data array.' - ), - ] - last_id: Annotated[ - str, - Field(description='The identifier of the last chat message in the data array.'), - ] - has_more: Annotated[ - bool, - Field(description='Indicates whether there are more chat messages available.'), - ] - - -class ChatCompletionRequestAssistantMessageContentPart(BaseModel): - __root__: Annotated[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartRefusal, - ], - Field(discriminator='type'), - ] - - -class Content1(BaseModel): - __root__: Annotated[ - List[ChatCompletionRequestMessageContentPartText], - Field( - description='An array of content parts with a defined type. For developer messages, only type `text` is supported.', - min_items=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestDeveloperMessage(BaseModel): - content: Annotated[ - Union[str, Content1], - Field(description='The contents of the developer message.'), - ] - role: Annotated[ - Literal['ChatCompletionRequestDeveloperMessage'], - Field(description='The role of the messages author, in this case `developer`.'), - ] - name: Annotated[ - Optional[str], - Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' - ), - ] = None - - -class Content2(BaseModel): - __root__: Annotated[ - List[ChatCompletionRequestSystemMessageContentPart], - Field( - description='An array of content parts with a defined type. For system messages, only type `text` is supported.', - min_items=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestSystemMessage(BaseModel): - content: Annotated[ - Union[str, Content2], Field(description='The contents of the system message.') - ] - role: Annotated[ - Literal['ChatCompletionRequestSystemMessage'], - Field(description='The role of the messages author, in this case `system`.'), - ] - name: Annotated[ - Optional[str], - Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' - ), - ] = None - - -class Content3(BaseModel): - __root__: Annotated[ - List[ChatCompletionRequestToolMessageContentPart], - Field( - description='An array of content parts with a defined type. For tool messages, only type `text` is supported.', - min_items=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestToolMessage(BaseModel): - role: Annotated[ - Literal['ChatCompletionRequestToolMessage'], - Field(description='The role of the messages author, in this case `tool`.'), - ] - content: Annotated[ - Union[str, Content3], Field(description='The contents of the tool message.') - ] - tool_call_id: Annotated[ - str, Field(description='Tool call that this message is responding to.') - ] - - -class Content4(BaseModel): - __root__: Annotated[ - List[ChatCompletionRequestUserMessageContentPart], - Field( - description='An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text, image, or audio inputs.', - min_items=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestUserMessage(BaseModel): - content: Annotated[ - Union[str, Content4], Field(description='The contents of the user message.\n') - ] - role: Annotated[ - Literal['ChatCompletionRequestUserMessage'], - Field(description='The role of the messages author, in this case `user`.'), - ] - name: Annotated[ - Optional[str], - Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' - ), - ] = None - - -class ChunkingStrategyRequestParam(BaseModel): - __root__: Annotated[ - Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty.', - discriminator='type', - ), - ] - - -class CodeInterpreterTool(BaseModel): - type: Annotated[ - Literal['CodeInterpreterTool'], - Field( - description='The type of the code interpreter tool. Always `code_interpreter`.\n' - ), - ] - container: Annotated[ - Union[str, CodeInterpreterContainerAuto], - Field( - description='The code interpreter container. Can be a container ID or an object that\nspecifies uploaded file IDs to make available to your code.\n' - ), - ] - - -class Outputs(BaseModel): - __root__: Annotated[ - Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage], - Field(discriminator='type'), - ] - - -class CodeInterpreterToolCall(BaseModel): - type: Annotated[ - Literal['CodeInterpreterToolCall'], - Field( - description='The type of the code interpreter tool call. Always `code_interpreter_call`.\n' - ), - ] - id: Annotated[ - str, Field(description='The unique ID of the code interpreter tool call.\n') - ] - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete', 'interpreting', 'failed'], - Field( - description='The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n' - ), - ] - container_id: Annotated[ - str, Field(description='The ID of the container used to run the code.\n') - ] - code: Optional[str] - outputs: Optional[List[Outputs]] - - -class ComparisonFilter(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['ComparisonFilter'], - Field( - description='Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`.\n- `eq`: equals\n- `ne`: not equal\n- `gt`: greater than\n- `gte`: greater than or equal\n- `lt`: less than\n- `lte`: less than or equal\n- `in`: in\n- `nin`: not in\n' - ), - ] - key: Annotated[str, Field(description='The key to compare against the value.')] - value: Annotated[ - Union[str, float, bool, List[ComparisonFilterValueItems]], - Field( - description='The value to compare against the attribute key; supports string, number, or boolean types.' - ), - ] - - -class Filters(BaseModel): - __root__: Annotated[Union[ComparisonFilter, Any], Field(discriminator='type')] - - -class CompoundFilter(BaseModel): - class Config: - extra = Extra.forbid - - type: Annotated[ - Literal['and', 'or'], Field(description='Type of operation: `and` or `or`.') - ] - filters: Annotated[ - List[Filters], - Field( - description='Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`.' - ), - ] - - -class ComputerToolCallOutput(BaseModel): - type: Annotated[ - Literal['computer_call_output'], - Field( - description='The type of the computer tool call output. Always `computer_call_output`.\n' - ), - ] - id: Annotated[ - Optional[str], Field(description='The ID of the computer tool call output.\n') - ] = None - call_id: Annotated[ - str, - Field( - description='The ID of the computer tool call that produced the output.\n' - ), - ] - acknowledged_safety_checks: Annotated[ - Optional[List[ComputerCallSafetyCheckParam]], - Field( - description='The safety checks reported by the API that have been acknowledged by the\ndeveloper.\n' - ), - ] = None - output: ComputerScreenshotImage - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n' - ), - ] = None - - -class ComputerToolCallOutputResource(ComputerToolCallOutput): - id: Annotated[ - str, Field(description='The unique ID of the computer call tool output.\n') - ] - type: Literal['ComputerToolCallOutputResource'] - - -class ContainerFileListResource(BaseModel): - object: Annotated[ - str, - Field(const=True, description="The type of object returned, must be 'list'."), - ] = 'list' - data: Annotated[ - List[ContainerFileResource], Field(description='A list of container files.') - ] - first_id: Annotated[str, Field(description='The ID of the first file in the list.')] - last_id: Annotated[str, Field(description='The ID of the last file in the list.')] - has_more: Annotated[ - bool, Field(description='Whether there are more files available.') - ] - - -class ContainerListResource(BaseModel): - object: Annotated[ - str, - Field(const=True, description="The type of object returned, must be 'list'."), - ] = 'list' - data: Annotated[List[ContainerResource], Field(description='A list of containers.')] - first_id: Annotated[ - str, Field(description='The ID of the first container in the list.') - ] - last_id: Annotated[ - str, Field(description='The ID of the last container in the list.') - ] - has_more: Annotated[ - bool, Field(description='Whether there are more containers available.') - ] - - -class Conversation(ConversationResource): - pass - - -class ConversationParam(BaseModel): - __root__: Annotated[ - Union[str, ConversationParam2], - Field( - description='The conversation that this response belongs to. Items from this conversation are prepended to `input_items` for this response request.\nInput items and output items from this response are automatically added to this conversation after this response completes.\n' - ), - ] - - -class VectorStore(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_items=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy, ChunkingStrategy1]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch2(BaseModel): - vector_store_ids: Annotated[ - List[str], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] - vector_stores: Annotated[ - Optional[List[VectorStore]], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] = None - - -class VectorStore1(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_items=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy2, ChunkingStrategy3]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch3(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] = None - vector_stores: Annotated[ - List[VectorStore1], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_items=1, - ), - ] - - -class ToolResources1(BaseModel): - code_interpreter: Optional[CodeInterpreter1] = None - file_search: Optional[Union[FileSearch2, FileSearch3]] = None - - -class UserLocation(BaseModel): - type: Annotated[ - Literal['approximate'], - Field( - description='The type of location approximation. Always `approximate`.\n' - ), - ] - approximate: WebSearchLocation - - -class WebSearchOptions(BaseModel): - user_location: Annotated[ - Optional[UserLocation], - Field(description='Approximate location parameters for the search.\n'), - ] = None - search_context_size: Annotated[Optional[WebSearchContextSize], Field()] = 'medium' - - -class Audio2(BaseModel): - voice: Annotated[ - VoiceIdsShared, - Field( - description='The voice the model uses to respond. Supported voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`.\n' - ), - ] - format: Annotated[ - Literal['wav', 'aac', 'mp3', 'flac', 'opus', 'pcm16'], - Field( - description='Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`,\n`opus`, or `pcm16`.\n' - ), - ] - - -class CreateChatCompletionResponse(BaseModel): - id: Annotated[ - str, Field(description='A unique identifier for the chat completion.') - ] - choices: Annotated[ - List[Choice], - Field( - description='A list of chat completion choices. Can be more than one if `n` is greater than 1.' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the chat completion was created.' - ), - ] - model: Annotated[str, Field(description='The model used for the chat completion.')] - service_tier: Optional[ServiceTier] = None - system_fingerprint: Annotated[ - Optional[str], - Field( - description='This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n' - ), - ] = None - object: Annotated[ - Literal['chat.completion'], - Field(description='The object type, which is always `chat.completion`.'), - ] - usage: Optional[CompletionUsage] = None - - -class CreateChatCompletionStreamResponse(BaseModel): - id: Annotated[ - str, - Field( - description='A unique identifier for the chat completion. Each chunk has the same ID.' - ), - ] - choices: Annotated[ - List[Choice1], - Field( - description='A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the\nlast chunk if you set `stream_options: {"include_usage": true}`.\n' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.' - ), - ] - model: Annotated[str, Field(description='The model to generate the completion.')] - service_tier: Optional[ServiceTier] = None - system_fingerprint: Annotated[ - Optional[str], - Field( - description='This fingerprint represents the backend configuration that the model runs with.\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n' - ), - ] = None - object: Annotated[ - Literal['chat.completion.chunk'], - Field(description='The object type, which is always `chat.completion.chunk`.'), - ] - usage: Annotated[ - Optional[CompletionUsage], - Field( - description='An optional field that will only be present when you set\n`stream_options: {"include_usage": true}` in your request. When present, it\ncontains a null value **except for the last chunk** which contains the\ntoken usage statistics for the entire request.\n\n**NOTE:** If the stream is interrupted or cancelled, you may not\nreceive the final usage chunk which contains the total token usage for\nthe request.\n' - ), - ] = None - - -class CreateCompletionRequest(BaseModel): - model: Annotated[ - Union[str, Literal['gpt-3.5-turbo-instruct', 'davinci-002', 'babbage-002']], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n' - ), - ] - prompt: Annotated[ - Optional[Union[Optional[str], List[str], Prompt, Prompt1]], - Field( - description='The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n' - ), - ] - best_of: Annotated[ - Optional[int], - Field( - description='Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed.\n\nWhen used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n', - ge=0, - le=20, - ), - ] = 1 - echo: Annotated[ - Optional[bool], - Field(description='Echo back the prompt in addition to the completion\n'), - ] = False - frequency_penalty: Annotated[ - Optional[float], - Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n", - ge=-2.0, - le=2.0, - ), - ] = 0 - logit_bias: Annotated[ - Optional[Dict[str, int]], - Field( - description='Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n\nAs an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated.\n' - ), - ] = None - logprobs: Annotated[ - Optional[int], - Field( - description='Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n\nThe maximum value for `logprobs` is 5.\n', - ge=0, - le=5, - ), - ] = None - max_tokens: Annotated[ - Optional[int], - Field( - description="The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n\nThe token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n", - example=16, - ge=0, - ), - ] = 16 - n: Annotated[ - Optional[int], - Field( - description='How many completions to generate for each prompt.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n', - example=1, - ge=1, - le=128, - ), - ] = 1 - presence_penalty: Annotated[ - Optional[float], - Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n", - ge=-2.0, - le=2.0, - ), - ] = 0 - seed: Annotated[ - Optional[int], - Field( - description='If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n' - ), - ] = None - stop: Optional[StopConfiguration] = None - stream: Annotated[ - Optional[bool], - Field( - description='Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n' - ), - ] = False - stream_options: Optional[ChatCompletionStreamOptions] = None - suffix: Annotated[ - Optional[str], - Field( - description='The suffix that comes after a completion of inserted text.\n\nThis parameter is only supported for `gpt-3.5-turbo-instruct`.\n', - example='test.', - ), - ] = None - temperature: Annotated[ - Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n', - example=1, - ge=0.0, - le=2.0, - ), - ] = 1 - top_p: Annotated[ - Optional[float], - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n', - example=1, - ge=0.0, - le=1.0, - ), - ] = 1 - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - example='user-1234', - ), - ] = None - - -class CreateEmbeddingResponse(BaseModel): - data: Annotated[ - List[Embedding], - Field(description='The list of embeddings generated by the model.'), - ] - model: Annotated[ - str, Field(description='The name of the model used to generate the embedding.') - ] - object: Annotated[ - Literal['list'], Field(description='The object type, which is always "list".') - ] - usage: Annotated[ - Usage1, Field(description='The usage information for the request.') - ] - - -class CreateEvalJsonlRunDataSource(BaseModel): - type: Annotated[ - Literal['CreateEvalJsonlRunDataSource'], - Field(description='The type of data source. Always `jsonl`.'), - ] - source: Annotated[ - Union[EvalJsonlFileContentSource, EvalJsonlFileIdSource], - Field( - description='Determines what populates the `item` namespace in the data source.', - discriminator='type', - ), - ] - - -class CreateFileRequest(BaseModel): - class Config: - extra = Extra.forbid - - file: Annotated[ - bytes, Field(description='The File object (not file name) to be uploaded.\n') - ] - purpose: FilePurpose - expires_after: Optional[FileExpirationAfter] = None - - -class CreateImageEditRequest(BaseModel): - image: Annotated[ - Union[bytes, Image], - Field( - description='The image(s) to edit. Must be a supported image file or an array of images.\n\nFor `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less\nthan 50MB. You can provide up to 16 images.\n\nFor `dall-e-2`, you can only provide one image, and it should be a square\n`png` file less than 4MB.\n' - ), - ] - prompt: Annotated[ - str, - Field( - description='A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.', - example='A cute baby sea otter wearing a beret', - ), - ] - mask: Annotated[ - Optional[bytes], - Field( - description='An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`.' - ), - ] = None - background: Annotated[ - Optional[Literal['transparent', 'opaque', 'auto']], - Field( - description='Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for `gpt-image-1`. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n', - example='transparent', - ), - ] = 'auto' - model: Annotated[ - Optional[ - Union[Optional[str], Literal['dall-e-2', 'gpt-image-1', 'gpt-image-1-mini']] - ], - Field( - description='The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.' - ), - ] = None - n: Annotated[ - Optional[int], - Field( - description='The number of images to generate. Must be between 1 and 10.', - example=1, - ge=1, - le=10, - ), - ] = 1 - size: Annotated[ - Optional[ - Literal['256x256', '512x512', '1024x1024', '1536x1024', '1024x1536', 'auto'] - ], - Field( - description='The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.', - example='1024x1024', - ), - ] = '1024x1024' - response_format: Annotated[ - Optional[Literal['url', 'b64_json']], - Field( - description='The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images.', - example='url', - ), - ] = 'url' - output_format: Annotated[ - Optional[Literal['png', 'jpeg', 'webp']], - Field( - description='The format in which the generated images are returned. This parameter is\nonly supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\nThe default value is `png`.\n', - example='png', - ), - ] = 'png' - output_compression: Annotated[ - Optional[int], - Field( - description='The compression level (0-100%) for the generated images. This parameter\nis only supported for `gpt-image-1` with the `webp` or `jpeg` output\nformats, and defaults to 100.\n', - example=100, - ), - ] = 100 - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - example='user-1234', - ), - ] = None - input_fidelity: Optional[InputFidelity] = None - stream: Annotated[ - Optional[bool], - Field( - description='Edit the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\n', - example=False, - ), - ] = False - partial_images: Optional[PartialImages] = None - quality: Annotated[ - Optional[Literal['standard', 'low', 'medium', 'high', 'auto']], - Field( - description='The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`.\n', - example='high', - ), - ] = 'auto' - - -class CreateImageRequest(BaseModel): - prompt: Annotated[ - str, - Field( - description='A text description of the desired image(s). The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.', - example='A cute baby sea otter', - ), - ] - model: Annotated[ - Optional[ - Union[ - Optional[str], - Literal['dall-e-2', 'dall-e-3', 'gpt-image-1', 'gpt-image-1-mini'], - ] - ], - Field( - description='The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.' - ), - ] = None - n: Annotated[ - Optional[int], - Field( - description='The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.', - example=1, - ge=1, - le=10, - ), - ] = 1 - quality: Annotated[ - Optional[Literal['standard', 'hd', 'low', 'medium', 'high', 'auto']], - Field( - description='The quality of the image that will be generated.\n\n- `auto` (default value) will automatically select the best quality for the given model.\n- `high`, `medium` and `low` are supported for `gpt-image-1`.\n- `hd` and `standard` are supported for `dall-e-3`.\n- `standard` is the only option for `dall-e-2`.\n', - example='medium', - ), - ] = 'auto' - response_format: Annotated[ - Optional[Literal['url', 'b64_json']], - Field( - description="The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images.", - example='url', - ), - ] = 'url' - output_format: Annotated[ - Optional[Literal['png', 'jpeg', 'webp']], - Field( - description='The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.', - example='png', - ), - ] = 'png' - output_compression: Annotated[ - Optional[int], - Field( - description='The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100.', - example=100, - ), - ] = 100 - stream: Annotated[ - Optional[bool], - Field( - description='Generate the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\nThis parameter is only supported for `gpt-image-1`.\n', - example=False, - ), - ] = False - partial_images: Optional[PartialImages] = None - size: Annotated[ - Optional[ - Literal[ - 'auto', - '1024x1024', - '1536x1024', - '1024x1536', - '256x256', - '512x512', - '1792x1024', - '1024x1792', - ] - ], - Field( - description='The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.', - example='1024x1024', - ), - ] = 'auto' - moderation: Annotated[ - Optional[Literal['low', 'auto']], - Field( - description='Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value).', - example='low', - ), - ] = 'auto' - background: Annotated[ - Optional[Literal['transparent', 'opaque', 'auto']], - Field( - description='Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for `gpt-image-1`. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n', - example='transparent', - ), - ] = 'auto' - style: Annotated[ - Optional[Literal['vivid', 'natural']], - Field( - description='The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.', - example='vivid', - ), - ] = 'vivid' - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - example='user-1234', - ), - ] = None - - -class Content61(BaseModel): - __root__: Annotated[ - Union[ - MessageContentImageFileObject, - MessageContentImageUrlObject, - MessageRequestContentTextObject, - ], - Field(discriminator='type'), - ] - - -class Content6(BaseModel): - __root__: Annotated[ - List[Content61], - Field( - description='An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](https://platform.openai.com/docs/models).', - min_items=1, - title='Array of content parts', - ), - ] - - -class CreateMessageRequest(BaseModel): - class Config: - extra = Extra.forbid - - role: Annotated[ - Literal['user', 'assistant'], - Field( - description='The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n' - ), - ] - content: Union[str, Content6] - attachments: Optional[List[Attachment]] = None - metadata: Optional[Metadata] = None - - -class Input3(BaseModel): - __root__: Annotated[ - Union[ModerationImageURLInput, ModerationTextInput], Field(discriminator='type') - ] - - -class CreateModerationRequest(BaseModel): - input: Annotated[ - Union[str, List[str], List[Input3]], - Field( - description='Input (or inputs) to classify. Can be a single string, an array of strings, or\nan array of multi-modal input objects similar to other models.\n' - ), - ] - model: Annotated[ - Optional[ - Union[ - str, - Literal[ - 'omni-moderation-latest', - 'omni-moderation-2024-09-26', - 'text-moderation-latest', - 'text-moderation-stable', - ], - ] - ], - Field( - description='The content moderation model you would like to use. Learn more in\n[the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about\navailable models [here](https://platform.openai.com/docs/models#moderation).\n' - ), - ] = None - - -class CreateSpeechRequest(BaseModel): - class Config: - extra = Extra.forbid - - model: Annotated[ - Union[str, Literal['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts']], - Field( - description='One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`.\n' - ), - ] - input: Annotated[ - str, - Field( - description='The text to generate audio for. The maximum length is 4096 characters.', - max_length=4096, - ), - ] - instructions: Annotated[ - Optional[str], - Field( - description='Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`.', - max_length=4096, - ), - ] = None - voice: Annotated[ - VoiceIdsShared, - Field( - description='The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options).' - ), - ] - response_format: Annotated[ - Literal['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm'], - Field( - description='The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`.' - ), - ] = 'mp3' - speed: Annotated[ - float, - Field( - description='The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default.', - ge=0.25, - le=4.0, - ), - ] = 1 - stream_format: Annotated[ - Literal['sse', 'audio'], - Field( - description='The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`.' - ), - ] = 'audio' - - -class CreateSpeechResponseStreamEvent(BaseModel): - __root__: Annotated[ - Union[SpeechAudioDeltaEvent, SpeechAudioDoneEvent], Field(discriminator='type') - ] - - -class VectorStore2(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_items=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy4, ChunkingStrategy5]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch5(BaseModel): - vector_store_ids: Annotated[ - List[str], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_items=1, - ), - ] - vector_stores: Annotated[ - Optional[List[VectorStore2]], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_items=1, - ), - ] = None - - -class VectorStore3(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_items=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy6, ChunkingStrategy7]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch6(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_items=1, - ), - ] = None - vector_stores: Annotated[ - List[VectorStore3], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_items=1, - ), - ] - - -class ToolResources3(BaseModel): - code_interpreter: Optional[CodeInterpreter1] = None - file_search: Optional[Union[FileSearch5, FileSearch6]] = None - - -class CreateThreadRequest(BaseModel): - class Config: - extra = Extra.forbid - - messages: Annotated[ - Optional[List[CreateMessageRequest]], - Field( - description='A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with.' - ), - ] = None - tool_resources: Optional[ToolResources3] = None - metadata: Optional[Metadata] = None - - -class CreateTranscriptionResponseDiarizedJson(BaseModel): - task: Annotated[ - Literal['transcribe'], - Field(description='The type of task that was run. Always `transcribe`.'), - ] - duration: Annotated[ - float, Field(description='Duration of the input audio in seconds.') - ] - text: Annotated[ - str, - Field( - description='The concatenated transcript text for the entire audio input.' - ), - ] - segments: Annotated[ - List[TranscriptionDiarizedSegment], - Field( - description='Segments of the transcript annotated with timestamps and speaker labels.' - ), - ] - usage: Annotated[ - Optional[Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration]], - Field( - description='Token or duration usage statistics for the request.', - discriminator='type', - ), - ] = None - - -class CreateTranscriptionResponseJson(BaseModel): - text: Annotated[str, Field(description='The transcribed text.')] - logprobs: Annotated[ - Optional[List[Logprob]], - Field( - description='The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array.\n' - ), - ] = None - usage: Annotated[ - Optional[Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration]], - Field( - description='Token usage statistics for the request.', discriminator='type' - ), - ] = None - - -class CreateTranscriptionResponseVerboseJson(BaseModel): - language: Annotated[str, Field(description='The language of the input audio.')] - duration: Annotated[float, Field(description='The duration of the input audio.')] - text: Annotated[str, Field(description='The transcribed text.')] - words: Annotated[ - Optional[List[TranscriptionWord]], - Field(description='Extracted words and their corresponding timestamps.'), - ] = None - segments: Annotated[ - Optional[List[TranscriptionSegment]], - Field( - description='Segments of the transcribed text and their corresponding details.' - ), - ] = None - usage: Optional[TranscriptTextUsageDuration] = None - - -class CreateTranslationResponseVerboseJson(BaseModel): - language: Annotated[ - str, - Field(description='The language of the output translation (always `english`).'), - ] - duration: Annotated[float, Field(description='The duration of the input audio.')] - text: Annotated[str, Field(description='The translated text.')] - segments: Annotated[ - Optional[List[TranscriptionSegment]], - Field( - description='Segments of the translated text and their corresponding details.' - ), - ] = None - - -class CreateUploadRequest(BaseModel): - class Config: - extra = Extra.forbid - - filename: Annotated[str, Field(description='The name of the file to upload.\n')] - purpose: Annotated[ - Literal['assistants', 'batch', 'fine-tune', 'vision'], - Field( - description='The intended purpose of the uploaded file.\n\nSee the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose).\n' - ), - ] - bytes: Annotated[ - int, Field(description='The number of bytes in the file you are uploading.\n') - ] - mime_type: Annotated[ - str, - Field( - description='The MIME type of the file.\n\nThis must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision.\n' - ), - ] - expires_after: Optional[FileExpirationAfter] = None - - -class CreateVectorStoreFileRequest(BaseModel): - class Config: - extra = Extra.forbid - - file_id: Annotated[ - str, - Field( - description='A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files.' - ), - ] - chunking_strategy: Optional[ChunkingStrategyRequestParam] = None - attributes: Optional[VectorStoreFileAttributes] = None - - -class CreateVectorStoreRequest(BaseModel): - class Config: - extra = Extra.forbid - - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.', - max_items=500, - ), - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the vector store.') - ] = None - description: Annotated[ - Optional[str], - Field( - description="A description for the vector store. Can be used to describe the vector store's purpose." - ), - ] = None - expires_after: Optional[VectorStoreExpirationAfter] = None - chunking_strategy: Optional[ChunkingStrategyRequestParam] = None - metadata: Optional[Metadata] = None - - -class DeletedConversation(DeletedConversationResource): - pass - - -class Drag(BaseModel): - type: Annotated[ - Literal['Drag'], - Field( - description='Specifies the event type. For a drag action, this property is \nalways set to `drag`.\n' - ), - ] - path: Annotated[ - List[DragPoint], - Field( - description='An array of coordinates representing the path of the drag action. Coordinates will appear as an array\nof objects, eg\n```\n[\n { x: 100, y: 200 },\n { x: 200, y: 300 }\n]\n```\n' - ), - ] - - -class EvalGraderPython(GraderPython): - pass_threshold: Annotated[ - Optional[float], Field(description='The threshold for the score.') - ] = None - type: Literal['EvalGraderPython'] - - -class EvalGraderStringCheck(GraderStringCheck): - type: Literal['EvalGraderStringCheck'] - - -class EvalGraderTextSimilarity(GraderTextSimilarity): - pass_threshold: Annotated[float, Field(description='The threshold for the score.')] - type: Literal['EvalGraderTextSimilarity'] - - -class EvalItem(BaseModel): - role: Annotated[ - Literal['user', 'assistant', 'system', 'developer'], - Field( - description='The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n' - ), - ] - content: Annotated[ - Union[str, InputTextContent, Content7, Content8, InputAudioModel, List], - Field(description='Inputs to the model - can contain template strings.\n'), - ] - type: Annotated[ - Optional[Literal['message']], - Field(description='The type of the message input. Always `message`.\n'), - ] = None - - -class EvalLogsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['EvalLogsDataSourceConfig'], - Field(description='The type of data source. Always `logs`.'), - ] - metadata: Optional[Metadata] = None - schema_: Annotated[ - Dict[str, Any], - Field( - alias='schema', - description='The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n', - ), - ] - - -class EvalResponsesSource(BaseModel): - type: Annotated[ - Literal['EvalResponsesSource'], - Field(description='The type of run data source. Always `responses`.'), - ] - metadata: Optional[Dict[str, Any]] = None - model: Optional[str] = None - instructions_search: Optional[str] = None - created_after: Optional[CreatedAfter] = None - created_before: Optional[CreatedBefore] = None - reasoning_effort: Optional[ReasoningEffort] = None - temperature: Optional[float] = None - top_p: Optional[float] = None - users: Optional[List[str]] = None - tools: Optional[List[str]] = None - - -class EvalRunOutputItem(BaseModel): - object: Annotated[ - Literal['eval.run.output_item'], - Field(description='The type of the object. Always "eval.run.output_item".'), - ] - id: Annotated[ - str, Field(description='Unique identifier for the evaluation run output item.') - ] - run_id: Annotated[ - str, - Field( - description='The identifier of the evaluation run associated with this output item.' - ), - ] - eval_id: Annotated[ - str, Field(description='The identifier of the evaluation group.') - ] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) when the evaluation run was created.' - ), - ] - status: Annotated[str, Field(description='The status of the evaluation run.')] - datasource_item_id: Annotated[ - int, Field(description='The identifier for the data source item.') - ] - datasource_item: Annotated[ - Dict[str, Any], Field(description='Details of the input data source item.') - ] - results: Annotated[ - List[EvalRunOutputItemResult], - Field(description='A list of grader results for this output item.'), - ] - sample: Annotated[ - Sample, - Field( - description='A sample containing the input and output of the evaluation run.' - ), - ] - - -class EvalRunOutputItemList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[ - List[EvalRunOutputItem], - Field(description='An array of eval run output item objects.\n'), - ] - first_id: Annotated[ - str, - Field( - description='The identifier of the first eval run output item in the data array.' - ), - ] - last_id: Annotated[ - str, - Field( - description='The identifier of the last eval run output item in the data array.' - ), - ] - has_more: Annotated[ - bool, - Field( - description='Indicates whether there are more eval run output items available.' - ), - ] - - -class EvalStoredCompletionsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['EvalStoredCompletionsDataSourceConfig'], - Field(description='The type of data source. Always `stored_completions`.'), - ] - metadata: Optional[Metadata] = None - schema_: Annotated[ - Dict[str, Any], - Field( - alias='schema', - description='The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n', - ), - ] - - -class EvalStoredCompletionsSource(BaseModel): - type: Annotated[ - Literal['EvalStoredCompletionsSource'], - Field(description='The type of source. Always `stored_completions`.'), - ] - metadata: Optional[Metadata] = None - model: Optional[str] = None - created_after: Optional[int] = None - created_before: Optional[int] = None - limit: Optional[int] = None - - -class Result1(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The unique ID of the file.\n') - ] = None - text: Annotated[ - Optional[str], Field(description='The text that was retrieved from the file.\n') - ] = None - filename: Annotated[Optional[str], Field(description='The name of the file.\n')] = ( - None - ) - attributes: Optional[VectorStoreFileAttributes] = None - score: Annotated[ - Optional[float], - Field( - description='The relevance score of the file - a value between 0 and 1.\n' - ), - ] = None - - -class FileSearchToolCall(BaseModel): - id: Annotated[ - str, Field(description='The unique ID of the file search tool call.\n') - ] - type: Annotated[ - Literal['FileSearchToolCall'], - Field( - description='The type of the file search tool call. Always `file_search_call`.\n' - ), - ] - status: Annotated[ - Literal['in_progress', 'searching', 'completed', 'incomplete', 'failed'], - Field( - description='The status of the file search tool call. One of `in_progress`,\n`searching`, `incomplete` or `failed`,\n' - ), - ] - queries: Annotated[ - List[str], Field(description='The queries used to search for files.\n') - ] - results: Optional[List[Result1]] = None - - -class FunctionAndCustomToolCallOutput(BaseModel): - __root__: Annotated[ - Union[InputTextContent, InputImageContent, InputFileContent], - Field(discriminator='type'), - ] - - -class FunctionObject(BaseModel): - description: Annotated[ - Optional[str], - Field( - description='A description of what the function does, used by the model to choose when and how to call the function.' - ), - ] = None - name: Annotated[ - str, - Field( - description='The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.' - ), - ] - parameters: Optional[FunctionParameters] = None - strict: Optional[bool] = None - - -class FunctionToolCallOutput(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the function tool call output. Populated when this item\nis returned via API.\n' - ), - ] = None - type: Annotated[ - Literal['function_call_output'], - Field( - description='The type of the function tool call output. Always `function_call_output`.\n' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the function tool call generated by the model.\n' - ), - ] - output: Annotated[ - Union[str, List[FunctionAndCustomToolCallOutput]], - Field( - description='The output from the function call generated by your code.\nCan be a string or an list of output content.\n' - ), - ] - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' - ), - ] = None - - -class FunctionToolCallOutputResource(FunctionToolCallOutput): - id: Annotated[ - str, Field(description='The unique ID of the function call tool output.\n') - ] - type: Literal['FunctionToolCallOutputResource'] - - -class GraderLabelModel(BaseModel): - type: Annotated[ - Literal['label_model'], - Field(description='The object type, which is always `label_model`.'), +class CreateImageEditRequest(BaseModel): + image: Annotated[ + bytes, + Field( + description="The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask." + ), ] - name: Annotated[str, Field(description='The name of the grader.')] - model: Annotated[ + prompt: Annotated[ str, Field( - description='The model to use for the evaluation. Must support structured outputs.' + description="A text description of the desired image(s). The maximum length is 1000 characters.", + example="A cute baby sea otter wearing a beret", ), ] - input: List[EvalItem] - labels: Annotated[ - List[str], - Field(description='The labels to assign to each item in the evaluation.'), - ] - passing_labels: Annotated[ - List[str], + mask: Annotated[ + Optional[bytes], Field( - description='The labels that indicate a passing result. Must be a subset of labels.' + description="An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`." ), - ] - - -class SamplingParams2(BaseModel): - seed: Optional[int] = None - top_p: Optional[float] = None - temperature: Optional[float] = None - max_completions_tokens: Optional[MaxCompletionsTokens] = None - reasoning_effort: Optional[ReasoningEffort] = None - - -class GraderScoreModel(BaseModel): - type: Annotated[ - Literal['GraderScoreModel'], - Field(description='The object type, which is always `score_model`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - model: Annotated[str, Field(description='The model to use for the evaluation.')] - sampling_params: Annotated[ - Optional[SamplingParams2], - Field(description='The sampling parameters for the model.'), - ] = None - input: Annotated[ - List[EvalItem], - Field(description='The input text. This may include template strings.'), - ] - range: Annotated[ - Optional[List[float]], - Field(description='The range of the score. Defaults to `[0, 1]`.'), ] = None - - -class GroupListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[GroupResponse], Field(description='Groups returned in the current page.') - ] - has_more: Annotated[ - bool, - Field(description='Whether additional groups are available when paginating.'), - ] - next: Annotated[ - Optional[str], + model: Annotated[ + Optional[Union[str, Literal["dall-e-2"]]], Field( - description='Cursor to fetch the next page of results, or `null` if there are no more results.' + description="The model to use for image generation. Only `dall-e-2` is supported at this time.", + example="dall-e-2", ), - ] - - -class GroupRoleAssignment(BaseModel): - object: Annotated[Literal['group.role'], Field(description='Always `group.role`.')] - group: Group - role: Role - - -class ImageEditCompletedEvent(BaseModel): - type: Annotated[ - Literal['ImageEditCompletedEvent'], - Field(description='The type of the event. Always `image_edit.completed`.\n'), - ] - b64_json: Annotated[ - str, + ] = "dall-e-2" + n: Annotated[ + Optional[int], Field( - description='Base64-encoded final edited image data, suitable for rendering as an image.\n' + description="The number of images to generate. Must be between 1 and 10.", + example=1, + ge=1, + le=10, ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] + ] = 1 size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the edited image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the edited image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the edited image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the edited image.\n'), - ] - usage: ImagesUsage - - -class ImageEditStreamEvent(BaseModel): - __root__: Annotated[ - Union[ImageEditPartialImageEvent, ImageEditCompletedEvent], - Field(discriminator='type'), - ] - - -class ImageGenCompletedEvent(BaseModel): - type: Annotated[ - Literal['ImageGenCompletedEvent'], + Optional[Literal["256x256", "512x512", "1024x1024"]], Field( - description='The type of the event. Always `image_generation.completed`.\n' + description="The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.", + example="1024x1024", ), - ] - b64_json: Annotated[ - str, + ] = "1024x1024" + response_format: Annotated[ + Optional[Literal["url", "b64_json"]], Field( - description='Base64-encoded image data, suitable for rendering as an image.\n' + description="The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.", + example="url", ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the generated image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the generated image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the generated image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the generated image.\n'), - ] - usage: ImagesUsage - - -class ImageGenStreamEvent(BaseModel): - __root__: Annotated[ - Union[ImageGenPartialImageEvent, ImageGenCompletedEvent], - Field(discriminator='type'), - ] + ] = "url" + user: Annotated[ + Optional[str], + Field( + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + example="user-1234", + ), + ] = None -class ImageGenTool(BaseModel): - type: Annotated[ - Literal['ImageGenTool'], +class CreateImageVariationRequest(BaseModel): + image: Annotated[ + bytes, Field( - description='The type of the image generation tool. Always `image_generation`.\n' + description="The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square." ), ] model: Annotated[ - Literal['gpt-image-1', 'gpt-image-1-mini'], - Field( - description='The image generation model to use. Default: `gpt-image-1`.\n' - ), - ] = 'gpt-image-1' - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field( - description='The quality of the generated image. One of `low`, `medium`, `high`,\nor `auto`. Default: `auto`.\n' - ), - ] = 'auto' - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], + Optional[Union[str, Literal["dall-e-2"]]], Field( - description='The size of the generated image. One of `1024x1024`, `1024x1536`,\n`1536x1024`, or `auto`. Default: `auto`.\n' + description="The model to use for image generation. Only `dall-e-2` is supported at this time.", + example="dall-e-2", ), - ] = 'auto' - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field( - description='The output format of the generated image. One of `png`, `webp`, or\n`jpeg`. Default: `png`.\n' - ), - ] = 'png' - output_compression: Annotated[ - int, + ] = "dall-e-2" + n: Annotated[ + Optional[int], Field( - description='Compression level for the output image. Default: 100.\n', - ge=0, - le=100, + description="The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.", + example=1, + ge=1, + le=10, ), - ] = 100 - moderation: Annotated[ - Literal['auto', 'low'], + ] = 1 + response_format: Annotated[ + Optional[Literal["url", "b64_json"]], Field( - description='Moderation level for the generated image. Default: `auto`.\n' + description="The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.", + example="url", ), - ] = 'auto' - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], + ] = "url" + size: Annotated[ + Optional[Literal["256x256", "512x512", "1024x1024"]], Field( - description='Background type for the generated image. One of `transparent`,\n`opaque`, or `auto`. Default: `auto`.\n' + description="The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.", + example="1024x1024", ), - ] = 'auto' - input_fidelity: Optional[InputFidelity] = None - input_image_mask: Annotated[ - Optional[InputImageMask], + ] = "1024x1024" + user: Annotated[ + Optional[str], Field( - description='Optional mask for inpainting. Contains `image_url`\n(string, optional) and `file_id` (string, optional).\n' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + example="user-1234", ), ] = None - partial_images: Annotated[ - int, + + +class CreateModerationRequest(BaseModel): + input: Annotated[Union[str, List[str]], Field(description="The input text to classify")] + model: Annotated[ + Optional[Union[str, Literal["text-moderation-latest", "text-moderation-stable"]]], Field( - description='Number of partial images to generate in streaming mode, from 0 (default value) to 3.\n', - ge=0, - le=3, + description="Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`.\n\nThe default is `text-moderation-latest` which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`.\n", + example="text-moderation-stable", ), - ] = 0 + ] = "text-moderation-latest" -class ImagesResponse(BaseModel): - created: Annotated[ - int, +class Categories(BaseModel): + hate: Annotated[ + bool, Field( - description='The Unix timestamp (in seconds) of when the image was created.' + description="Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment." ), ] - data: Annotated[ - Optional[List[Image1]], Field(description='The list of generated images.') - ] = None - background: Annotated[ - Optional[Literal['transparent', 'opaque']], + hate_threatening: Annotated[ + bool, Field( - description='The background parameter used for the image generation. Either `transparent` or `opaque`.' + alias="hate/threatening", + description="Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.", ), - ] = None - output_format: Annotated[ - Optional[Literal['png', 'webp', 'jpeg']], + ] + harassment: Annotated[ + bool, Field( - description='The output format of the image generation. Either `png`, `webp`, or `jpeg`.' + description="Content that expresses, incites, or promotes harassing language towards any target." ), - ] = None - size: Annotated[ - Optional[Literal['1024x1024', '1024x1536', '1536x1024']], + ] + harassment_threatening: Annotated[ + bool, Field( - description='The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`.' + alias="harassment/threatening", + description="Harassment content that also includes violence or serious harm towards any target.", ), - ] = None - quality: Annotated[ - Optional[Literal['low', 'medium', 'high']], + ] + self_harm: Annotated[ + bool, Field( - description='The quality of the image generated. Either `low`, `medium`, or `high`.' + alias="self-harm", + description="Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.", ), - ] = None - usage: Optional[ImageGenUsage] = None - - -class InputContent(BaseModel): - __root__: Annotated[ - Union[InputTextContent, InputImageContent, InputFileContent], - Field(discriminator='type'), ] - - -class InputMessageContentList(BaseModel): - __root__: Annotated[ - List[InputContent], + self_harm_intent: Annotated[ + bool, Field( - description='A list of one or many input items to the model, containing different content \ntypes.\n', - title='Input item content list', + alias="self-harm/intent", + description="Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders.", ), ] - - -class ListBatchesResponse(BaseModel): - data: List[Batch] - first_id: Annotated[Optional[str], Field(example='batch_abc123')] = None - last_id: Annotated[Optional[str], Field(example='batch_abc456')] = None - has_more: bool - object: Literal['list'] - - -class ListFilesResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[OpenAIFile] - first_id: Annotated[str, Field(example='file-abc123')] - last_id: Annotated[str, Field(example='file-abc456')] - has_more: Annotated[bool, Field(example=False)] - - -class ListModelsResponse(BaseModel): - object: Literal['list'] - data: List[Model] - - -class ListVectorStoresResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[VectorStoreObject] - first_id: Annotated[str, Field(example='vs_abc123')] - last_id: Annotated[str, Field(example='vs_abc456')] - has_more: Annotated[bool, Field(example=False)] - - -class LocalShellToolCall(BaseModel): - type: Annotated[ - Literal['LocalShellToolCall'], + self_harm_instructions: Annotated[ + bool, Field( - description='The type of the local shell call. Always `local_shell_call`.\n' + alias="self-harm/instructions", + description="Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts.", ), ] - id: Annotated[str, Field(description='The unique ID of the local shell call.\n')] - call_id: Annotated[ - str, + sexual: Annotated[ + bool, Field( - description='The unique ID of the local shell tool call generated by the model.\n' + description="Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness)." ), ] - action: LocalShellExecAction - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], - Field(description='The status of the local shell call.\n'), + sexual_minors: Annotated[ + bool, + Field( + alias="sexual/minors", + description="Sexual content that includes an individual who is under 18 years old.", + ), ] - - -class MCPListTools(BaseModel): - type: Annotated[ - Literal['MCPListTools'], - Field(description='The type of the item. Always `mcp_list_tools`.\n'), + violence: Annotated[ + bool, + Field(description="Content that depicts death, violence, or physical injury."), ] - id: Annotated[str, Field(description='The unique ID of the list.\n')] - server_label: Annotated[str, Field(description='The label of the MCP server.\n')] - tools: Annotated[ - List[MCPListToolsTool], - Field(description='The tools available on the server.\n'), + violence_graphic: Annotated[ + bool, + Field( + alias="violence/graphic", + description="Content that depicts death, violence, or physical injury in graphic detail.", + ), ] - error: Optional[str] = None - - -class RequireApproval(BaseModel): - class Config: - extra = Extra.forbid - always: Optional[MCPToolFilter] = None - never: Optional[MCPToolFilter] = None - -class MCPTool(BaseModel): - type: Annotated[ - Literal['MCPTool'], Field(description='The type of the MCP tool. Always `mcp`.') +class CategoryScores(BaseModel): + hate: Annotated[float, Field(description="The score for the category 'hate'.")] + hate_threatening: Annotated[ + float, + Field( + alias="hate/threatening", + description="The score for the category 'hate/threatening'.", + ), ] - server_label: Annotated[ - str, + harassment: Annotated[float, Field(description="The score for the category 'harassment'.")] + harassment_threatening: Annotated[ + float, Field( - description='A label for this MCP server, used to identify it in tool calls.\n' + alias="harassment/threatening", + description="The score for the category 'harassment/threatening'.", ), ] - server_url: Annotated[ - Optional[str], + self_harm: Annotated[ + float, + Field(alias="self-harm", description="The score for the category 'self-harm'."), + ] + self_harm_intent: Annotated[ + float, Field( - description='The URL for the MCP server. One of `server_url` or `connector_id` must be\nprovided.\n' + alias="self-harm/intent", + description="The score for the category 'self-harm/intent'.", ), - ] = None - connector_id: Annotated[ - Optional[ - Literal[ - 'connector_dropbox', - 'connector_gmail', - 'connector_googlecalendar', - 'connector_googledrive', - 'connector_microsoftteams', - 'connector_outlookcalendar', - 'connector_outlookemail', - 'connector_sharepoint', - ] - ], + ] + self_harm_instructions: Annotated[ + float, Field( - description='Identifier for service connectors, like those available in ChatGPT. One of\n`server_url` or `connector_id` must be provided. Learn more about service\nconnectors [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).\n\nCurrently supported `connector_id` values are:\n\n- Dropbox: `connector_dropbox`\n- Gmail: `connector_gmail`\n- Google Calendar: `connector_googlecalendar`\n- Google Drive: `connector_googledrive`\n- Microsoft Teams: `connector_microsoftteams`\n- Outlook Calendar: `connector_outlookcalendar`\n- Outlook Email: `connector_outlookemail`\n- SharePoint: `connector_sharepoint`\n' + alias="self-harm/instructions", + description="The score for the category 'self-harm/instructions'.", ), - ] = None - authorization: Annotated[ - Optional[str], + ] + sexual: Annotated[float, Field(description="The score for the category 'sexual'.")] + sexual_minors: Annotated[ + float, Field( - description='An OAuth access token that can be used with a remote MCP server, either\nwith a custom MCP server URL or a service connector. Your application\nmust handle the OAuth authorization flow and provide the token here.\n' + alias="sexual/minors", + description="The score for the category 'sexual/minors'.", ), - ] = None - server_description: Annotated[ - Optional[str], + ] + violence: Annotated[float, Field(description="The score for the category 'violence'.")] + violence_graphic: Annotated[ + float, Field( - description='Optional description of the MCP server, used to provide more context.\n' + alias="violence/graphic", + description="The score for the category 'violence/graphic'.", ), - ] = None - headers: Optional[Dict[str, str]] = None - allowed_tools: Optional[Union[List[str], MCPToolFilter]] = None - require_approval: Optional[Union[RequireApproval, Literal['always', 'never']]] = ( - None - ) + ] -class MCPToolCall(BaseModel): - type: Annotated[ - Literal['MCPToolCall'], - Field(description='The type of the item. Always `mcp_call`.\n'), - ] - id: Annotated[str, Field(description='The unique ID of the tool call.\n')] - server_label: Annotated[ - str, Field(description='The label of the MCP server running the tool.\n') - ] - name: Annotated[str, Field(description='The name of the tool that was run.\n')] - arguments: Annotated[ - str, Field(description='A JSON string of the arguments passed to the tool.\n') +class Result(BaseModel): + flagged: Annotated[bool, Field(description="Whether any of the below categories are flagged.")] + categories: Annotated[ + Categories, + Field(description="A list of the categories, and whether they are flagged or not."), ] - output: Optional[str] = None - error: Optional[str] = None - status: Annotated[ - Optional[MCPToolCallStatus], + category_scores: Annotated[ + CategoryScores, Field( - description='The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`.\n' + description="A list of the categories along with their scores as predicted by model." ), - ] = None - approval_request_id: Optional[str] = None - - -class Text1(BaseModel): - value: Annotated[str, Field(description='The data that makes up the text.')] - annotations: List[TextAnnotation] - - -class MessageContentTextObject(BaseModel): - type: Annotated[ - Literal['MessageContentTextObject'], Field(description='Always `text`.') ] - text: Text1 -class Text2(BaseModel): - value: Annotated[ - Optional[str], Field(description='The data that makes up the text.') - ] = None - annotations: Optional[List[TextAnnotationDelta]] = None +class CreateModerationResponse(BaseModel): + id: Annotated[str, Field(description="The unique identifier for the moderation request.")] + model: Annotated[str, Field(description="The model used to generate the moderation results.")] + results: Annotated[List[Result], Field(description="A list of moderation objects.")] -class MessageDeltaContentTextObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the content part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentTextObject'], Field(description='Always `text`.') +class CreateFileRequest(BaseModel): + class Config: + extra = Extra.forbid + + file: Annotated[bytes, Field(description="The File object (not file name) to be uploaded.\n")] + purpose: Annotated[ + Literal["assistants", "batch", "fine-tune", "vision"], + Field( + description='The intended purpose of the uploaded file.\n\nUse "assistants" for [Assistants](/docs/api-reference/assistants) and [Message](/docs/api-reference/messages) files, "vision" for Assistants image file inputs, "batch" for [Batch API](/docs/guides/batch), and "fine-tune" for [Fine-tuning](/docs/api-reference/fine-tuning).\n' + ), ] - text: Optional[Text2] = None -class ModelIdsShared(BaseModel): - __root__: Annotated[Union[str, ChatModel], Field(example='gpt-4o')] +class DeleteFileResponse(BaseModel): + id: str + object: Literal["file"] + deleted: bool + +class CreateUploadRequest(BaseModel): + class Config: + extra = Extra.forbid -class ModelResponseProperties(BaseModel): - metadata: Optional[Metadata] = None - top_logprobs: Optional[TopLogprobs] = None - temperature: Optional[Temperature2] = None - top_p: Optional[TopP2] = None - user: Annotated[ - Optional[str], + filename: Annotated[str, Field(description="The name of the file to upload.\n")] + purpose: Annotated[ + Literal["assistants", "batch", "fine-tune", "vision"], Field( - description='This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n', - example='user-1234', + description="The intended purpose of the uploaded file.\n\nSee the [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose).\n" ), - ] = None - safety_identifier: Annotated[ - Optional[str], + ] + bytes: Annotated[int, Field(description="The number of bytes in the file you are uploading.\n")] + mime_type: Annotated[ + str, Field( - description="A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n", - example='safety-identifier-1234', + description="The MIME type of the file.\n\nThis must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision.\n" ), - ] = None - prompt_cache_key: Annotated[ + ] + + +class AddUploadPartRequest(BaseModel): + class Config: + extra = Extra.forbid + + data: Annotated[bytes, Field(description="The chunk of bytes for this Part.\n")] + + +class CompleteUploadRequest(BaseModel): + class Config: + extra = Extra.forbid + + part_ids: Annotated[List[str], Field(description="The ordered list of Part IDs.\n")] + md5: Annotated[ Optional[str], Field( - description='Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n', - example='prompt-cache-key-1234', + description="The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n" ), ] = None - service_tier: Optional[ServiceTier] = None - prompt_cache_retention: Optional[Literal['in-memory', '24h']] = None -class OutputContent(BaseModel): +class CancelUploadRequest(BaseModel): + pass + + class Config: + extra = Extra.forbid + + +class BatchSize(BaseModel): __root__: Annotated[ - Union[OutputTextContent, RefusalContent, ReasoningTextContent], - Field(discriminator='type'), + int, + Field( + description="Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n", + ge=1, + le=256, + ), ] -class OutputMessageContent(BaseModel): +class LearningRateMultiplier(BaseModel): __root__: Annotated[ - Union[OutputTextContent, RefusalContent], Field(discriminator='type') + float, + Field( + description="Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n", + gt=0.0, + ), ] -class Owner1(BaseModel): - type: Annotated[ - Optional[Literal['user', 'service_account']], - Field(description='`user` or `service_account`'), - ] = None - user: Optional[ProjectUser] = None - service_account: Optional[ProjectServiceAccount] = None +class NEpochs(BaseModel): + __root__: Annotated[ + int, + Field( + description="The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n", + ge=1, + le=50, + ), + ] -class ProjectApiKey(BaseModel): - object: Annotated[ - Literal['organization.project.api_key'], +class Hyperparameters(BaseModel): + batch_size: Annotated[ + Optional[Union[Literal["auto"], BatchSize]], Field( - description='The object type, which is always `organization.project.api_key`' + description="Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n" ), - ] - redacted_value: Annotated[ - str, Field(description='The redacted value of the API key') - ] - name: Annotated[str, Field(description='The name of the API key')] - created_at: Annotated[ - int, + ] = "auto" + learning_rate_multiplier: Annotated[ + Optional[Union[Literal["auto"], LearningRateMultiplier]], Field( - description='The Unix timestamp (in seconds) of when the API key was created' + description="Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n" ), - ] - last_used_at: Annotated[ - int, + ] = "auto" + n_epochs: Annotated[ + Optional[Union[Literal["auto"], NEpochs]], Field( - description='The Unix timestamp (in seconds) of when the API key was last used.' + description="The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n" ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - owner: Owner1 + ] = "auto" -class ProjectApiKeyListResponse(BaseModel): - object: Literal['list'] - data: List[ProjectApiKey] - first_id: str - last_id: str - has_more: bool - - -class PublicRoleListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[Role], Field(description='Roles returned in the current page.') - ] - has_more: Annotated[ - bool, Field(description='Whether more roles are available when paginating.') +class Wandb(BaseModel): + project: Annotated[ + str, + Field( + description="The name of the project that the new run will be created under.\n", + example="my-wandb-project", + ), ] - next: Annotated[ + name: Annotated[ Optional[str], Field( - description='Cursor to fetch the next page of results, or `null` when there are no additional roles.' + description="A display name to set for the run. If not set, we will use the Job ID as the name.\n" ), - ] - - -class RealtimeBetaClientEventTranscriptionSessionUpdate(BaseModel): - event_id: Annotated[ + ] = None + entity: Annotated[ Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), + Field( + description="The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n" + ), ] = None - type: Annotated[ - str, + tags: Annotated[ + Optional[List[str]], Field( - const=True, - description='The event type, must be `transcription_session.update`.', + description='A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}".\n' ), - ] = 'transcription_session.update' - session: RealtimeTranscriptionSessionCreateRequest + ] = None -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionCompleted( - BaseModel -): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] +class Integration(BaseModel): type: Annotated[ - Literal['conversation.item.input_audio_transcription.completed'], + Literal["wandb"], Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.completed`.\n' + description='The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported.\n' ), ] - item_id: Annotated[ - str, Field(description='The ID of the user message item containing the audio.') - ] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - transcript: Annotated[str, Field(description='The transcribed text.')] - logprobs: Optional[List[LogProbProperties]] = None - usage: Annotated[ - Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration], - Field(description='Usage statistics for the transcription.'), + wandb: Annotated[ + Wandb, + Field( + description="The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n" + ), ] -class RealtimeBetaServerEventTranscriptionSessionCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, +class CreateFineTuningJobRequest(BaseModel): + model: Annotated[ + Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"]], Field( - const=True, - description='The event type, must be `transcription_session.created`.', + description="The name of the model to fine-tune. You can select one of the\n[supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned).\n", + example="gpt-4o-mini", ), - ] = 'transcription_session.created' - session: RealtimeTranscriptionSessionCreateResponse - - -class RealtimeBetaServerEventTranscriptionSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ + ] + training_file: Annotated[ str, Field( - const=True, - description='The event type, must be `transcription_session.updated`.', + description="The ID of an uploaded file that contains training data.\n\nSee [upload file](/docs/api-reference/files/create) for how to upload a file.\n\nYour dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n\nThe contents of the file should differ depending on if the model uses the [chat](/docs/api-reference/fine-tuning/chat-input) or [completions](/docs/api-reference/fine-tuning/completions-input) format.\n\nSee the [fine-tuning guide](/docs/guides/fine-tuning) for more details.\n", + example="file-abc123", ), - ] = 'transcription_session.updated' - session: RealtimeTranscriptionSessionCreateResponse - - -class RealtimeClientEventTranscriptionSessionUpdate(BaseModel): - event_id: Annotated[ + ] + hyperparameters: Annotated[ + Optional[Hyperparameters], + Field(description="The hyperparameters used for the fine-tuning job."), + ] = None + suffix: Annotated[ Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), + Field( + description='A string of up to 18 characters that will be added to your fine-tuned model name.\n\nFor example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n', + max_length=40, + min_length=1, + ), ] = None - type: Annotated[ - str, + validation_file: Annotated[ + Optional[str], Field( - const=True, - description='The event type, must be `transcription_session.update`.', + description="The ID of an uploaded file that contains validation data.\n\nIf you provide this file, the data is used to generate validation\nmetrics periodically during fine-tuning. These metrics can be viewed in\nthe fine-tuning results file.\nThe same data should not be present in both train and validation files.\n\nYour dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n\nSee the [fine-tuning guide](/docs/guides/fine-tuning) for more details.\n", + example="file-abc123", + ), + ] = None + integrations: Annotated[ + Optional[List[Integration]], + Field(description="A list of integrations to enable for your fine-tuning job."), + ] = None + seed: Annotated[ + Optional[int], + Field( + description="The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\nIf a seed is not specified, one will be generated for you.\n", + example=42, + ge=0, + le=2147483647, ), - ] = 'transcription_session.update' - session: RealtimeTranscriptionSessionCreateRequest - - -class RealtimeMCPToolCall(BaseModel): - type: Annotated[ - Literal['RealtimeMCPToolCall'], - Field(description='The type of the item. Always `mcp_call`.'), - ] - id: Annotated[str, Field(description='The unique ID of the tool call.')] - server_label: Annotated[ - str, Field(description='The label of the MCP server running the tool.') - ] - name: Annotated[str, Field(description='The name of the tool that was run.')] - arguments: Annotated[ - str, Field(description='A JSON string of the arguments passed to the tool.') - ] - approval_request_id: Optional[str] = None - output: Optional[str] = None - error: Optional[ - Union[ - RealtimeMCPProtocolError, - RealtimeMCPToolExecutionError, - RealtimeMCPHTTPError, - ] ] = None -class Output(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the output audio.'), - ] = None - voice: Annotated[ - VoiceIdsShared, +class Input(BaseModel): + __root__: Annotated[ + List[str], Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n' + description="The array of strings that will be turned into an embedding.", + example="The quick brown fox jumped over the lazy dog", + max_items=2048, + min_items=1, + title="array", ), - ] = 'alloy' + ] -class Audio3(BaseModel): - output: Optional[Output] = None +class Input1(BaseModel): + __root__: Annotated[ + List[int], + Field( + description="The array of integers that will be turned into an embedding.", + example="[1212, 318, 257, 1332, 13]", + max_items=2048, + min_items=1, + title="array", + ), + ] -class Audio4(BaseModel): - output: Optional[Output] = None +class Input2Item(BaseModel): + __root__: Annotated[List[int], Field(min_items=1)] -class RealtimeServerEventConversationItemInputAudioTranscriptionCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['RealtimeServerEventConversationItemInputAudioTranscriptionCompleted'], +class Input2(BaseModel): + __root__: Annotated[ + List[Input2Item], Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.completed`.\n' + description="The array of arrays containing integers that will be turned into an embedding.", + example="[[1212, 318, 257, 1332, 13]]", + max_items=2048, + min_items=1, + title="array", ), ] - item_id: Annotated[ - str, + + +class CreateEmbeddingRequest(BaseModel): + class Config: + extra = Extra.forbid + + input: Annotated[ + Union[str, Input, Input1, Input2], Field( - description='The ID of the item containing the audio that is being transcribed.' + description="Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n", + example="The quick brown fox jumped over the lazy dog", ), ] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - transcript: Annotated[str, Field(description='The transcribed text.')] - logprobs: Optional[List[LogProbProperties]] = None - usage: Annotated[ - Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration], + model: Annotated[ + Union[ + str, + Literal[ + "text-embedding-ada-002", + "text-embedding-3-small", + "text-embedding-3-large", + ], + ], Field( - description="Usage statistics for the transcription, this is billed according to the ASR model's pricing rather than the realtime model's pricing." + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n", + example="text-embedding-3-small", ), ] - - -class RealtimeServerEventTranscriptionSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, + encoding_format: Annotated[ + Optional[Literal["float", "base64"]], Field( - const=True, - description='The event type, must be `transcription_session.updated`.', + description="The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).", + example="float", ), - ] = 'transcription_session.updated' - session: RealtimeTranscriptionSessionCreateResponse - - -class Input5(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the input audio.'), - ] = None - transcription: Annotated[ - Optional[AudioTranscription], + ] = "float" + dimensions: Annotated[ + Optional[int], Field( - description='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.\n' + description="The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n", + ge=1, ), ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], + user: Annotated[ + Optional[str], Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + example="user-1234", ), ] = None - turn_detection: Optional[RealtimeTurnDetection] = None - - -class Output2(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the output audio.'), - ] = None - voice: Annotated[ - VoiceIdsShared, - Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n' - ), - ] = 'alloy' - speed: Annotated[ - float, - Field( - description="The speed of the model's spoken response as a multiple of the original speed.\n1.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.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n", - ge=0.25, - le=1.5, - ), - ] = 1 - -class Audio5(BaseModel): - input: Optional[Input5] = None - output: Optional[Output2] = None - -class Tools2(BaseModel): - __root__: Annotated[ - Union[RealtimeFunctionTool, MCPTool], Field(discriminator='type') +class Usage1(BaseModel): + prompt_tokens: Annotated[int, Field(description="The number of tokens used by the prompt.")] + total_tokens: Annotated[ + int, Field(description="The total number of tokens used by the request.") ] -class Output3(BaseModel): - format: Optional[RealtimeAudioFormats] = None - voice: Optional[VoiceIdsShared] = None - speed: Optional[float] = None - - -class Audio6(BaseModel): - input: Optional[Input6] = None - output: Optional[Output3] = None - - -class RealtimeSessionCreateResponse(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='Unique identifier for the session that looks like `sess_1234567890abcdef`.\n' - ), - ] = None - object: Annotated[ - Optional[str], Field(description='The object type. Always `realtime.session`.') - ] = None - expires_at: Annotated[ - Optional[int], +class CreateTranscriptionRequest(BaseModel): + class Config: + extra = Extra.forbid + + file: Annotated[ + bytes, Field( - description='Expiration timestamp for the session, in seconds since epoch.' + description="The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n" ), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], + ] + model: Annotated[ + Union[str, Literal["whisper-1"]], Field( - description='Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' + description="ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n", + example="whisper-1", ), - ] = None - model: Annotated[ - Optional[str], Field(description='The Realtime model used for this session.') - ] = None - output_modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], + ] + language: Annotated[ + Optional[str], Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' + description="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) format will improve accuracy and latency.\n" ), ] = None - instructions: Annotated[ + prompt: Annotated[ Optional[str], Field( - description='The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. "be extremely succinct", "act friendly", "here are examples of good\nresponses") and on audio behavior (e.g. "talk quickly", "inject emotion\ninto your voice", "laugh frequently"). The instructions are not guaranteed\nto be followed by the model, but they provide guidance to the model on the\ndesired behavior.\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n' + description="An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language.\n" ), ] = None - audio: Annotated[ - Optional[Audio6], + response_format: Annotated[ + Optional[Literal["json", "text", "srt", "verbose_json", "vtt"]], Field( - description='Configuration for input and output audio for the session.\n' + description="The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n" ), - ] = None - tracing: Annotated[ - Optional[Union[Literal['auto'], Tracing3]], + ] = "json" + temperature: Annotated[ + Optional[float], Field( - description='Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n', - title='Tracing Configuration', + description="The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n" ), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection2], + ] = 0 + timestamp_granularities__: Annotated[ + Optional[List[Literal["word", "segment"]]], Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' + alias="timestamp_granularities[]", + description="The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\n", ), - ] = None - tools: Annotated[ - Optional[List[RealtimeFunctionTool]], - Field(description='Tools (functions) available to the model.'), - ] = None - tool_choice: Annotated[ - Optional[str], + ] = ["segment"] + + +class CreateTranscriptionResponseJson(BaseModel): + text: Annotated[str, Field(description="The transcribed text.")] + + +class TranscriptionSegment(BaseModel): + id: Annotated[int, Field(description="Unique identifier of the segment.")] + seek: Annotated[int, Field(description="Seek offset of the segment.")] + start: Annotated[float, Field(description="Start time of the segment in seconds.")] + end: Annotated[float, Field(description="End time of the segment in seconds.")] + text: Annotated[str, Field(description="Text content of the segment.")] + tokens: Annotated[List[int], Field(description="Array of token IDs for the text content.")] + temperature: Annotated[ + float, + Field(description="Temperature parameter used for generating the segment."), + ] + avg_logprob: Annotated[ + float, Field( - description='How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n' + description="Average logprob of the segment. If the value is lower than -1, consider the logprobs failed." ), - ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + ] + compression_ratio: Annotated[ + float, Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed." ), - ] = None + ] + no_speech_prob: Annotated[ + float, + Field( + description="Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent." + ), + ] + + +class TranscriptionWord(BaseModel): + word: Annotated[str, Field(description="The text content of the word.")] + start: Annotated[float, Field(description="Start time of the word in seconds.")] + end: Annotated[float, Field(description="End time of the word in seconds.")] -class Input7(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the input audio.'), +class CreateTranscriptionResponseVerboseJson(BaseModel): + language: Annotated[str, Field(description="The language of the input audio.")] + duration: Annotated[str, Field(description="The duration of the input audio.")] + text: Annotated[str, Field(description="The transcribed text.")] + words: Annotated[ + Optional[List[TranscriptionWord]], + Field(description="Extracted words and their corresponding timestamps."), ] = None - transcription: Annotated[ - Optional[AudioTranscription], + segments: Annotated[ + Optional[List[TranscriptionSegment]], + Field(description="Segments of the transcribed text and their corresponding details."), + ] = None + + +class CreateTranslationRequest(BaseModel): + class Config: + extra = Extra.forbid + + file: Annotated[ + bytes, Field( - description='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.\n' + description="The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n" ), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], + ] + model: Annotated[ + Union[str, Literal["whisper-1"]], Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' + description="ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n", + example="whisper-1", + ), + ] + prompt: Annotated[ + Optional[str], + Field( + description="An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English.\n" ), ] = None - turn_detection: Optional[RealtimeTurnDetection] = None - - -class Output4(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the output audio.'), - ] = None - voice: Annotated[ - VoiceIdsShared, + response_format: Annotated[ + Optional[str], Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n' + description="The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n" ), - ] = 'alloy' - speed: Annotated[ - float, + ] = "json" + temperature: Annotated[ + Optional[float], Field( - description="The speed of the model's spoken response as a multiple of the original speed.\n1.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.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n", - ge=0.25, - le=1.5, + description="The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n" ), - ] = 1 + ] = 0 -class Audio7(BaseModel): - input: Optional[Input7] = None - output: Optional[Output4] = None +class CreateTranslationResponseJson(BaseModel): + text: str -class Input8(BaseModel): - format: Optional[RealtimeAudioFormats] = None - transcription: Annotated[ - Optional[AudioTranscription], - Field( - description='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.\n' - ), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], - Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' - ), +class CreateTranslationResponseVerboseJson(BaseModel): + language: Annotated[ + str, + Field(description="The language of the output translation (always `english`)."), + ] + duration: Annotated[str, Field(description="The duration of the input audio.")] + text: Annotated[str, Field(description="The translated text.")] + segments: Annotated[ + Optional[List[TranscriptionSegment]], + Field(description="Segments of the translated text and their corresponding details."), ] = None - turn_detection: Optional[RealtimeTurnDetection] = None - -class Audio8(BaseModel): - input: Optional[Input8] = None +class CreateSpeechRequest(BaseModel): + class Config: + extra = Extra.forbid -class RealtimeTranscriptionSessionCreateRequestGA(BaseModel): - type: Annotated[ - Literal['RealtimeTranscriptionSessionCreateRequestGA'], + model: Annotated[ + Union[str, Literal["tts-1", "tts-1-hd"]], Field( - description='The type of session to create. Always `transcription` for transcription sessions.\n' + description="One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd`\n" ), ] - audio: Annotated[ - Optional[Audio8], - Field(description='Configuration for input and output audio.\n'), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], + input: Annotated[ + str, Field( - description='Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' + description="The text to generate audio for. The maximum length is 4096 characters.", + max_length=4096, ), - ] = None + ] + voice: Annotated[ + Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], + Field( + description="The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech/voice-options)." + ), + ] + response_format: Annotated[ + Optional[Literal["mp3", "opus", "aac", "flac", "wav", "pcm"]], + Field( + description="The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." + ), + ] = "mp3" + speed: Annotated[ + Optional[float], + Field( + description="The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default.", + ge=0.25, + le=4.0, + ), + ] = 1.0 -class Reasoning(BaseModel): - effort: Optional[ReasoningEffort] = None - summary: Optional[Literal['auto', 'concise', 'detailed']] = None - generate_summary: Optional[Literal['auto', 'concise', 'detailed']] = None +class Model(BaseModel): + id: Annotated[ + str, + Field(description="The model identifier, which can be referenced in the API endpoints."), + ] + created: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) when the model was created."), + ] + object: Annotated[ + Literal["model"], Field(description='The object type, which is always "model".') + ] + owned_by: Annotated[str, Field(description="The organization that owns the model.")] -class ReasoningItem(BaseModel): - type: Annotated[ - Literal['ReasoningItem'], - Field(description='The type of the object. Always `reasoning`.\n'), - ] +class OpenAIFile(BaseModel): id: Annotated[ - str, Field(description='The unique identifier of the reasoning content.\n') + str, + Field(description="The file identifier, which can be referenced in the API endpoints."), + ] + bytes: Annotated[int, Field(description="The size of the file, in bytes.")] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the file was created."), + ] + filename: Annotated[str, Field(description="The name of the file.")] + object: Annotated[ + Literal["file"], Field(description="The object type, which is always `file`.") + ] + purpose: Annotated[ + Literal[ + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", + ], + Field( + description="The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`." + ), ] - encrypted_content: Optional[str] = None - summary: Annotated[List[Summary], Field(description='Reasoning summary content.\n')] - content: Annotated[ - Optional[List[ReasoningTextContent]], - Field(description='Reasoning text content.\n'), - ] = None status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], + Literal["uploaded", "processed", "error"], + Field( + description="Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`." + ), + ] + status_details: Annotated[ + Optional[str], Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' + description="Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`." ), ] = None -class ResponseContentPartAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseContentPartAddedEvent'], +class Upload(BaseModel): + id: Annotated[ + str, Field( - description='The type of the event. Always `response.content_part.added`.\n' + description="The Upload unique identifier, which can be referenced in API endpoints." ), ] - item_id: Annotated[ + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the Upload was created."), + ] + filename: Annotated[str, Field(description="The name of the file to be uploaded.")] + bytes: Annotated[int, Field(description="The intended number of bytes to be uploaded.")] + purpose: Annotated[ str, Field( - description='The ID of the output item that the content part was added to.\n' + description="The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values." ), ] - output_index: Annotated[ + status: Annotated[ + Literal["pending", "completed", "cancelled", "expired"], + Field(description="The status of the Upload."), + ] + expires_at: Annotated[ int, + Field(description="The Unix timestamp (in seconds) for when the Upload was created."), + ] + object: Annotated[ + Optional[Literal["upload"]], + Field(description='The object type, which is always "upload".'), + ] = None + file: Annotated[ + Optional[OpenAIFile], + Field(description="The ready File object after the Upload is completed."), + ] = None + + +class UploadPart(BaseModel): + id: Annotated[ + str, Field( - description='The index of the output item that the content part was added to.\n' + description="The upload Part unique identifier, which can be referenced in API endpoints." ), ] - content_index: Annotated[ - int, Field(description='The index of the content part that was added.\n') + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the Part was created."), ] - part: Annotated[ - OutputContent, Field(description='The content part that was added.\n') + upload_id: Annotated[ + str, + Field(description="The ID of the Upload object that this Part was added to."), ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') + object: Annotated[ + Literal["upload.part"], + Field(description="The object type, which is always `upload.part`."), ] -class ResponseContentPartDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseContentPartDoneEvent'], +class Embedding(BaseModel): + index: Annotated[ + int, Field(description="The index of the embedding in the list of embeddings.") + ] + embedding: Annotated[ + List[float], Field( - description='The type of the event. Always `response.content_part.done`.\n' + description="The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings).\n" ), ] - item_id: Annotated[ + object: Annotated[ + Literal["embedding"], + Field(description='The object type, which is always "embedding".'), + ] + + +class Error1(BaseModel): + code: Annotated[str, Field(description="A machine-readable error code.")] + message: Annotated[str, Field(description="A human-readable error message.")] + param: Annotated[ str, Field( - description='The ID of the output item that the content part was added to.\n' + description="The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific." ), ] - output_index: Annotated[ + + +class NEpochs1(BaseModel): + __root__: Annotated[ int, Field( - description='The index of the output item that the content part was added to.\n' + description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n"auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs.', + ge=1, + le=50, ), ] - content_index: Annotated[ - int, Field(description='The index of the content part that is done.\n') + + +class Hyperparameters1(BaseModel): + n_epochs: Annotated[ + Union[Literal["auto"], NEpochs1], + Field( + description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n"auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs.' + ), ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') + + +class FineTuningIntegration(BaseModel): + type: Annotated[ + Literal["wandb"], + Field(description="The type of the integration being enabled for the fine-tuning job"), ] - part: Annotated[ - OutputContent, Field(description='The content part that is done.\n') + wandb: Annotated[ + Wandb, + Field( + description="The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n" + ), ] -class ResponseError1(BaseModel): - code: ResponseErrorCode - message: Annotated[ - str, Field(description='A human-readable description of the error.\n') - ] +class FineTuningJobEvent(BaseModel): + id: str + created_at: int + level: Literal["info", "warn", "error"] + message: str + object: Literal["fine_tuning.job.event"] -class ResponseError(BaseModel): - __root__: Optional[ResponseError1] +class Metrics(BaseModel): + step: Optional[float] = None + train_loss: Optional[float] = None + train_mean_token_accuracy: Optional[float] = None + valid_loss: Optional[float] = None + valid_mean_token_accuracy: Optional[float] = None + full_valid_loss: Optional[float] = None + full_valid_mean_token_accuracy: Optional[float] = None -class JsonSchema(BaseModel): - description: Annotated[ - Optional[str], - Field( - description='A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n' - ), - ] = None - name: Annotated[ +class FineTuningJobCheckpoint(BaseModel): + id: Annotated[ str, Field( - description='The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n' + description="The checkpoint identifier, which can be referenced in the API endpoints." ), ] - schema_: Annotated[ - Optional[ResponseFormatJsonSchemaSchema], Field(alias='schema') + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the checkpoint was created."), + ] + fine_tuned_model_checkpoint: Annotated[ + str, + Field(description="The name of the fine-tuned checkpoint model that is created."), + ] + step_number: Annotated[ + int, Field(description="The step number that the checkpoint was created at.") + ] + metrics: Annotated[ + Metrics, + Field(description="Metrics at the step number during the fine-tuning job."), + ] + fine_tuning_job_id: Annotated[ + str, + Field(description="The name of the fine-tuning job that this checkpoint was created from."), + ] + object: Annotated[ + Literal["fine_tuning.job.checkpoint"], + Field(description='The object type, which is always "fine_tuning.job.checkpoint".'), + ] + + +class FinetuneCompletionRequestInput(BaseModel): + prompt: Annotated[ + Optional[str], Field(description="The input prompt for this training example.") + ] = None + completion: Annotated[ + Optional[str], + Field(description="The desired completion for this training example."), ] = None - strict: Optional[bool] = None -class ResponseFormatJsonSchema(BaseModel): - type: Annotated[ - Literal['ResponseFormatJsonSchema'], - Field( - description='The type of response format being defined. Always `json_schema`.' - ), +class CompletionUsage(BaseModel): + completion_tokens: Annotated[ + int, Field(description="Number of tokens in the generated completion.") ] - json_schema: Annotated[ - JsonSchema, - Field( - description='Structured Outputs configuration options, including a JSON Schema.\n', - title='JSON schema', - ), + prompt_tokens: Annotated[int, Field(description="Number of tokens in the prompt.")] + total_tokens: Annotated[ + int, + Field(description="Total number of tokens used in the request (prompt + completion)."), ] -class ResponsePromptVariables(BaseModel): - __root__: Optional[ - Dict[str, Union[str, InputTextContent, InputImageContent, InputFileContent]] +class RunCompletionUsage(BaseModel): + completion_tokens: Annotated[ + int, + Field(description="Number of completion tokens used over the course of the run."), ] - - -class SubmitToolOutputs(BaseModel): - tool_calls: Annotated[ - List[RunToolCallObject], Field(description='A list of the relevant tool calls.') + prompt_tokens: Annotated[ + int, + Field(description="Number of prompt tokens used over the course of the run."), + ] + total_tokens: Annotated[ + int, Field(description="Total number of tokens used (prompt + completion).") ] -class RequiredAction(BaseModel): - type: Annotated[ - Literal['submit_tool_outputs'], - Field(description='For now, this is always `submit_tool_outputs`.'), +class RunStepCompletionUsage(BaseModel): + completion_tokens: Annotated[ + int, + Field(description="Number of completion tokens used over the course of the run step."), ] - submit_tool_outputs: Annotated[ - SubmitToolOutputs, - Field( - description='Details on the tool outputs needed for this run to continue.' - ), + prompt_tokens: Annotated[ + int, + Field(description="Number of prompt tokens used over the course of the run step."), + ] + total_tokens: Annotated[ + int, Field(description="Total number of tokens used (prompt + completion).") ] -class Outputs1(BaseModel): +class AssistantsApiResponseFormatOption(BaseModel): __root__: Annotated[ Union[ - RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, - RunStepDeltaStepDetailsToolCallsCodeOutputImageObject, + Literal["auto"], + ResponseFormatText, + ResponseFormatJsonObject, + ResponseFormatJsonSchema, ], - Field(discriminator='type'), + Field( + description='Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n' + ), ] -class CodeInterpreter6(BaseModel): - input: Annotated[ - Optional[str], Field(description='The input to the Code Interpreter tool call.') - ] = None - outputs: Annotated[ - Optional[List[Outputs1]], +class CodeInterpreter(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.' + description="A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n", + max_items=20, ), - ] = None + ] = [] -class RunStepDeltaStepDetailsToolCallsCodeObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the tool call in the tool calls array.') - ] - id: Annotated[Optional[str], Field(description='The ID of the tool call.')] = None - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsCodeObject'], +class FileSearch(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='The type of tool call. This is always going to be `code_interpreter` for this type of tool call.' + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, ), - ] - code_interpreter: Annotated[ - Optional[CodeInterpreter6], - Field(description='The Code Interpreter tool call definition.'), ] = None -class Outputs2(BaseModel): - __root__: Annotated[ - Union[ - RunStepDetailsToolCallsCodeOutputLogsObject, - RunStepDetailsToolCallsCodeOutputImageObject, - ], - Field(discriminator='type'), - ] +class ToolResources(BaseModel): + code_interpreter: Optional[CodeInterpreter] = None + file_search: Optional[FileSearch] = None -class CodeInterpreter7(BaseModel): - input: Annotated[ - str, Field(description='The input to the Code Interpreter tool call.') - ] - outputs: Annotated[ - List[Outputs2], +class CodeInterpreter1(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.' + description="A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + max_items=20, ), - ] + ] = [] -class RunStepDetailsToolCallsCodeObject(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call.')] - type: Annotated[ - Literal['RunStepDetailsToolCallsCodeObject'], - Field( - description='The type of tool call. This is always going to be `code_interpreter` for this type of tool call.' - ), - ] - code_interpreter: Annotated[ - CodeInterpreter7, - Field(description='The Code Interpreter tool call definition.'), - ] +class ChunkingStrategy(BaseModel): + class Config: + extra = Extra.forbid + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class FileSearch9(BaseModel): - ranking_options: Optional[RunStepDetailsToolCallsFileSearchRankingOptionsObject] = ( - None - ) - results: Annotated[ - Optional[List[RunStepDetailsToolCallsFileSearchResultObject]], - Field(description='The results of the file search.'), - ] = None +class Static(BaseModel): + class Config: + extra = Extra.forbid -class RunStepDetailsToolCallsFileSearchObject(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call object.')] - type: Annotated[ - Literal['RunStepDetailsToolCallsFileSearchObject'], + max_chunk_size_tokens: Annotated[ + int, Field( - description='The type of tool call. This is always going to be `file_search` for this type of tool call.' + description="The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.", + ge=100, + le=4096, ), ] - file_search: Annotated[ - FileSearch9, - Field(description='For now, this is always going to be an empty object.'), - ] - - -class TextResponseFormatConfiguration(BaseModel): - __root__: Annotated[ - Union[ - ResponseFormatText, TextResponseFormatJsonSchema, ResponseFormatJsonObject - ], + chunk_overlap_tokens: Annotated[ + int, Field( - description='An object specifying the format that the model must output.\n\nConfiguring `{ "type": "json_schema" }` enables Structured Outputs, \nwhich ensures the model will match your supplied JSON schema. Learn more in the \n[Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n\nThe default format is `{ "type": "text" }` with no additional options.\n\n**Not recommended for gpt-4o and newer models:**\n\nSetting to `{ "type": "json_object" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n', - discriminator='type', + description="The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" ), ] -class ToolChoiceParam(BaseModel): - __root__: Annotated[ - Union[ - ToolChoiceOptions, - ToolChoiceAllowed, - ToolChoiceTypes, - ToolChoiceFunction, - ToolChoiceMCP, - ToolChoiceCustom, - SpecificApplyPatchParam, - SpecificFunctionShellParam, - ], +class ChunkingStrategy1(BaseModel): + class Config: + extra = Extra.forbid + + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static + + +class VectorStore(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n', - discriminator='type', + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_items=10000, ), - ] + ] = None + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy, ChunkingStrategy1]], + Field( + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None -class TranscriptTextDoneEvent(BaseModel): - type: Annotated[ - Literal['TranscriptTextDoneEvent'], - Field(description='The type of the event. Always `transcript.text.done`.\n'), +class FileSearch1(BaseModel): + vector_store_ids: Annotated[ + List[str], + Field( + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, + ), ] - text: Annotated[str, Field(description='The text that was transcribed.\n')] - logprobs: Annotated[ - Optional[List[Logprob1]], + vector_stores: Annotated[ + Optional[List[VectorStore]], Field( - description='The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n' + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, ), ] = None - usage: Optional[TranscriptTextUsageTokens] = None - -class TranscriptionChunkingStrategy(BaseModel): - __root__: Optional[Union[Literal['auto'], VadConfig]] - -class UpdateVectorStoreFileAttributesRequest(BaseModel): +class ChunkingStrategy2(BaseModel): class Config: extra = Extra.forbid - attributes: VectorStoreFileAttributes + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class UpdateVectorStoreRequest(BaseModel): +class ChunkingStrategy3(BaseModel): class Config: extra = Extra.forbid - name: Annotated[ - Optional[str], Field(description='The name of the vector store.') - ] = None - expires_after: Optional[VectorStoreExpirationAfter] = None - metadata: Optional[Metadata] = None - - -class Result2(BaseModel): - __root__: Annotated[ - Union[ - UsageCompletionsResult, - UsageEmbeddingsResult, - UsageModerationsResult, - UsageImagesResult, - UsageAudioSpeechesResult, - UsageAudioTranscriptionsResult, - UsageVectorStoresResult, - UsageCodeInterpreterSessionsResult, - CostsResult, - ], - Field(discriminator='object'), - ] + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static -class UsageTimeBucket(BaseModel): - object: Literal['bucket'] - start_time: int - end_time: int - result: List[Result2] +class VectorStore1(BaseModel): + file_ids: Annotated[ + Optional[List[str]], + Field( + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_items=10000, + ), + ] = None + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy2, ChunkingStrategy3]], + Field( + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None -class VectorStoreFileObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['vector_store.file'], - Field(description='The object type, which is always `vector_store.file`.'), - ] - usage_bytes: Annotated[ - int, +class FileSearch2(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='The total vector store usage in bytes. Note that this may be different from the original file size.' + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, ), - ] - created_at: Annotated[ - int, + ] = None + vector_stores: Annotated[ + List[VectorStore1], Field( - description='The Unix timestamp (in seconds) for when the vector store file was created.' + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, ), ] - vector_store_id: Annotated[ - str, + + +class ToolResources1(BaseModel): + code_interpreter: Optional[CodeInterpreter1] = None + file_search: Optional[Union[FileSearch1, FileSearch2]] = None + + +class CodeInterpreter2(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.' + description="Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + max_items=20, ), - ] - status: Annotated[ - Literal['in_progress', 'completed', 'cancelled', 'failed'], + ] = [] + + +class FileSearch3(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use.' + description="Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, ), - ] - last_error: Optional[LastError2] - chunking_strategy: Optional[ChunkingStrategyResponse] = None - attributes: Optional[VectorStoreFileAttributes] = None + ] = None -class VectorStoreSearchRequest(BaseModel): - class Config: - extra = Extra.forbid +class ToolResources2(BaseModel): + code_interpreter: Optional[CodeInterpreter2] = None + file_search: Optional[FileSearch3] = None + - query: Annotated[ - Union[str, List[QueryItem]], Field(description='A query string for a search') +class DeleteAssistantResponse(BaseModel): + id: str + deleted: bool + object: Literal["assistant.deleted"] + + +class AssistantToolsCode(BaseModel): + type: Annotated[ + Literal["code_interpreter"], + Field(description="The type of tool being defined: `code_interpreter`"), ] - rewrite_query: Annotated[ - bool, - Field( - description='Whether to rewrite the natural language query for vector search.' - ), - ] = False + + +class FileSearch4(BaseModel): max_num_results: Annotated[ - int, + Optional[int], Field( - description='The maximum number of results to return. This number should be between 1 and 50 inclusive.', + description="The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n\nNote that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information.\n", ge=1, le=50, ), - ] = 10 - filters: Annotated[ - Optional[Union[ComparisonFilter, CompoundFilter]], - Field(description='A filter to apply based on file attributes.'), ] = None - ranking_options: Annotated[ - Optional[RankingOptions], Field(description='Ranking options for search.') + + +class AssistantToolsFileSearch(BaseModel): + type: Annotated[ + Literal["file_search"], + Field(description="The type of tool being defined: `file_search`"), + ] + file_search: Annotated[ + Optional[FileSearch4], Field(description="Overrides for the file search tool.") ] = None -class Filters2(BaseModel): - __root__: Union[ComparisonFilter, CompoundFilter] +class AssistantToolsFileSearchTypeOnly(BaseModel): + type: Annotated[ + Literal["file_search"], + Field(description="The type of tool being defined: `file_search`"), + ] -class FileSearchTool(BaseModel): +class AssistantToolsFunction(BaseModel): type: Annotated[ - Literal['FileSearchTool'], - Field(description='The type of the file search tool. Always `file_search`.'), + Literal["function"], + Field(description="The type of tool being defined: `function`"), ] - vector_store_ids: Annotated[ - List[str], Field(description='The IDs of the vector stores to search.') + function: FunctionObject + + +class TruncationObject(BaseModel): + type: Annotated[ + Literal["auto", "last_messages"], + Field( + description="The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`." + ), ] - max_num_results: Annotated[ + last_messages: Annotated[ Optional[int], Field( - description='The maximum number of results to return. This number should be between 1 and 50 inclusive.' + description="The number of most recent messages from the thread when constructing the context for the run.", + ge=1, ), ] = None - ranking_options: Annotated[ - Optional[RankingOptions1], Field(description='Ranking options for search.') - ] = None - filters: Optional[Filters2] = None -class RunStepDetailsToolCall(BaseModel): - __root__: Annotated[ - Union[ - RunStepDetailsToolCallsCodeObject, - RunStepDetailsToolCallsFileSearchObject, - RunStepDetailsToolCallsFunctionObject, - ], - Field(discriminator='type'), - ] +class Function3(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] -class RunStepDeltaStepDetailsToolCall(BaseModel): - __root__: Annotated[ - Union[ - RunStepDeltaStepDetailsToolCallsCodeObject, - RunStepDeltaStepDetailsToolCallsFileSearchObject, - RunStepDeltaStepDetailsToolCallsFunctionObject, - ], - Field(discriminator='type'), +class AssistantsNamedToolChoice(BaseModel): + type: Annotated[ + Literal["function", "code_interpreter", "file_search"], + Field( + description="The type of the tool. If type is `function`, the function name must be set" + ), ] + function: Optional[Function3] = None -class MessageContent(BaseModel): - __root__: Annotated[ - Union[ - MessageContentImageFileObject, - MessageContentImageUrlObject, - MessageContentTextObject, - MessageContentRefusalObject, - ], - Field(discriminator='type'), +class LastError(BaseModel): + code: Annotated[ + Literal["server_error", "rate_limit_exceeded", "invalid_prompt"], + Field(description="One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`."), ] + message: Annotated[str, Field(description="A human-readable description of the error.")] -class MessageContentDelta(BaseModel): - __root__: Annotated[ - Union[ - MessageDeltaContentImageFileObject, - MessageDeltaContentTextObject, - MessageDeltaContentRefusalObject, - MessageDeltaContentImageUrlObject, - ], - Field(discriminator='type'), - ] - +class IncompleteDetails(BaseModel): + reason: Annotated[ + Optional[Literal["max_completion_tokens", "max_prompt_tokens"]], + Field( + description="The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run." + ), + ] = None -class AssistantToolsFunction(BaseModel): - type: Annotated[ - Literal['AssistantToolsFunction'], - Field(description='The type of tool being defined: `function`'), - ] - function: FunctionObject +class ModifyRunRequest(BaseModel): + class Config: + extra = Extra.forbid -class AssistantsApiResponseFormatOption(BaseModel): - __root__: Annotated[ - Union[ - Literal['auto'], - ResponseFormatText, - ResponseFormatJsonObject, - ResponseFormatJsonSchema, - ], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] + ] = None -class AuditLogActor(BaseModel): - type: Annotated[ - Optional[Literal['session', 'api_key']], - Field(description='The type of actor. Is either `session` or `api_key`.'), +class ToolOutput(BaseModel): + tool_call_id: Annotated[ + Optional[str], + Field( + description="The ID of the tool call in the `required_action` object within the run object the output is being submitted for." + ), + ] = None + output: Annotated[ + Optional[str], + Field(description="The output of the tool call to be submitted to continue the run."), ] = None - session: Optional[AuditLogActorSession] = None - api_key: Optional[AuditLogActorApiKey] = None -class ChatCompletionList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[ - List[CreateChatCompletionResponse], - Field(description='An array of chat completion objects.\n'), +class SubmitToolOutputsRunRequest(BaseModel): + class Config: + extra = Extra.forbid + + tool_outputs: Annotated[ + List[ToolOutput], + Field(description="A list of tools for which the outputs are being submitted."), ] - first_id: Annotated[ - str, + stream: Annotated[ + Optional[bool], Field( - description='The identifier of the first chat completion in the data array.' + description="If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" ), + ] = None + + +class Function4(BaseModel): + name: Annotated[str, Field(description="The name of the function.")] + arguments: Annotated[ + str, + Field(description="The arguments that the model expects you to pass to the function."), ] - last_id: Annotated[ + + +class RunToolCallObject(BaseModel): + id: Annotated[ str, Field( - description='The identifier of the last chat completion in the data array.' + description="The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint." ), ] - has_more: Annotated[ - bool, + type: Annotated[ + Literal["function"], Field( - description='Indicates whether there are more Chat Completions available.' + description="The type of tool call the output is required for. For now, this is always `function`." ), ] + function: Annotated[Function4, Field(description="The function definition.")] -class Content(BaseModel): - __root__: Annotated[ - List[ChatCompletionRequestAssistantMessageContentPart], +class CodeInterpreter3(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.', - min_items=1, - title='Array of content parts', + description="A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + max_items=20, ), - ] + ] = [] -class ChatCompletionRequestAssistantMessage(BaseModel): - content: Optional[Union[str, Content]] = None - refusal: Optional[str] = None - role: Annotated[ - Literal['ChatCompletionRequestAssistantMessage'], - Field(description='The role of the messages author, in this case `assistant`.'), - ] - name: Annotated[ - Optional[str], +class FileSearch5(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_items=1, ), ] = None - audio: Optional[Audio] = None - tool_calls: Optional[ChatCompletionMessageToolCalls] = None - function_call: Optional[FunctionCall] = None -class ChatCompletionRequestMessage(BaseModel): - __root__: Annotated[ - Union[ - ChatCompletionRequestDeveloperMessage, - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - ChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ], - Field(discriminator='role'), - ] +class ToolResources3(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[FileSearch5] = None -class ChatCompletionTool(BaseModel): - type: Annotated[ - Literal['ChatCompletionTool'], +class FileSearch6(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='The type of the tool. Currently, only `function` is supported.' + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_items=1, ), - ] - function: FunctionObject + ] = None -class ComputerAction(BaseModel): - __root__: Annotated[ - Union[ - ClickParam, - DoubleClickAction, - Drag, - KeyPressAction, - Move, - Screenshot, - Scroll, - Type, - Wait, - ], - Field(discriminator='type'), - ] +class ToolResources4(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[FileSearch6] = None -class ComputerToolCall(BaseModel): - type: Annotated[ - Literal['ComputerToolCall'], - Field(description='The type of the computer call. Always `computer_call`.'), - ] - id: Annotated[str, Field(description='The unique ID of the computer call.')] - call_id: Annotated[ +class ThreadObject(BaseModel): + id: Annotated[ str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["thread"], + Field(description="The object type, which is always `thread`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the thread was created."), + ] + tool_resources: Annotated[ + ToolResources4, Field( - description='An identifier used when responding to the tool call with output.\n' + description="A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), ] - action: ComputerAction - pending_safety_checks: Annotated[ - List[ComputerCallSafetyCheckParam], - Field(description='The pending safety checks for the computer call.\n'), - ] - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], + metadata: Annotated[ + Dict[str, Any], Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] -class Content5(BaseModel): - __root__: Annotated[ - Union[InputContent, OutputContent], - Field(description='Multi-modal input and output contents.\n'), - ] +class ChunkingStrategy4(BaseModel): + class Config: + extra = Extra.forbid + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class Tools(BaseModel): - __root__: Annotated[ - Union[ChatCompletionTool, CustomToolChatCompletions], - Field(discriminator='type'), - ] +class ChunkingStrategy5(BaseModel): + class Config: + extra = Extra.forbid -class SamplingParams(BaseModel): - reasoning_effort: Optional[ReasoningEffort] = None - temperature: Annotated[ - float, - Field(description='A higher temperature increases randomness in the outputs.'), - ] = 1 - max_completion_tokens: Annotated[ - Optional[int], - Field(description='The maximum number of tokens in the generated output.'), - ] = None - top_p: Annotated[ - float, - Field( - description='An alternative to temperature for nucleus sampling; 1.0 includes all tokens.' - ), - ] = 1 - seed: Annotated[ - int, - Field( - description='A seed value to initialize the randomness, during sampling.' - ), - ] = 42 - response_format: Annotated[ - Optional[ - Union[ - ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject - ] - ], + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static + + +class VectorStore2(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='An object specifying the format that the model must output.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n' + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_items=10000, ), ] = None - tools: Annotated[ - Optional[List[ChatCompletionTool]], + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy4, ChunkingStrategy5]], Field( - description='A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n' + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." ), ] = None - - -class CreateEvalItem(BaseModel): - __root__: Annotated[ - Union[CreateEvalItem1, EvalItem], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.', - title='CreateEvalItem', + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] + ] = None -class CreateEvalLabelModelGrader(BaseModel): - type: Annotated[ - Literal['CreateEvalLabelModelGrader'], - Field(description='The object type, which is always `label_model`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - model: Annotated[ - str, - Field( - description='The model to use for the evaluation. Must support structured outputs.' - ), - ] - input: Annotated[ - List[CreateEvalItem], - Field( - description='A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.' - ), - ] - labels: Annotated[ - List[str], - Field(description='The labels to classify to each item in the evaluation.'), - ] - passing_labels: Annotated[ +class FileSearch7(BaseModel): + vector_store_ids: Annotated[ List[str], Field( - description='The labels that indicate a passing result. Must be a subset of labels.' + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_items=1, ), ] - - -class InputMessages2(BaseModel): - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `template`.'), - ] - template: Annotated[ - List[Union[Template, EvalItem]], + vector_stores: Annotated[ + Optional[List[VectorStore2]], Field( - description='A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.' + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_items=1, ), - ] - + ] = None -class Text(BaseModel): - format: Optional[TextResponseFormatConfiguration] = None +class ChunkingStrategy6(BaseModel): + class Config: + extra = Extra.forbid -class CreateModelResponseProperties(ModelResponseProperties): - top_logprobs: Annotated[ - Optional[int], - Field( - description='An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n', - ge=0, - le=20, - ), - ] = None + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class CreateTranscriptionRequest(BaseModel): +class ChunkingStrategy7(BaseModel): class Config: extra = Extra.forbid - file: Annotated[ - bytes, - Field( - description='The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n' - ), - ] - model: Annotated[ - Union[ - str, - Literal[ - 'whisper-1', - 'gpt-4o-transcribe', - 'gpt-4o-mini-transcribe', - 'gpt-4o-transcribe-diarize', - ], - ], - Field( - description='ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `whisper-1` (which is powered by our open source Whisper V2 model), and `gpt-4o-transcribe-diarize`.\n', - example='gpt-4o-transcribe', - ), - ] - language: Annotated[ - Optional[str], + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static + + +class VectorStore3(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='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.\n' + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_items=10000, ), ] = None - prompt: Annotated[ - Optional[str], + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy6, ChunkingStrategy7]], Field( - description="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. This field is not supported when using `gpt-4o-transcribe-diarize`.\n" + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." ), ] = None - response_format: Annotated[Optional[AudioResponseFormat], Field()] = 'json' - temperature: Annotated[ - float, + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n' + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = 0 - include: Annotated[ - Optional[List[TranscriptionInclude]], + ] = None + + +class FileSearch8(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description="Additional information to include in the transcription response.\n`logprobs` will return the log probabilities of the tokens in the\nresponse to understand the model's confidence in the transcription.\n`logprobs` only works with response_format set to `json` and only with\nthe models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`. This field is not supported when using `gpt-4o-transcribe-diarize`.\n" + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_items=1, ), ] = None - timestamp_granularities: Annotated[ - List[Literal['word', 'segment']], + vector_stores: Annotated[ + List[VectorStore3], Field( - description='The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\nThis option is not available for `gpt-4o-transcribe-diarize`.\n' + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_items=1, ), - ] = ['segment'] - stream: Optional[bool] = None - chunking_strategy: Optional[TranscriptionChunkingStrategy] = None - known_speaker_names: Annotated[ + ] + + +class ToolResources5(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[Union[FileSearch7, FileSearch8]] = None + + +class FileSearch9(BaseModel): + vector_store_ids: Annotated[ Optional[List[str]], Field( - description='Optional list of speaker names that correspond to the audio samples provided in `known_speaker_references[]`. Each entry should be a short identifier (for example `customer` or `agent`). Up to 4 speakers are supported.\n', - max_items=4, + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_items=1, ), ] = None - known_speaker_references: Annotated[ - Optional[List[str]], + + +class ToolResources6(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[FileSearch9] = None + + +class ModifyThreadRequest(BaseModel): + class Config: + extra = Extra.forbid + + tool_resources: Annotated[ + Optional[ToolResources6], Field( - description='Optional list of audio samples (as [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)) that contain known speaker references matching `known_speaker_names[]`. Each sample must be between 2 and 10 seconds, and can use any of the same input audio formats supported by `file`.\n', - max_items=4, + description="A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None -class CreateTranscriptionResponseStreamEvent(BaseModel): - __root__: Annotated[ - Union[ - TranscriptTextSegmentEvent, - TranscriptTextDeltaEvent, - TranscriptTextDoneEvent, - ], - Field(discriminator='type'), +class DeleteThreadResponse(BaseModel): + id: str + deleted: bool + object: Literal["thread.deleted"] + + +class ListThreadsResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[ThreadObject] + first_id: Annotated[str, Field(example="asst_abc123")] + last_id: Annotated[str, Field(example="asst_abc456")] + has_more: Annotated[bool, Field(example=False)] + + +class IncompleteDetails1(BaseModel): + reason: Annotated[ + Literal["content_filter", "max_tokens", "run_cancelled", "run_expired", "run_failed"], + Field(description="The reason the message is incomplete."), ] -class CreateVectorStoreFileBatchRequest(BaseModel): +class Attachment(BaseModel): + file_id: Annotated[ + Optional[str], Field(description="The ID of the file to attach to the message.") + ] = None + tools: Annotated[ + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly]]], + Field(description="The tools to add this file to."), + ] = None + + +class ModifyMessageRequest(BaseModel): class Config: extra = Extra.forbid - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. If `attributes` or `chunking_strategy` are provided, they will be applied to all files in the batch. Mutually exclusive with `files`.', - max_items=500, - min_items=1, - ), - ] = None - files: Annotated[ - Optional[List[CreateVectorStoreFileRequest]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. Use this when you need to override metadata for specific files. The global `attributes` or `chunking_strategy` will be ignored and must be specified for each file. Mutually exclusive with `file_ids`.', - max_items=500, - min_items=1, + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - chunking_strategy: Optional[ChunkingStrategyRequestParam] = None - attributes: Optional[VectorStoreFileAttributes] = None -class CustomToolCallOutput(BaseModel): - type: Annotated[ - Literal['CustomToolCallOutput'], +class DeleteMessageResponse(BaseModel): + id: str + deleted: bool + object: Literal["thread.message.deleted"] + + +class ImageFile(BaseModel): + file_id: Annotated[ + str, Field( - description='The type of the custom tool call output. Always `custom_tool_call_output`.\n' + description='The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' ), ] - id: Annotated[ + detail: Annotated[ + Optional[Literal["auto", "low", "high"]], + Field( + description="Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`." + ), + ] = "auto" + + +class MessageContentImageFileObject(BaseModel): + type: Annotated[Literal["image_file"], Field(description="Always `image_file`.")] + image_file: ImageFile + + +class ImageFile1(BaseModel): + file_id: Annotated[ Optional[str], Field( - description='The unique ID of the custom tool call output in the OpenAI platform.\n' + description='The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' ), ] = None - call_id: Annotated[ - str, + detail: Annotated[ + Optional[Literal["auto", "low", "high"]], Field( - description='The call ID, used to map this custom tool call output to a custom tool call.\n' + description="Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`." ), - ] - output: Annotated[ - Union[str, List[FunctionAndCustomToolCallOutput]], + ] = "auto" + + +class MessageDeltaContentImageFileObject(BaseModel): + index: Annotated[int, Field(description="The index of the content part in the message.")] + type: Annotated[Literal["image_file"], Field(description="Always `image_file`.")] + image_file: Optional[ImageFile1] = None + + +class ImageUrl1(BaseModel): + url: Annotated[ + AnyUrl, Field( - description='The output from the custom tool call generated by your code.\nCan be a string or an list of output content.\n' + description="The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." ), ] + detail: Annotated[ + Optional[Literal["auto", "low", "high"]], + Field( + description="Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`" + ), + ] = "auto" -class EasyInputMessage(BaseModel): - role: Annotated[ - Literal['user', 'assistant', 'system', 'developer'], +class MessageContentImageUrlObject(BaseModel): + type: Annotated[Literal["image_url"], Field(description="The type of the content part.")] + image_url: ImageUrl1 + + +class ImageUrl2(BaseModel): + url: Annotated[ + Optional[str], Field( - description='The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n' + description="The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." ), - ] - content: Annotated[ - Union[str, InputMessageContentList], + ] = None + detail: Annotated[ + Optional[Literal["auto", "low", "high"]], Field( - description='Text, image, or audio input to the model, used to generate a response.\nCan also contain previous assistant responses.\n' + description="Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`." ), + ] = "auto" + + +class MessageDeltaContentImageUrlObject(BaseModel): + index: Annotated[int, Field(description="The index of the content part in the message.")] + type: Annotated[Literal["image_url"], Field(description="Always `image_url`.")] + image_url: Optional[ImageUrl2] = None + + +class MessageContentRefusalObject(BaseModel): + type: Annotated[Literal["refusal"], Field(description="Always `refusal`.")] + refusal: str + + +class MessageRequestContentTextObject(BaseModel): + type: Annotated[Literal["text"], Field(description="Always `text`.")] + text: Annotated[str, Field(description="Text content to be sent to the model")] + + +class FileCitation(BaseModel): + file_id: Annotated[str, Field(description="The ID of the specific File the citation is from.")] + + +class MessageContentTextAnnotationsFileCitationObject(BaseModel): + type: Annotated[Literal["file_citation"], Field(description="Always `file_citation`.")] + text: Annotated[ + str, + Field(description="The text in the message content that needs to be replaced."), ] - type: Annotated[ - Literal['EasyInputMessage'], - Field(description='The type of the message input. Always `message`.\n'), + file_citation: FileCitation + start_index: Annotated[int, Field(ge=0)] + end_index: Annotated[int, Field(ge=0)] + + +class FilePath(BaseModel): + file_id: Annotated[str, Field(description="The ID of the file that was generated.")] + + +class MessageContentTextAnnotationsFilePathObject(BaseModel): + type: Annotated[Literal["file_path"], Field(description="Always `file_path`.")] + text: Annotated[ + str, + Field(description="The text in the message content that needs to be replaced."), ] + file_path: FilePath + start_index: Annotated[int, Field(ge=0)] + end_index: Annotated[int, Field(ge=0)] -class EvalGraderLabelModel(GraderLabelModel): - pass +class MessageDeltaContentRefusalObject(BaseModel): + index: Annotated[int, Field(description="The index of the refusal part in the message.")] + type: Annotated[Literal["refusal"], Field(description="Always `refusal`.")] + refusal: Optional[str] = None -class EvalGraderScoreModel(GraderScoreModel): - pass_threshold: Annotated[ - Optional[float], Field(description='The threshold for the score.') +class FileCitation1(BaseModel): + file_id: Annotated[ + Optional[str], + Field(description="The ID of the specific File the citation is from."), ] = None - type: Literal['EvalGraderScoreModel'] + quote: Annotated[Optional[str], Field(description="The specific quote in the file.")] = None -class FineTuneChatCompletionRequestAssistantMessage( - ChatCompletionRequestAssistantMessage -): - weight: Annotated[ - Optional[Literal[0, 1]], - Field( - description='Controls whether the assistant message is trained against (0 or 1)' - ), - ] = None - role: Annotated[ - Literal['assistant'], - Field(description='The role of the messages author, in this case `assistant`.'), +class MessageDeltaContentTextAnnotationsFileCitationObject(BaseModel): + index: Annotated[ + int, Field(description="The index of the annotation in the text content part.") ] + type: Annotated[Literal["file_citation"], Field(description="Always `file_citation`.")] + text: Annotated[ + Optional[str], + Field(description="The text in the message content that needs to be replaced."), + ] = None + file_citation: Optional[FileCitation1] = None + start_index: Annotated[Optional[int], Field(ge=0)] = None + end_index: Annotated[Optional[int], Field(ge=0)] = None -class FineTuneChatRequestInput(BaseModel): - messages: Annotated[ - Optional[ - List[ - Union[ - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - FineTuneChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ] - ] - ], - Field(min_items=1), - ] = None - tools: Annotated[ - Optional[List[ChatCompletionTool]], - Field(description='A list of tools the model may generate JSON inputs for.'), - ] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - functions: Annotated[ - Optional[List[ChatCompletionFunctions]], - Field( - description='A list of functions the model may generate JSON inputs for.', - max_items=128, - min_items=1, - ), +class FilePath1(BaseModel): + file_id: Annotated[ + Optional[str], Field(description="The ID of the file that was generated.") ] = None -class Input4(BaseModel): - messages: Annotated[ - Optional[ - List[ - Union[ - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - FineTuneChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ] - ] - ], - Field(min_items=1), +class MessageDeltaContentTextAnnotationsFilePathObject(BaseModel): + index: Annotated[ + int, Field(description="The index of the annotation in the text content part.") + ] + type: Annotated[Literal["file_path"], Field(description="Always `file_path`.")] + text: Annotated[ + Optional[str], + Field(description="The text in the message content that needs to be replaced."), ] = None - tools: Annotated[ - Optional[List[ChatCompletionTool]], - Field(description='A list of tools the model may generate JSON inputs for.'), + file_path: Optional[FilePath1] = None + start_index: Annotated[Optional[int], Field(ge=0)] = None + end_index: Annotated[Optional[int], Field(ge=0)] = None + + +class LastError1(BaseModel): + code: Annotated[ + Literal["server_error", "rate_limit_exceeded"], + Field(description="One of `server_error` or `rate_limit_exceeded`."), + ] + message: Annotated[str, Field(description="A human-readable description of the error.")] + + +class MessageCreation(BaseModel): + message_id: Annotated[ + str, + Field(description="The ID of the message that was created by this run step."), + ] + + +class RunStepDetailsMessageCreationObject(BaseModel): + type: Annotated[Literal["message_creation"], Field(description="Always `message_creation`.")] + message_creation: MessageCreation + + +class MessageCreation1(BaseModel): + message_id: Annotated[ + Optional[str], + Field(description="The ID of the message that was created by this run step."), ] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True -class FineTunePreferenceRequestInput(BaseModel): - input: Optional[Input4] = None - preferred_output: Annotated[ - Optional[List[ChatCompletionRequestAssistantMessage]], - Field( - description='The preferred completion message for the output.', max_items=1 - ), - ] = None - non_preferred_output: Annotated[ - Optional[List[ChatCompletionRequestAssistantMessage]], - Field( - description='The non-preferred completion message for the output.', - max_items=1, - ), +class RunStepDeltaStepDetailsMessageCreationObject(BaseModel): + type: Annotated[Literal["message_creation"], Field(description="Always `message_creation`.")] + message_creation: Optional[MessageCreation1] = None + + +class RunStepDetailsToolCallsCodeOutputLogsObject(BaseModel): + type: Annotated[Literal["logs"], Field(description="Always `logs`.")] + logs: Annotated[str, Field(description="The text output from the Code Interpreter tool call.")] + + +class RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(BaseModel): + index: Annotated[int, Field(description="The index of the output in the outputs array.")] + type: Annotated[Literal["logs"], Field(description="Always `logs`.")] + logs: Annotated[ + Optional[str], + Field(description="The text output from the Code Interpreter tool call."), ] = None -class FineTuneReinforcementRequestInput(BaseModel): - messages: Annotated[ - List[ - Union[ - ChatCompletionRequestDeveloperMessage, - ChatCompletionRequestUserMessage, - FineTuneChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ] - ], - Field(min_items=1), +class Image1(BaseModel): + file_id: Annotated[ + str, Field(description="The [file](/docs/api-reference/files) ID of the image.") ] - tools: Annotated[ - Optional[List[ChatCompletionTool]], - Field(description='A list of tools the model may generate JSON inputs for.'), + + +class RunStepDetailsToolCallsCodeOutputImageObject(BaseModel): + type: Annotated[Literal["image"], Field(description="Always `image`.")] + image: Image1 + + +class Image2(BaseModel): + file_id: Annotated[ + Optional[str], + Field(description="The [file](/docs/api-reference/files) ID of the image."), ] = None -class GraderMulti(BaseModel): +class RunStepDeltaStepDetailsToolCallsCodeOutputImageObject(BaseModel): + index: Annotated[int, Field(description="The index of the output in the outputs array.")] + type: Annotated[Literal["image"], Field(description="Always `image`.")] + image: Optional[Image2] = None + + +class RunStepDetailsToolCallsFileSearchObject(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call object.")] type: Annotated[ - Literal['GraderMulti'], - Field(description='The object type, which is always `multi`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - graders: Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderLabelModel, - ] - calculate_output: Annotated[ - str, - Field(description='A formula to calculate the output based on grader results.'), + Literal["file_search"], + Field( + description="The type of tool call. This is always going to be `file_search` for this type of tool call." + ), + ] + file_search: Annotated[ + Dict[str, Any], + Field(description="For now, this is always going to be an empty object."), ] -class InputMessage(BaseModel): +class RunStepDeltaStepDetailsToolCallsFileSearchObject(BaseModel): + index: Annotated[int, Field(description="The index of the tool call in the tool calls array.")] + id: Annotated[Optional[str], Field(description="The ID of the tool call object.")] = None type: Annotated[ - Literal['InputMessage'], - Field(description='The type of the message input. Always set to `message`.\n'), - ] - role: Annotated[ - Literal['user', 'system', 'developer'], + Literal["file_search"], Field( - description='The role of the message input. One of `user`, `system`, or `developer`.\n' + description="The type of tool call. This is always going to be `file_search` for this type of tool call." ), ] - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], + file_search: Annotated[ + Dict[str, Any], + Field(description="For now, this is always going to be an empty object."), + ] + + +class Function5(BaseModel): + name: Annotated[str, Field(description="The name of the function.")] + arguments: Annotated[str, Field(description="The arguments passed to the function.")] + output: Annotated[ + str, Field( - description='The status of item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' + description="The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet." ), - ] = None - content: InputMessageContentList + ] -class InputMessageResource(InputMessage): - id: Annotated[str, Field(description='The unique ID of the message input.\n')] - type: Literal['InputMessageResource'] +class RunStepDetailsToolCallsFunctionObject(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call object.")] + type: Annotated[ + Literal["function"], + Field( + description="The type of tool call. This is always going to be `function` for this type of tool call." + ), + ] + function: Annotated[ + Function5, Field(description="The definition of the function that was called.") + ] -class ListVectorStoreFilesResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[VectorStoreFileObject] - first_id: Annotated[str, Field(example='file-abc123')] - last_id: Annotated[str, Field(example='file-abc456')] - has_more: Annotated[bool, Field(example=False)] +class Function6(BaseModel): + name: Annotated[Optional[str], Field(description="The name of the function.")] = None + arguments: Annotated[ + Optional[str], Field(description="The arguments passed to the function.") + ] = None + output: Annotated[ + Optional[str], + Field( + description="The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet." + ), + ] = None -class Delta(BaseModel): - role: Annotated[ - Optional[Literal['user', 'assistant']], +class RunStepDeltaStepDetailsToolCallsFunctionObject(BaseModel): + index: Annotated[int, Field(description="The index of the tool call in the tool calls array.")] + id: Annotated[Optional[str], Field(description="The ID of the tool call object.")] = None + type: Annotated[ + Literal["function"], Field( - description='The entity that produced the message. One of `user` or `assistant`.' + description="The type of tool call. This is always going to be `function` for this type of tool call." ), - ] = None - content: Annotated[ - Optional[List[MessageContentDelta]], - Field(description='The content of the message in array of text and/or images.'), + ] + function: Annotated[ + Optional[Function6], + Field(description="The definition of the function that was called."), ] = None -class MessageDeltaObject(BaseModel): - id: Annotated[ - str, +class VectorStoreExpirationAfter(BaseModel): + anchor: Annotated[ + Literal["last_active_at"], Field( - description='The identifier of the message, which can be referenced in API endpoints.' + description="Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." ), ] - object: Annotated[ - Literal['thread.message.delta'], - Field(description='The object type, which is always `thread.message.delta`.'), - ] - delta: Annotated[ - Delta, + days: Annotated[ + int, Field( - description='The delta containing the fields that have changed on the Message.' + description="The number of days after the anchor time that the vector store will expire.", + ge=1, + le=365, ), ] -class MessageObject(BaseModel): +class FileCounts(BaseModel): + in_progress: Annotated[ + int, + Field(description="The number of files that are currently being processed."), + ] + completed: Annotated[ + int, + Field(description="The number of files that have been successfully processed."), + ] + failed: Annotated[int, Field(description="The number of files that have failed to process.")] + cancelled: Annotated[int, Field(description="The number of files that were cancelled.")] + total: Annotated[int, Field(description="The total number of files.")] + + +class VectorStoreObject(BaseModel): id: Annotated[ str, - Field(description='The identifier, which can be referenced in API endpoints.'), + Field(description="The identifier, which can be referenced in API endpoints."), ] object: Annotated[ - Literal['thread.message'], - Field(description='The object type, which is always `thread.message`.'), + Literal["vector_store"], + Field(description="The object type, which is always `vector_store`."), ] created_at: Annotated[ int, - Field( - description='The Unix timestamp (in seconds) for when the message was created.' - ), + Field(description="The Unix timestamp (in seconds) for when the vector store was created."), ] - thread_id: Annotated[ - str, - Field( - description='The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs to.' - ), + name: Annotated[str, Field(description="The name of the vector store.")] + usage_bytes: Annotated[ + int, + Field(description="The total number of bytes used by the files in the vector store."), ] + file_counts: FileCounts status: Annotated[ - Literal['in_progress', 'incomplete', 'completed'], + Literal["expired", "in_progress", "completed"], Field( - description='The status of the message, which can be either `in_progress`, `incomplete`, or `completed`.' + description="The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use." ), ] - incomplete_details: Optional[IncompleteDetails] - completed_at: Optional[int] - incomplete_at: Optional[int] - role: Annotated[ - Literal['user', 'assistant'], + expires_after: Optional[VectorStoreExpirationAfter] = None + expires_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the vector store will expire."), + ] = None + last_active_at: Annotated[ + int, Field( - description='The entity that produced the message. One of `user` or `assistant`.' + description="The Unix timestamp (in seconds) for when the vector store was last active." ), ] - content: Annotated[ - List[MessageContent], - Field(description='The content of the message in array of text and/or images.'), + metadata: Annotated[ + Dict[str, Any], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), ] - assistant_id: Optional[str] - run_id: Optional[str] - attachments: Optional[List[Attachment1]] - metadata: Metadata -class MessageStreamEvent1(BaseModel): - event: Literal['0#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject - +class UpdateVectorStoreRequest(BaseModel): + class Config: + extra = Extra.forbid -class MessageStreamEvent2(BaseModel): - event: Literal['1#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject + name: Annotated[Optional[str], Field(description="The name of the vector store.")] = None + expires_after: Optional[VectorStoreExpirationAfter] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None -class MessageStreamEvent3(BaseModel): - event: Literal['2#-datamodel-code-generator-#-object-#-special-#'] - data: MessageDeltaObject +class ListVectorStoresResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[VectorStoreObject] + first_id: Annotated[str, Field(example="vs_abc123")] + last_id: Annotated[str, Field(example="vs_abc456")] + has_more: Annotated[bool, Field(example=False)] -class MessageStreamEvent4(BaseModel): - event: Literal['3#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject +class DeleteVectorStoreResponse(BaseModel): + id: str + deleted: bool + object: Literal["vector_store.deleted"] -class MessageStreamEvent5(BaseModel): - event: Literal['4#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject +class LastError2(BaseModel): + code: Annotated[ + Literal["server_error", "unsupported_file", "invalid_file"], + Field(description="One of `server_error` or `rate_limit_exceeded`."), + ] + message: Annotated[str, Field(description="A human-readable description of the error.")] -class MessageStreamEvent(BaseModel): - __root__: Annotated[ - Union[ - MessageStreamEvent1, - MessageStreamEvent2, - MessageStreamEvent3, - MessageStreamEvent4, - MessageStreamEvent5, - ], - Field(discriminator='event'), - ] +class OtherChunkingStrategyResponseParam(BaseModel): + class Config: + extra = Extra.forbid + type: Annotated[Literal["other"], Field(description="Always `other`.")] -class ModelIdsResponses(BaseModel): - __root__: Annotated[ - Union[ - ModelIdsShared, - Literal[ - 'o1-pro', - 'o1-pro-2025-03-19', - 'o3-pro', - 'o3-pro-2025-06-10', - 'o3-deep-research', - 'o3-deep-research-2025-06-26', - 'o4-mini-deep-research', - 'o4-mini-deep-research-2025-06-26', - 'computer-use-preview', - 'computer-use-preview-2025-03-11', - 'gpt-5-codex', - 'gpt-5-pro', - 'gpt-5-pro-2025-10-06', - ], - ], - Field(example='gpt-4o'), - ] +class StaticChunkingStrategy(BaseModel): + class Config: + extra = Extra.forbid -class OutputMessage(BaseModel): - id: Annotated[str, Field(description='The unique ID of the output message.\n')] - type: Annotated[ - Literal['OutputMessage'], - Field(description='The type of the output message. Always `message`.\n'), - ] - role: Annotated[ - Literal['assistant'], - Field(description='The role of the output message. Always `assistant`.\n'), - ] - content: Annotated[ - List[OutputMessageContent], - Field(description='The content of the output message.\n'), + max_chunk_size_tokens: Annotated[ + int, + Field( + description="The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.", + ge=100, + le=4096, + ), ] - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], + chunk_overlap_tokens: Annotated[ + int, Field( - description='The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n' + description="The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" ), ] -class Prompt3(BaseModel): - id: Annotated[ - str, Field(description='The unique identifier of the prompt template to use.') - ] - version: Optional[str] = None - variables: Optional[ResponsePromptVariables] = None +class AutoChunkingStrategyRequestParam(BaseModel): + class Config: + extra = Extra.forbid + + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class Prompt2(BaseModel): - __root__: Optional[Prompt3] +class StaticChunkingStrategyRequestParam(BaseModel): + class Config: + extra = Extra.forbid + + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: StaticChunkingStrategy -class RealtimeConversationItem(BaseModel): +class ChunkingStrategyRequestParam(BaseModel): __root__: Annotated[ - Union[ - RealtimeConversationItemMessageSystem, - RealtimeConversationItemMessageUser, - RealtimeConversationItemMessageAssistant, - RealtimeConversationItemFunctionCall, - RealtimeConversationItemFunctionCallOutput, - RealtimeMCPApprovalResponse, - RealtimeMCPListTools, - RealtimeMCPToolCall, - RealtimeMCPApprovalRequest, - ], + Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam], Field( - description='A single item within a Realtime conversation.', - discriminator='type', + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." ), ] -class RealtimeResponse(BaseModel): - id: Annotated[ - Optional[str], - Field(description='The unique ID of the response, will look like `resp_1234`.'), - ] = None - object: Annotated[ +class CreateVectorStoreFileRequest(BaseModel): + class Config: + extra = Extra.forbid + + file_id: Annotated[ str, - Field(const=True, description='The object type, must be `realtime.response`.'), - ] = 'realtime.response' - status: Annotated[ - Optional[ - Literal['completed', 'cancelled', 'failed', 'incomplete', 'in_progress'] - ], - Field( - description='The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n' - ), - ] = None - status_details: Annotated[ - Optional[StatusDetails1], - Field(description='Additional details about the status.'), - ] = None - output: Annotated[ - Optional[List[RealtimeConversationItem]], - Field(description='The list of output items generated by the response.'), - ] = None - metadata: Optional[Metadata] = None - audio: Annotated[ - Optional[Audio3], Field(description='Configuration for audio output.') - ] = None - usage: Annotated[ - Optional[Usage4], - Field( - description='Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n' - ), - ] = None - conversation_id: Annotated[ - Optional[str], - Field( - description='Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nautomatically by VAD the response will be added to the default conversation\n' - ), - ] = None - output_modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model used to respond, currently the only possible values are\n`[\\"audio\\"]`, `[\\"text\\"]`. Audio output always include a text transcript. Setting the\noutput to mode `text` will disable audio output from the model.\n' - ), - ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n' + description="A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files." ), - ] = None + ] + chunking_strategy: Optional[ChunkingStrategyRequestParam] = None -class RealtimeResponseCreateParams(BaseModel): - output_modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model used to respond, currently the only possible values are\n`[\\"audio\\"]`, `[\\"text\\"]`. Audio output always include a text transcript. Setting the\noutput to mode `text` will disable audio output from the model.\n' - ), - ] = None - instructions: Annotated[ - Optional[str], - Field( - description='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.\nNote 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.\n' - ), - ] = None - audio: Annotated[ - Optional[Audio4], Field(description='Configuration for audio input and output.') - ] = None - tools: Annotated[ - Optional[List[Union[RealtimeFunctionTool, MCPTool]]], - Field(description='Tools available to the model.'), - ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), - ] = None - conversation: Annotated[ - Optional[Union[str, Literal['auto', 'none']]], - Field( - description='Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which\nwill not add items to default conversation.\n' - ), - ] = None - metadata: Optional[Metadata] = None - prompt: Optional[Prompt2] = None - input: Annotated[ - Optional[List[RealtimeConversationItem]], - Field( - description='Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items that previously appeared in the session\nusing their id.\n' - ), - ] = None +class DeleteVectorStoreFileResponse(BaseModel): + id: str + deleted: bool + object: Literal["vector_store.file.deleted"] -class RealtimeServerEventConversationItemAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.added'], - Field( - const=True, description='The event type, must be `conversation.item.added`.' - ), +class FileCounts1(BaseModel): + in_progress: Annotated[ + int, + Field(description="The number of files that are currently being processed."), ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem + completed: Annotated[int, Field(description="The number of files that have been processed.")] + failed: Annotated[int, Field(description="The number of files that have failed to process.")] + cancelled: Annotated[int, Field(description="The number of files that where cancelled.")] + total: Annotated[int, Field(description="The total number of files.")] -class RealtimeServerEventConversationItemCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.created'], +class VectorStoreFileBatchObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["vector_store.files_batch"], + Field(description="The object type, which is always `vector_store.file_batch`."), + ] + created_at: Annotated[ + int, Field( - const=True, - description='The event type, must be `conversation.item.created`.', + description="The Unix timestamp (in seconds) for when the vector store files batch was created." ), ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem - - -class RealtimeServerEventConversationItemDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.done'], + vector_store_id: Annotated[ + str, + Field( + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to." + ), + ] + status: Annotated[ + Literal["in_progress", "completed", "cancelled", "failed"], Field( - const=True, description='The event type, must be `conversation.item.done`.' + description="The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`." ), ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem + file_counts: FileCounts1 -class RealtimeServerEventConversationItemRetrieved(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.retrieved'], +class CreateVectorStoreFileBatchRequest(BaseModel): + class Config: + extra = Extra.forbid + + file_ids: Annotated[ + List[str], Field( - const=True, - description='The event type, must be `conversation.item.retrieved`.', + description="A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.", + max_items=500, + min_items=1, ), ] - item: RealtimeConversationItem + chunking_strategy: Optional[ChunkingStrategyRequestParam] = None -class RealtimeServerEventResponseCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.created'], - Field(const=True, description='The event type, must be `response.created`.'), - ] - response: RealtimeResponse +class ThreadStreamEvent1(BaseModel): + event: Literal["thread.created"] + data: ThreadObject -class RealtimeServerEventResponseDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.done'], - Field(const=True, description='The event type, must be `response.done`.'), - ] - response: RealtimeResponse +class ThreadStreamEvent(BaseModel): + __root__: ThreadStreamEvent1 -class RealtimeServerEventResponseOutputItemAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_item.added'], - Field( - const=True, - description='The event type, must be `response.output_item.added`.', - ), - ] - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') - ] - item: RealtimeConversationItem +class ErrorEvent(BaseModel): + event: Literal["error"] + data: Error -class RealtimeServerEventResponseOutputItemDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_item.done'], - Field( - const=True, - description='The event type, must be `response.output_item.done`.', - ), - ] - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') - ] - item: RealtimeConversationItem +class DoneEvent(BaseModel): + event: Literal["done"] + data: Literal["[DONE]"] -class RealtimeSession(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='Unique identifier for the session that looks like `sess_1234567890abcdef`.\n' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.session']], - Field(description='The object type. Always `realtime.session`.'), - ] = None - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' - ), - ] = None - model: Annotated[ - Optional[ - Literal[ - 'gpt-realtime', - 'gpt-realtime-2025-08-28', - 'gpt-4o-realtime-preview', - 'gpt-4o-realtime-preview-2024-10-01', - 'gpt-4o-realtime-preview-2024-12-17', - 'gpt-4o-realtime-preview-2025-06-03', - 'gpt-4o-mini-realtime-preview', - 'gpt-4o-mini-realtime-preview-2024-12-17', - 'gpt-realtime-mini', - 'gpt-realtime-mini-2025-10-06', - 'gpt-audio-mini', - 'gpt-audio-mini-2025-10-06', - ] - ], - Field(description='The Realtime model used for this session.\n'), +class Datum(BaseModel): + code: Annotated[ + Optional[str], Field(description="An error code identifying the error type.") ] = None - instructions: Annotated[ + message: Annotated[ Optional[str], - Field( - description='The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. "be extremely succinct", "act friendly", "here are examples of good\nresponses") and on audio behavior (e.g. "talk quickly", "inject emotion\ninto your voice", "laugh frequently"). The instructions are not\nguaranteed to be followed by the model, but they provide guidance to the\nmodel on the desired behavior.\n\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n' - ), - ] = None - voice: Annotated[ - Optional[VoiceIdsShared], - Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' - ), - ] = None - input_audio_format: Annotated[ - Literal['pcm16', 'g711_ulaw', 'g711_alaw'], - Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n' - ), - ] = 'pcm16' - output_audio_format: Annotated[ - Literal['pcm16', 'g711_ulaw', 'g711_alaw'], - Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, output audio is sampled at a rate of 24kHz.\n' - ), - ] = 'pcm16' - input_audio_transcription: Optional[AudioTranscription] = None - turn_detection: Optional[RealtimeTurnDetection] = None - input_audio_noise_reduction: Annotated[ - Optional[InputAudioNoiseReduction], - Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' - ), - ] = None - speed: Annotated[ - float, - Field( - description="The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n", - ge=0.25, - le=1.5, - ), - ] = 1 - tracing: Optional[Union[Literal['auto'], Tracing]] = None - tools: Annotated[ - Optional[List[RealtimeFunctionTool]], - Field(description='Tools (functions) available to the model.'), + Field(description="A human-readable message providing more details about the error."), ] = None - tool_choice: Annotated[ - str, - Field( - description='How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n' - ), - ] = 'auto' - temperature: Annotated[ - float, - Field( - description='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.\n' - ), - ] = 0.8 - max_response_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), + param: Annotated[ + Optional[str], + Field(description="The name of the parameter that caused the error, if applicable."), ] = None - expires_at: Annotated[ + line: Annotated[ Optional[int], Field( - description='Expiration timestamp for the session, in seconds since epoch.' + description="The line number of the input file where the error occurred, if applicable." ), ] = None - prompt: Optional[Prompt2] = None - include: Optional[List[Literal['item.input_audio_transcription.logprobs']]] = None -class RealtimeSessionCreateRequest(BaseModel): - client_secret: Annotated[ - ClientSecret, Field(description='Ephemeral key returned by the API.') - ] - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' - ), - ] = None - instructions: Annotated[ - Optional[str], - Field( - description='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.\nNote 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.\n' - ), - ] = None - voice: Annotated[ - Optional[VoiceIdsShared], - Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' - ), - ] = None - input_audio_format: Annotated[ - Optional[str], - Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' - ), - ] = None - output_audio_format: Annotated[ - Optional[str], - Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' - ), - ] = None - input_audio_transcription: Annotated[ - Optional[InputAudioTranscription], - Field( - description='Configuration for input audio transcription, defaults to off and can be\nset to `null` to turn off once on. Input audio transcription is not native\nto the model, since the model consumes audio directly. Transcription runs\nasynchronously and should be treated as rough guidance\nrather than the representation understood by the model.\n' - ), - ] = None - speed: Annotated[ - float, - Field( - description="The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n", - ge=0.25, - le=1.5, - ), - ] = 1 - tracing: Annotated[ - Optional[Union[Literal['auto'], Tracing]], - Field( - description='Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n', - title='Tracing Configuration', - ), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection], - Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' - ), - ] = None - tools: Annotated[ - Optional[List[Tool2]], - Field(description='Tools (functions) available to the model.'), - ] = None - tool_choice: Annotated[ - Optional[str], - Field( - description='How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n' - ), - ] = None - temperature: Annotated[ - Optional[float], - Field( - description='Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n' - ), - ] = None - max_response_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), +class Errors(BaseModel): + object: Annotated[ + Optional[str], Field(description="The object type, which is always `list`.") ] = None - truncation: Optional[RealtimeTruncation] = None - prompt: Optional[Prompt2] = None + data: Optional[List[Datum]] = None -class RealtimeSessionCreateRequestGA(BaseModel): - type: Annotated[ - Literal['RealtimeSessionCreateRequestGA'], - Field( - description='The type of session to create. Always `realtime` for the Realtime API.\n' - ), +class RequestCounts(BaseModel): + total: Annotated[int, Field(description="Total number of requests in the batch.")] + completed: Annotated[ + int, + Field(description="Number of requests that have been completed successfully."), ] - output_modalities: Annotated[ - List[Literal['text', 'audio']], - Field( - description='The set of modalities the model can respond with. It defaults to `["audio"]`, indicating\nthat the model will respond with audio plus a transcript. `["text"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n' - ), - ] = ['audio'] - model: Annotated[ - Optional[ - Union[ - str, - Literal[ - 'gpt-realtime', - 'gpt-realtime-2025-08-28', - 'gpt-4o-realtime-preview', - 'gpt-4o-realtime-preview-2024-10-01', - 'gpt-4o-realtime-preview-2024-12-17', - 'gpt-4o-realtime-preview-2025-06-03', - 'gpt-4o-mini-realtime-preview', - 'gpt-4o-mini-realtime-preview-2024-12-17', - 'gpt-realtime-mini', - 'gpt-realtime-mini-2025-10-06', - 'gpt-audio-mini', - 'gpt-audio-mini-2025-10-06', - ], - ] + failed: Annotated[int, Field(description="Number of requests that have failed.")] + + +class Batch(BaseModel): + id: str + object: Annotated[ + Literal["batch"], Field(description="The object type, which is always `batch`.") + ] + endpoint: Annotated[str, Field(description="The OpenAI API endpoint used by the batch.")] + errors: Optional[Errors] = None + input_file_id: Annotated[str, Field(description="The ID of the input file for the batch.")] + completion_window: Annotated[ + str, + Field(description="The time frame within which the batch should be processed."), + ] + status: Annotated[ + Literal[ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled", ], - Field(description='The Realtime model used for this session.\n'), - ] = None - instructions: Annotated[ + Field(description="The current status of the batch."), + ] + output_file_id: Annotated[ Optional[str], Field( - description='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.\n\nNote 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.\n' + description="The ID of the file containing the outputs of successfully executed requests." ), ] = None - audio: Annotated[ - Optional[Audio5], - Field(description='Configuration for input and output audio.\n'), + error_file_id: Annotated[ + Optional[str], + Field(description="The ID of the file containing the outputs of requests with errors."), ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' - ), + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the batch was created."), + ] + in_progress_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch started processing."), ] = None - tracing: Annotated[ - Optional[Union[Literal['auto'], Tracing2]], - Field( - description='Realtime API can write session traces to the [Traces Dashboard](/logs?api=traces). Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n', - title='Tracing Configuration', - ), + expires_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch will expire."), ] = None - tools: Annotated[ - Optional[List[Tools2]], Field(description='Tools available to the model.') + finalizing_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch started finalizing."), ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), + completed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch was completed."), ] = None - truncation: Optional[RealtimeTruncation] = None - prompt: Optional[Prompt2] = None - - -class RealtimeSessionCreateResponseGA(BaseModel): - client_secret: Annotated[ - ClientSecret1, Field(description='Ephemeral key returned by the API.') - ] - type: Annotated[ - Literal['RealtimeSessionCreateResponseGA'], - Field( - description='The type of session to create. Always `realtime` for the Realtime API.\n' - ), - ] - output_modalities: Annotated[ - List[Literal['text', 'audio']], - Field( - description='The set of modalities the model can respond with. It defaults to `["audio"]`, indicating\nthat the model will respond with audio plus a transcript. `["text"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n' - ), - ] = ['audio'] - model: Annotated[ - Optional[ - Union[ - str, - Literal[ - 'gpt-realtime', - 'gpt-realtime-2025-08-28', - 'gpt-4o-realtime-preview', - 'gpt-4o-realtime-preview-2024-10-01', - 'gpt-4o-realtime-preview-2024-12-17', - 'gpt-4o-realtime-preview-2025-06-03', - 'gpt-4o-mini-realtime-preview', - 'gpt-4o-mini-realtime-preview-2024-12-17', - 'gpt-realtime-mini', - 'gpt-realtime-mini-2025-10-06', - 'gpt-audio-mini', - 'gpt-audio-mini-2025-10-06', - ], - ] - ], - Field(description='The Realtime model used for this session.\n'), + failed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch failed."), ] = None - instructions: Annotated[ - Optional[str], - Field( - description='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.\n\nNote 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.\n' - ), + expired_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch expired."), ] = None - audio: Annotated[ - Optional[Audio7], - Field(description='Configuration for input and output audio.\n'), + cancelling_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch started cancelling."), ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' - ), + cancelled_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch was cancelled."), ] = None - tracing: Optional[Union[Literal['auto'], Tracing4]] = None - tools: Annotated[ - Optional[List[Union[RealtimeFunctionTool, MCPTool]]], - Field(description='Tools available to the model.'), + request_counts: Annotated[ + Optional[RequestCounts], + Field(description="The request counts for different statuses within the batch."), ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - truncation: Optional[RealtimeTruncation] = None - prompt: Optional[Prompt2] = None - -class ResponseTextParam(BaseModel): - format: Optional[TextResponseFormatConfiguration] = None - verbosity: Optional[Verbosity] = None - -class RunGraderRequest(BaseModel): - grader: Annotated[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ], +class BatchRequestInput(BaseModel): + custom_id: Annotated[ + Optional[str], Field( - description='The grader used for the fine-tuning job.', discriminator='type' + description="A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch." ), - ] - item: Annotated[ - Optional[Dict[str, Any]], + ] = None + method: Annotated[ + Optional[Literal["POST"]], Field( - description='The dataset item provided to the grader. This will be used to populate \nthe `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details. \n' + description="The HTTP method to be used for the request. Currently only `POST` is supported." ), ] = None - model_sample: Annotated[ - str, + url: Annotated[ + Optional[str], Field( - description='The model sample to be evaluated. This value will be used to populate \nthe `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details.\nThe `output_json` variable will be populated if the model sample is a \nvalid JSON string.\n \n' + description="The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported." ), - ] + ] = None -class RunStepDeltaStepDetailsToolCallsObject(BaseModel): - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsObject'], - Field(description='Always `tool_calls`.'), - ] - tool_calls: Annotated[ - Optional[List[RunStepDeltaStepDetailsToolCall]], +class Response(BaseModel): + status_code: Annotated[ + Optional[int], Field(description="The HTTP status code of the response") + ] = None + request_id: Annotated[ + Optional[str], Field( - description='An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n' + description="An unique identifier for the OpenAI API request. Please include this request ID when contacting support." ), ] = None + body: Annotated[ + Optional[Dict[str, Any]], Field(description="The JSON body of the response") + ] = None -class RunStepDetailsToolCallsObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsToolCallsObject'], - Field(description='Always `tool_calls`.'), - ] - tool_calls: Annotated[ - List[RunStepDetailsToolCall], - Field( - description='An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n' - ), - ] +class Error2(BaseModel): + code: Annotated[Optional[str], Field(description="A machine-readable error code.")] = None + message: Annotated[Optional[str], Field(description="A human-readable error message.")] = None -class RunStepObject(BaseModel): - id: Annotated[ - str, - Field( - description='The identifier of the run step, which can be referenced in API endpoints.' - ), - ] - object: Annotated[ - Literal['thread.run.step'], - Field(description='The object type, which is always `thread.run.step`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the run step was created.' - ), - ] - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated with the run step.' - ), - ] - thread_id: Annotated[ - str, - Field( - description='The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run.' - ), - ] - run_id: Annotated[ - str, - Field( - description='The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a part of.' - ), - ] - type: Annotated[ - Literal['message_creation', 'tool_calls'], +class BatchRequestOutput(BaseModel): + id: Optional[str] = None + custom_id: Annotated[ + Optional[str], Field( - description='The type of run step, which can be either `message_creation` or `tool_calls`.' + description="A developer-provided per-request id that will be used to match outputs to inputs." ), - ] - status: Annotated[ - Literal['in_progress', 'cancelled', 'failed', 'completed', 'expired'], + ] = None + response: Optional[Response] = None + error: Annotated[ + Optional[Error2], Field( - description='The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`.' + description="For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure." ), - ] - step_details: Annotated[ - Union[RunStepDetailsMessageCreationObject, RunStepDetailsToolCallsObject], - Field(description='The details of the run step.', discriminator='type'), - ] - last_error: Optional[LastError1] - expired_at: Optional[int] - cancelled_at: Optional[int] - failed_at: Optional[int] - completed_at: Optional[int] - metadata: Metadata - usage: RunStepCompletionUsage + ] = None -class RunStepStreamEvent1(BaseModel): - event: Literal['0#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class ListBatchesResponse(BaseModel): + data: List[Batch] + first_id: Annotated[Optional[str], Field(example="batch_abc123")] = None + last_id: Annotated[Optional[str], Field(example="batch_abc456")] = None + has_more: bool + object: Literal["list"] -class RunStepStreamEvent2(BaseModel): - event: Literal['1#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorServiceAccount(BaseModel): + id: Annotated[Optional[str], Field(description="The service account id.")] = None -class RunStepStreamEvent4(BaseModel): - event: Literal['3#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorUser(BaseModel): + id: Annotated[Optional[str], Field(description="The user id.")] = None + email: Annotated[Optional[str], Field(description="The user email.")] = None -class RunStepStreamEvent5(BaseModel): - event: Literal['4#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorApiKey(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking id of the API key.")] = None + type: Annotated[ + Optional[Literal["user", "service_account"]], + Field(description="The type of API key. Can be either `user` or `service_account`."), + ] = None + user: Optional[AuditLogActorUser] = None + service_account: Optional[AuditLogActorServiceAccount] = None -class RunStepStreamEvent6(BaseModel): - event: Literal['5#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorSession(BaseModel): + user: Optional[AuditLogActorUser] = None + ip_address: Annotated[ + Optional[str], + Field(description="The IP address from which the action was performed."), + ] = None -class RunStepStreamEvent7(BaseModel): - event: Literal['6#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActor(BaseModel): + type: Annotated[ + Optional[Literal["session", "api_key"]], + Field(description="The type of actor. Is either `session` or `api_key`."), + ] = None + session: Optional[AuditLogActorSession] = None + api_key: Optional[AuditLogActorApiKey] = None -class Tool(BaseModel): +class AuditLogEventType(BaseModel): __root__: Annotated[ - Union[ - FunctionTool, - FileSearchTool, - ComputerUsePreviewTool, - WebSearchTool, - MCPTool, - CodeInterpreterTool, - ImageGenTool, - LocalShellToolParam, - FunctionShellToolParam, - CustomToolParam, - WebSearchPreviewTool, - ApplyPatchToolParam, + Literal[ + "api_key.created", + "api_key.updated", + "api_key.deleted", + "invite.sent", + "invite.accepted", + "invite.deleted", + "login.succeeded", + "login.failed", + "logout.succeeded", + "logout.failed", + "organization.updated", + "project.created", + "project.updated", + "project.archived", + "service_account.created", + "service_account.updated", + "service_account.deleted", + "user.added", + "user.updated", + "user.deleted", ], - Field( - description='A tool that can be used to generate a response.\n', - discriminator='type', - ), + Field(description="The event type."), ] -class ToolsArray(BaseModel): - __root__: Annotated[ - List[Tool], - Field( - description="An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n [built-in tools](https://platform.openai.com/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" - ), - ] +class Project(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + name: Annotated[Optional[str], Field(description="The project title.")] = None -class UsageResponse(BaseModel): - object: Literal['page'] - data: List[UsageTimeBucket] - has_more: bool - next_page: str +class Data(BaseModel): + scopes: Annotated[ + Optional[List[str]], + Field(description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`'), + ] = None -class ValidateGraderRequest(BaseModel): - grader: Annotated[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ], - Field(description='The grader used for the fine-tuning job.'), - ] +class ApiKeyCreated(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking ID of the API key.")] = None + data: Annotated[ + Optional[Data], Field(description="The payload used to create the API key.") + ] = None -class ValidateGraderResponse(BaseModel): - grader: Annotated[ - Optional[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ] - ], - Field(description='The grader used for the fine-tuning job.'), +class ChangesRequested(BaseModel): + scopes: Annotated[ + Optional[List[str]], + Field(description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`'), ] = None -class AssistantTool(BaseModel): - __root__: Annotated[ - Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], - Field(discriminator='type'), - ] +class ApiKeyUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking ID of the API key.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested], + Field(description="The payload used to update the API key."), + ] = None -class CreateThreadAndRunRequestWithoutStream(BaseModel): - class Config: - extra = Extra.forbid +class ApiKeyDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking ID of the API key.")] = None - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' - ), - ] - thread: Optional[CreateThreadRequest] = None - model: Annotated[ - Optional[ - Union[ - Optional[str], - Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ], - ] - ], - Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' - ), + +class Data1(BaseModel): + email: Annotated[Optional[str], Field(description="The email invited to the organization.")] = ( + None + ) + role: Annotated[ + Optional[str], + Field(description="The role the email was invited to be. Is either `owner` or `member`."), ] = None - instructions: Annotated[ + + +class InviteSent(BaseModel): + id: Annotated[Optional[str], Field(description="The ID of the invite.")] = None + data: Annotated[ + Optional[Data1], Field(description="The payload used to create the invite.") + ] = None + + +class InviteAccepted(BaseModel): + id: Annotated[Optional[str], Field(description="The ID of the invite.")] = None + + +class InviteDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The ID of the invite.")] = None + + +class LoginFailed(BaseModel): + error_code: Annotated[Optional[str], Field(description="The error code of the failure.")] = None + error_message: Annotated[ + Optional[str], Field(description="The error message of the failure.") + ] = None + + +class LogoutFailed(BaseModel): + error_code: Annotated[Optional[str], Field(description="The error code of the failure.")] = None + error_message: Annotated[ + Optional[str], Field(description="The error message of the failure.") + ] = None + + +class Settings(BaseModel): + threads_ui_visibility: Annotated[ Optional[str], Field( - description='Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.' + description="Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`." ), ] = None - tools: Annotated[ - Optional[List[AssistantTool]], + usage_dashboard_visibility: Annotated[ + Optional[str], Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', - max_items=20, + description="Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`." ), ] = None - tool_resources: Annotated[ - Optional[ToolResources7], - Field( - description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" - ), + + +class ChangesRequested1(BaseModel): + title: Annotated[Optional[str], Field(description="The organization title.")] = None + description: Annotated[Optional[str], Field(description="The organization description.")] = None + name: Annotated[Optional[str], Field(description="The organization name.")] = None + settings: Optional[Settings] = None + + +class OrganizationUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The organization ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested1], + Field(description="The payload used to update the organization settings."), ] = None - metadata: Optional[Metadata] = None - temperature: Annotated[ - Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - example=1, - ge=0.0, - le=2.0, - ), - ] = 1 - top_p: Annotated[ - Optional[float], - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - example=1, - ge=0.0, - le=1.0, - ), - ] = 1 - max_prompt_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), + + +class Data2(BaseModel): + name: Annotated[Optional[str], Field(description="The project name.")] = None + title: Annotated[ + Optional[str], + Field(description="The title of the project as seen on the dashboard."), ] = None - max_completion_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), + + +class ProjectCreated(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + data: Annotated[ + Optional[Data2], Field(description="The payload used to create the project.") ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None -class CreateRunRequestWithoutStream(BaseModel): - class Config: - extra = Extra.forbid +class ChangesRequested2(BaseModel): + title: Annotated[ + Optional[str], + Field(description="The title of the project as seen on the dashboard."), + ] = None - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' - ), - ] - model: Annotated[ - Optional[Union[Optional[str], AssistantSupportedModels]], - Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' - ), + +class ProjectUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested2], + Field(description="The payload used to update the project."), ] = None - reasoning_effort: Optional[ReasoningEffort] = None - instructions: Annotated[ + + +class ProjectArchived(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + + +class Data3(BaseModel): + role: Annotated[ Optional[str], - Field( - description='Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.' - ), + Field(description="The role of the service account. Is either `owner` or `member`."), ] = None - additional_instructions: Annotated[ + + +class ServiceAccountCreated(BaseModel): + id: Annotated[Optional[str], Field(description="The service account ID.")] = None + data: Annotated[ + Optional[Data3], + Field(description="The payload used to create the service account."), + ] = None + + +class ChangesRequested3(BaseModel): + role: Annotated[ Optional[str], - Field( - description='Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.' - ), + Field(description="The role of the service account. Is either `owner` or `member`."), ] = None - additional_messages: Annotated[ - Optional[List[CreateMessageRequest]], - Field( - description='Adds additional messages to the thread before creating the run.' - ), + + +class ServiceAccountUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The service account ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested3], + Field(description="The payload used to updated the service account."), ] = None - tools: Annotated[ - Optional[List[AssistantTool]], - Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', - max_items=20, - ), + + +class ServiceAccountDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The service account ID.")] = None + + +class Data4(BaseModel): + role: Annotated[ + Optional[str], + Field(description="The role of the user. Is either `owner` or `member`."), ] = None - metadata: Optional[Metadata] = None - temperature: Annotated[ - Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - example=1, - ge=0.0, - le=2.0, - ), - ] = 1 - top_p: Annotated[ - Optional[float], - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - example=1, - ge=0.0, - le=1.0, - ), - ] = 1 - max_prompt_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), + + +class UserAdded(BaseModel): + id: Annotated[Optional[str], Field(description="The user ID.")] = None + data: Annotated[ + Optional[Data4], + Field(description="The payload used to add the user to the project."), ] = None - max_completion_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), + + +class ChangesRequested4(BaseModel): + role: Annotated[ + Optional[str], + Field(description="The role of the user. Is either `owner` or `member`."), ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None -class RunStepDeltaObjectDelta(BaseModel): - step_details: Annotated[ - Optional[ - Union[ - RunStepDeltaStepDetailsMessageCreationObject, - RunStepDeltaStepDetailsToolCallsObject, - ] - ], - Field(description='The details of the run step.', discriminator='type'), +class UserUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested4], + Field(description="The payload used to update the user."), ] = None -class AssistantObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['assistant'], - Field(description='The object type, which is always `assistant`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the assistant was created.' - ), - ] - name: Optional[Name] - description: Optional[Description] - model: Annotated[ - str, - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n' - ), - ] - instructions: Optional[Instructions] - tools: Annotated[ - List[AssistantTool], - Field( - description='A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n', - max_items=128, - ), - ] - tool_resources: Optional[ToolResources] = None - metadata: Metadata - temperature: Optional[Temperature] = None - top_p: Optional[TopP] = None - response_format: Optional[AssistantsApiResponseFormatOption] = None +class UserDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The user ID.")] = None class AuditLog(BaseModel): - id: Annotated[str, Field(description='The ID of this log.')] + id: Annotated[str, Field(description="The ID of this log.")] type: AuditLogEventType - effective_at: Annotated[ - int, Field(description='The Unix timestamp (in seconds) of the event.') - ] + effective_at: Annotated[int, Field(description="The Unix timestamp (in seconds) of the event.")] project: Annotated[ Optional[Project], Field( - description='The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project.' + description="The project that the action was scoped to. Absent for actions not scoped to projects." ), ] = None actor: AuditLogActor api_key_created: Annotated[ Optional[ApiKeyCreated], Field( - alias='api_key.created', - description='The details for events with this `type`.', + alias="api_key.created", + description="The details for events with this `type`.", ), ] = None api_key_updated: Annotated[ Optional[ApiKeyUpdated], Field( - alias='api_key.updated', - description='The details for events with this `type`.', + alias="api_key.updated", + description="The details for events with this `type`.", ), ] = None api_key_deleted: Annotated[ Optional[ApiKeyDeleted], Field( - alias='api_key.deleted', - description='The details for events with this `type`.', + alias="api_key.deleted", + description="The details for events with this `type`.", ), ] = None - checkpoint_permission_created: Annotated[ - Optional[CheckpointPermissionCreated], - Field( - alias='checkpoint.permission.created', - description='The project and fine-tuned model checkpoint that the checkpoint permission was created for.', - ), + invite_sent: Annotated[ + Optional[InviteSent], + Field(alias="invite.sent", description="The details for events with this `type`."), ] = None - checkpoint_permission_deleted: Annotated[ - Optional[CheckpointPermissionDeleted], + invite_accepted: Annotated[ + Optional[InviteAccepted], Field( - alias='checkpoint.permission.deleted', - description='The details for events with this `type`.', + alias="invite.accepted", + description="The details for events with this `type`.", ), ] = None - external_key_registered: Annotated[ - Optional[ExternalKeyRegistered], + invite_deleted: Annotated[ + Optional[InviteDeleted], Field( - alias='external_key.registered', - description='The details for events with this `type`.', + alias="invite.deleted", + description="The details for events with this `type`.", ), ] = None - external_key_removed: Annotated[ - Optional[ExternalKeyRemoved], - Field( - alias='external_key.removed', - description='The details for events with this `type`.', - ), + login_failed: Annotated[ + Optional[LoginFailed], + Field(alias="login.failed", description="The details for events with this `type`."), ] = None - group_created: Annotated[ - Optional[GroupCreated], + logout_failed: Annotated[ + Optional[LogoutFailed], Field( - alias='group.created', - description='The details for events with this `type`.', + alias="logout.failed", + description="The details for events with this `type`.", ), ] = None - group_updated: Annotated[ - Optional[GroupUpdated], + organization_updated: Annotated[ + Optional[OrganizationUpdated], Field( - alias='group.updated', - description='The details for events with this `type`.', + alias="organization.updated", + description="The details for events with this `type`.", ), ] = None - group_deleted: Annotated[ - Optional[GroupDeleted], + project_created: Annotated[ + Optional[ProjectCreated], Field( - alias='group.deleted', - description='The details for events with this `type`.', + alias="project.created", + description="The details for events with this `type`.", ), ] = None - scim_enabled: Annotated[ - Optional[ScimEnabled], + project_updated: Annotated[ + Optional[ProjectUpdated], Field( - alias='scim.enabled', description='The details for events with this `type`.' + alias="project.updated", + description="The details for events with this `type`.", ), ] = None - scim_disabled: Annotated[ - Optional[ScimDisabled], + project_archived: Annotated[ + Optional[ProjectArchived], Field( - alias='scim.disabled', - description='The details for events with this `type`.', + alias="project.archived", + description="The details for events with this `type`.", ), ] = None - invite_sent: Annotated[ - Optional[InviteSent], + service_account_created: Annotated[ + Optional[ServiceAccountCreated], Field( - alias='invite.sent', description='The details for events with this `type`.' + alias="service_account.created", + description="The details for events with this `type`.", ), ] = None - invite_accepted: Annotated[ - Optional[InviteAccepted], + service_account_updated: Annotated[ + Optional[ServiceAccountUpdated], Field( - alias='invite.accepted', - description='The details for events with this `type`.', + alias="service_account.updated", + description="The details for events with this `type`.", ), ] = None - invite_deleted: Annotated[ - Optional[InviteDeleted], + service_account_deleted: Annotated[ + Optional[ServiceAccountDeleted], Field( - alias='invite.deleted', - description='The details for events with this `type`.', + alias="service_account.deleted", + description="The details for events with this `type`.", ), ] = None - ip_allowlist_created: Annotated[ - Optional[IpAllowlistCreated], - Field( - alias='ip_allowlist.created', - description='The details for events with this `type`.', - ), + user_added: Annotated[ + Optional[UserAdded], + Field(alias="user.added", description="The details for events with this `type`."), ] = None - ip_allowlist_updated: Annotated[ - Optional[IpAllowlistUpdated], - Field( - alias='ip_allowlist.updated', - description='The details for events with this `type`.', - ), + user_updated: Annotated[ + Optional[UserUpdated], + Field(alias="user.updated", description="The details for events with this `type`."), + ] = None + user_deleted: Annotated[ + Optional[UserDeleted], + Field(alias="user.deleted", description="The details for events with this `type`."), + ] = None + + +class ListAuditLogsResponse(BaseModel): + object: Literal["list"] + data: List[AuditLog] + first_id: Annotated[str, Field(example="audit_log-defb456h8dks")] + last_id: Annotated[str, Field(example="audit_log-hnbkd8s93s")] + has_more: bool + + +class Invite(BaseModel): + object: Annotated[ + Literal["organization.invite"], + Field(description="The object type, which is always `organization.invite`"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + email: Annotated[ + str, + Field(description="The email address of the individual to whom the invite was sent"), + ] + role: Annotated[Literal["owner", "reader"], Field(description="`owner` or `reader`")] + status: Annotated[ + Literal["accepted", "expired", "pending"], + Field(description="`accepted`,`expired`, or `pending`"), + ] + invited_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the invite was sent."), + ] + expires_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the invite expires."), + ] + accepted_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) of when the invite was accepted."), + ] = None + + +class InviteListResponse(BaseModel): + object: Annotated[Literal["list"], Field(description="The object type, which is always `list`")] + data: List[Invite] + first_id: Annotated[ + Optional[str], + Field(description="The first `invite_id` in the retrieved `list`"), + ] = None + last_id: Annotated[ + Optional[str], Field(description="The last `invite_id` in the retrieved `list`") ] = None - ip_allowlist_deleted: Annotated[ - Optional[IpAllowlistDeleted], + has_more: Annotated[ + Optional[bool], Field( - alias='ip_allowlist.deleted', - description='The details for events with this `type`.', + description="The `has_more` property is used for pagination to indicate there are additional results." ), ] = None - ip_allowlist_config_activated: Annotated[ - Optional[IpAllowlistConfigActivated], + + +class InviteRequest(BaseModel): + email: Annotated[str, Field(description="Send an email to this address")] + role: Annotated[Literal["reader", "owner"], Field(description="`owner` or `reader`")] + + +class InviteDeleteResponse(BaseModel): + object: Annotated[ + Literal["organization.invite.deleted"], + Field(description="The object type, which is always `organization.invite.deleted`"), + ] + id: str + deleted: bool + + +class User(BaseModel): + object: Annotated[ + Literal["organization.user"], + Field(description="The object type, which is always `organization.user`"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + name: Annotated[str, Field(description="The name of the user")] + email: Annotated[str, Field(description="The email address of the user")] + role: Annotated[Literal["owner", "reader"], Field(description="`owner` or `reader`")] + added_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the user was added."), + ] + + +class UserListResponse(BaseModel): + object: Literal["list"] + data: List[User] + first_id: str + last_id: str + has_more: bool + + +class UserRoleUpdateRequest(BaseModel): + role: Annotated[Literal["owner", "reader"], Field(description="`owner` or `reader`")] + + +class UserDeleteResponse(BaseModel): + object: Literal["organization.user.deleted"] + id: str + deleted: bool + + +class Project1(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + object: Annotated[ + Literal["organization.project"], + Field(description="The object type, which is always `organization.project`"), + ] + name: Annotated[str, Field(description="The name of the project. This appears in reporting.")] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the project was created."), + ] + archived_at: Annotated[ + Optional[int], Field( - alias='ip_allowlist.config.activated', - description='The details for events with this `type`.', + description="The Unix timestamp (in seconds) of when the project was archived or `null`." ), ] = None - ip_allowlist_config_deactivated: Annotated[ - Optional[IpAllowlistConfigDeactivated], + status: Annotated[Literal["active", "archived"], Field(description="`active` or `archived`")] + + +class ProjectListResponse(BaseModel): + object: Literal["list"] + data: List[Project1] + first_id: str + last_id: str + has_more: bool + + +class ProjectCreateRequest(BaseModel): + name: Annotated[ + str, + Field(description="The friendly name of the project, this name appears in reports."), + ] + + +class ProjectUpdateRequest(BaseModel): + name: Annotated[ + str, + Field(description="The updated name of the project, this name appears in reports."), + ] + + +class DefaultProjectErrorResponse(BaseModel): + code: int + message: str + + +class ProjectUser(BaseModel): + object: Annotated[ + Literal["organization.project.user"], + Field(description="The object type, which is always `organization.project.user`"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + name: Annotated[str, Field(description="The name of the user")] + email: Annotated[str, Field(description="The email address of the user")] + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + added_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the project was added."), + ] + + +class ProjectUserListResponse(BaseModel): + object: str + data: List[ProjectUser] + first_id: str + last_id: str + has_more: bool + + +class ProjectUserCreateRequest(BaseModel): + user_id: Annotated[str, Field(description="The ID of the user.")] + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + + +class ProjectUserUpdateRequest(BaseModel): + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + + +class ProjectUserDeleteResponse(BaseModel): + object: Literal["organization.project.user.deleted"] + id: str + deleted: bool + + +class ProjectServiceAccount(BaseModel): + object: Annotated[ + Literal["organization.project.service_account"], Field( - alias='ip_allowlist.config.deactivated', - description='The details for events with this `type`.', + description="The object type, which is always `organization.project.service_account`" ), - ] = None - login_succeeded: Annotated[ - Optional[Dict[str, Any]], + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + name: Annotated[str, Field(description="The name of the service account")] + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + created_at: Annotated[ + int, Field( - alias='login.succeeded', - description='This event has no additional fields beyond the standard audit log attributes.', + description="The Unix timestamp (in seconds) of when the service account was created" ), - ] = None - login_failed: Annotated[ - Optional[LoginFailed], + ] + + +class ProjectServiceAccountListResponse(BaseModel): + object: Literal["list"] + data: List[ProjectServiceAccount] + first_id: str + last_id: str + has_more: bool + + +class ProjectServiceAccountCreateRequest(BaseModel): + name: Annotated[str, Field(description="The name of the service account being created.")] + + +class ProjectServiceAccountApiKey(BaseModel): + object: Annotated[ + Literal["organization.project.service_account.api_key"], Field( - alias='login.failed', description='The details for events with this `type`.' + description="The object type, which is always `organization.project.service_account.api_key`" ), + ] + value: str + name: str + created_at: int + id: str + + +class ProjectServiceAccountDeleteResponse(BaseModel): + object: Literal["organization.project.service_account.deleted"] + id: str + deleted: bool + + +class Owner(BaseModel): + type: Annotated[ + Optional[Literal["user", "service_account"]], + Field(description="`user` or `service_account`"), ] = None - logout_succeeded: Annotated[ - Optional[Dict[str, Any]], + user: Optional[ProjectUser] = None + service_account: Optional[ProjectServiceAccount] = None + + +class ProjectApiKey(BaseModel): + object: Annotated[ + Literal["organization.project.api_key"], + Field(description="The object type, which is always `organization.project.api_key`"), + ] + redacted_value: Annotated[str, Field(description="The redacted value of the API key")] + name: Annotated[str, Field(description="The name of the API key")] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the API key was created"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + owner: Owner + + +class ProjectApiKeyListResponse(BaseModel): + object: Literal["list"] + data: List[ProjectApiKey] + first_id: str + last_id: str + has_more: bool + + +class ProjectApiKeyDeleteResponse(BaseModel): + object: Literal["organization.project.api_key.deleted"] + id: str + deleted: bool + + +class ListModelsResponse(BaseModel): + object: Literal["list"] + data: List[Model] + + +class CreateCompletionRequest(BaseModel): + model: Annotated[ + Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], Field( - alias='logout.succeeded', - description='This event has no additional fields beyond the standard audit log attributes.', + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n" ), - ] = None - logout_failed: Annotated[ - Optional[LogoutFailed], + ] + prompt: Annotated[ + Union[str, List[str], Prompt, Prompt1], Field( - alias='logout.failed', - description='The details for events with this `type`.', + description="The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n" ), - ] = None - organization_updated: Annotated[ - Optional[OrganizationUpdated], + ] + best_of: Annotated[ + Optional[int], Field( - alias='organization.updated', - description='The details for events with this `type`.', + description='Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed.\n\nWhen used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n', + ge=0, + le=20, ), - ] = None - project_created: Annotated[ - Optional[ProjectCreated], + ] = 1 + echo: Annotated[ + Optional[bool], + Field(description="Echo back the prompt in addition to the completion\n"), + ] = False + frequency_penalty: Annotated[ + Optional[float], Field( - alias='project.created', - description='The details for events with this `type`.', + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] = None - project_updated: Annotated[ - Optional[ProjectUpdated], + ] = 0 + logit_bias: Annotated[ + Optional[Dict[str, int]], Field( - alias='project.updated', - description='The details for events with this `type`.', + description='Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n\nAs an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated.\n' ), ] = None - project_archived: Annotated[ - Optional[ProjectArchived], + logprobs: Annotated[ + Optional[int], Field( - alias='project.archived', - description='The details for events with this `type`.', + description="Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n\nThe maximum value for `logprobs` is 5.\n", + ge=0, + le=5, ), ] = None - project_deleted: Annotated[ - Optional[ProjectDeleted], + max_tokens: Annotated[ + Optional[int], Field( - alias='project.deleted', - description='The details for events with this `type`.', + description="The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n\nThe token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n", + example=16, + ge=0, ), - ] = None - rate_limit_updated: Annotated[ - Optional[RateLimitUpdated], + ] = 16 + n: Annotated[ + Optional[int], Field( - alias='rate_limit.updated', - description='The details for events with this `type`.', + description="How many completions to generate for each prompt.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n", + example=1, + ge=1, + le=128, ), - ] = None - rate_limit_deleted: Annotated[ - Optional[RateLimitDeleted], + ] = 1 + presence_penalty: Annotated[ + Optional[float], Field( - alias='rate_limit.deleted', - description='The details for events with this `type`.', + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] = None - role_created: Annotated[ - Optional[RoleCreated], + ] = 0 + seed: Annotated[ + Optional[int], Field( - alias='role.created', description='The details for events with this `type`.' + description="If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n", + ge=-9223372036854775808, + le=9223372036854775807, ), ] = None - role_updated: Annotated[ - Optional[RoleUpdated], + stop: Annotated[ + Optional[Union[str, Stop]], Field( - alias='role.updated', description='The details for events with this `type`.' + description="Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.\n" ), ] = None - role_deleted: Annotated[ - Optional[RoleDeleted], + stream: Annotated[ + Optional[bool], Field( - alias='role.deleted', description='The details for events with this `type`.' + description="Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n" ), - ] = None - role_assignment_created: Annotated[ - Optional[RoleAssignmentCreated], + ] = False + stream_options: Optional[ChatCompletionStreamOptions] = None + suffix: Annotated[ + Optional[str], Field( - alias='role.assignment.created', - description='The details for events with this `type`.', + description="The suffix that comes after a completion of inserted text.\n\nThis parameter is only supported for `gpt-3.5-turbo-instruct`.\n", + example="test.", ), ] = None - role_assignment_deleted: Annotated[ - Optional[RoleAssignmentDeleted], + temperature: Annotated[ + Optional[float], Field( - alias='role.assignment.deleted', - description='The details for events with this `type`.', + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n", + example=1, + ge=0.0, + le=2.0, ), - ] = None - service_account_created: Annotated[ - Optional[ServiceAccountCreated], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - alias='service_account.created', - description='The details for events with this `type`.', + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n", + example=1, + ge=0.0, + le=1.0, ), - ] = None - service_account_updated: Annotated[ - Optional[ServiceAccountUpdated], + ] = 1 + user: Annotated[ + Optional[str], Field( - alias='service_account.updated', - description='The details for events with this `type`.', + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + example="user-1234", ), ] = None - service_account_deleted: Annotated[ - Optional[ServiceAccountDeleted], + + +class CreateCompletionResponse(BaseModel): + id: Annotated[str, Field(description="A unique identifier for the completion.")] + choices: Annotated[ + List[Choice], Field( - alias='service_account.deleted', - description='The details for events with this `type`.', + description="The list of completion choices the model generated for the input prompt." ), - ] = None - user_added: Annotated[ - Optional[UserAdded], + ] + created: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the completion was created."), + ] + model: Annotated[str, Field(description="The model used for completion.")] + system_fingerprint: Annotated[ + Optional[str], Field( - alias='user.added', description='The details for events with this `type`.' + description="This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None - user_updated: Annotated[ - Optional[UserUpdated], + object: Annotated[ + Literal["text_completion"], + Field(description='The object type, which is always "text_completion"'), + ] + usage: Optional[CompletionUsage] = None + + +class ChatCompletionTool(BaseModel): + type: Annotated[ + Literal["function"], + Field(description="The type of the tool. Currently, only `function` is supported."), + ] + function: FunctionObject + + +class ChatCompletionToolChoiceOption(BaseModel): + __root__: Annotated[ + Union[Literal["none", "auto", "required"], ChatCompletionNamedToolChoice], Field( - alias='user.updated', description='The details for events with this `type`.' + description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tool and instead generates a message.\n`auto` means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools.\nSpecifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n\n`none` is the default when no tools are present. `auto` is the default if tools are present.\n' ), - ] = None - user_deleted: Annotated[ - Optional[UserDeleted], + ] + + +class ChatCompletionMessageToolCalls(BaseModel): + __root__: Annotated[ + List[ChatCompletionMessageToolCall], + Field(description="The tool calls generated by the model, such as function calls."), + ] + + +class ChatCompletionResponseMessage(BaseModel): + content: Annotated[str, Field(description="The contents of the message.")] + refusal: Annotated[str, Field(description="The refusal message generated by the model.")] + tool_calls: Optional[ChatCompletionMessageToolCalls] = None + role: Annotated[ + Literal["assistant"], + Field(description="The role of the author of this message."), + ] + function_call: Annotated[ + Optional[FunctionCall], Field( - alias='user.deleted', description='The details for events with this `type`.' + description="Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." ), ] = None - certificate_created: Annotated[ - Optional[CertificateCreated], + + +class Choice1(BaseModel): + finish_reason: Annotated[ + Literal["stop", "length", "tool_calls", "content_filter", "function_call"], Field( - alias='certificate.created', - description='The details for events with this `type`.', + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" ), - ] = None - certificate_updated: Annotated[ - Optional[CertificateUpdated], + ] + index: Annotated[int, Field(description="The index of the choice in the list of choices.")] + message: ChatCompletionResponseMessage + logprobs: Annotated[Logprobs2, Field(description="Log probability information for the choice.")] + + +class CreateChatCompletionResponse(BaseModel): + id: Annotated[str, Field(description="A unique identifier for the chat completion.")] + choices: Annotated[ + List[Choice1], Field( - alias='certificate.updated', - description='The details for events with this `type`.', + description="A list of chat completion choices. Can be more than one if `n` is greater than 1." ), - ] = None - certificate_deleted: Annotated[ - Optional[CertificateDeleted], + ] + created: Annotated[ + int, Field( - alias='certificate.deleted', - description='The details for events with this `type`.', + description="The Unix timestamp (in seconds) of when the chat completion was created." ), - ] = None - certificates_activated: Annotated[ - Optional[CertificatesActivated], + ] + model: Annotated[str, Field(description="The model used for the chat completion.")] + service_tier: Annotated[ + Optional[Literal["scale", "default"]], Field( - alias='certificates.activated', - description='The details for events with this `type`.', + description="The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.", + example="scale", ), ] = None - certificates_deactivated: Annotated[ - Optional[CertificatesDeactivated], + system_fingerprint: Annotated[ + Optional[str], Field( - alias='certificates.deactivated', - description='The details for events with this `type`.', + description="This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None + object: Annotated[ + Literal["chat.completion"], + Field(description="The object type, which is always `chat.completion`."), + ] + usage: Optional[CompletionUsage] = None -class ConversationItem(BaseModel): - __root__: Annotated[ - Union[ - Message, - FunctionToolCallResource, - FunctionToolCallOutputResource, - FileSearchToolCall, - WebSearchToolCall, - ImageGenToolCall, - ComputerToolCall, - ComputerToolCallOutputResource, - ReasoningItem, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponseResource, - MCPToolCall, - CustomToolCall, - CustomToolCallOutput, - ], +class Choice2(BaseModel): + finish_reason: Annotated[ + Literal["stop", "length", "function_call", "content_filter"], Field( - description='A single item within a conversation. The set of possible types are the same as the `output` type of a [Response object](https://platform.openai.com/docs/api-reference/responses/object#responses/object-output).', - discriminator='type', - title='Conversation item', + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, or `function_call` if the model called a function.\n" ), ] + index: Annotated[int, Field(description="The index of the choice in the list of choices.")] + message: ChatCompletionResponseMessage -class ConversationItemList(BaseModel): - object: Annotated[ - str, - Field(const=True, description='The type of object returned, must be `list`.'), - ] = 'list' - data: Annotated[ - List[ConversationItem], Field(description='A list of conversation items.') - ] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') +class CreateChatCompletionFunctionResponse(BaseModel): + id: Annotated[str, Field(description="A unique identifier for the chat completion.")] + choices: Annotated[ + List[Choice2], + Field( + description="A list of chat completion choices. Can be more than one if `n` is greater than 1." + ), ] - first_id: Annotated[str, Field(description='The ID of the first item in the list.')] - last_id: Annotated[str, Field(description='The ID of the last item in the list.')] - - -class CreateAssistantRequest(BaseModel): - class Config: - extra = Extra.forbid - - model: Annotated[ - Union[str, AssistantSupportedModels], + created: Annotated[ + int, Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n', - example='gpt-4o', + description="The Unix timestamp (in seconds) of when the chat completion was created." ), ] - name: Optional[Name] = None - description: Optional[Description] = None - instructions: Optional[Instructions] = None - reasoning_effort: Optional[ReasoningEffort] = None - tools: Annotated[ - List[AssistantTool], + model: Annotated[str, Field(description="The model used for the chat completion.")] + system_fingerprint: Annotated[ + Optional[str], Field( - description='A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n', - max_items=128, + description="This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), - ] = [] - tool_resources: Optional[ToolResources1] = None - metadata: Optional[Metadata] = None - temperature: Optional[Temperature] = None - top_p: Optional[TopP] = None - response_format: Optional[AssistantsApiResponseFormatOption] = None + ] = None + object: Annotated[ + Literal["chat.completion"], + Field(description="The object type, which is always `chat.completion`."), + ] + usage: Optional[CompletionUsage] = None -class CreateChatCompletionRequest(CreateModelResponseProperties): - messages: Annotated[ - List[ChatCompletionRequestMessage], - Field( - description='A list of messages comprising the conversation so far. Depending on the\n[model](https://platform.openai.com/docs/models) you use, different message types (modalities) are\nsupported, like [text](https://platform.openai.com/docs/guides/text-generation),\n[images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).\n', - min_items=1, - ), +class ImagesResponse(BaseModel): + created: int + data: List[Image] + + +class ListFilesResponse(BaseModel): + data: List[OpenAIFile] + object: Literal["list"] + + +class ListFineTuningJobEventsResponse(BaseModel): + data: List[FineTuningJobEvent] + object: Literal["list"] + + +class ListFineTuningJobCheckpointsResponse(BaseModel): + data: List[FineTuningJobCheckpoint] + object: Literal["list"] + first_id: Optional[str] = None + last_id: Optional[str] = None + has_more: bool + + +class CreateEmbeddingResponse(BaseModel): + data: Annotated[ + List[Embedding], + Field(description="The list of embeddings generated by the model."), ] model: Annotated[ + str, Field(description="The name of the model used to generate the embedding.") + ] + object: Annotated[ + Literal["list"], Field(description='The object type, which is always "list".') + ] + usage: Annotated[Usage1, Field(description="The usage information for the request.")] + + +class FineTuningJob(BaseModel): + id: Annotated[ str, + Field(description="The object identifier, which can be referenced in the API endpoints."), + ] + created_at: Annotated[ + int, Field( - description='Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\nto browse and compare available models.\n' + description="The Unix timestamp (in seconds) for when the fine-tuning job was created." ), ] - modalities: Optional[ResponseModalities] = None - verbosity: Optional[Verbosity] = None - reasoning_effort: Optional[ReasoningEffort] = None - max_completion_tokens: Annotated[ - Optional[int], + error: Annotated[ + Error1, Field( - description='An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n' + description="For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure." ), - ] = None - frequency_penalty: Annotated[ - Optional[float], + ] + fine_tuned_model: Annotated[ + str, Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on\ntheir existing frequency in the text so far, decreasing the model's\nlikelihood to repeat the same line verbatim.\n", - ge=-2.0, - le=2.0, + description="The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running." ), - ] = 0 - presence_penalty: Annotated[ - Optional[float], + ] + finished_at: Annotated[ + int, Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on\nwhether they appear in the text so far, increasing the model's likelihood\nto talk about new topics.\n", - ge=-2.0, - le=2.0, + description="The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running." ), - ] = 0 - web_search_options: Annotated[ - Optional[WebSearchOptions], + ] + hyperparameters: Annotated[ + Hyperparameters1, Field( - description='This tool searches the web for relevant results to use in a response.\nLearn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n', - title='Web search', + description="The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details." ), - ] = None - top_logprobs: Annotated[ - Optional[int], + ] + model: Annotated[str, Field(description="The base model that is being fine-tuned.")] + object: Annotated[ + Literal["fine_tuning.job"], + Field(description='The object type, which is always "fine_tuning.job".'), + ] + organization_id: Annotated[ + str, Field(description="The organization that owns the fine-tuning job.") + ] + result_files: Annotated[ + List[str], Field( - description='An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n`logprobs` must be set to `true` if this parameter is used.\n', - ge=0, - le=20, + description="The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents)." ), - ] = None - response_format: Annotated[ - Optional[ - Union[ - ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject - ] - ], + ] + status: Annotated[ + Literal["validating_files", "queued", "running", "succeeded", "failed", "cancelled"], Field( - description='An object specifying the format that the model must output.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n', - discriminator='type', + description="The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`." ), - ] = None - audio: Annotated[ - Optional[Audio2], + ] + trained_tokens: Annotated[ + int, Field( - description='Parameters for audio output. Required when audio output is requested with\n`modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio).\n' + description="The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running." ), - ] = None - store: Annotated[ - Optional[bool], + ] + training_file: Annotated[ + str, Field( - description='Whether or not to store the output of this chat completion request for\nuse in our [model distillation](https://platform.openai.com/docs/guides/distillation) or\n[evals](https://platform.openai.com/docs/guides/evals) products.\n\nSupports text and image inputs. Note: image inputs over 8MB will be dropped.\n' + description="The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents)." ), - ] = False - stream: Annotated[ - Optional[bool], + ] + validation_file: Annotated[ + str, Field( - description='If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\nfor more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\nguide for more information on how to handle the streaming events.\n' + description="The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents)." ), - ] = False - stop: Optional[StopConfiguration] = None - logit_bias: Annotated[ - Optional[Dict[str, int]], + ] + integrations: Annotated[ + Optional[List[FineTuningIntegration]], Field( - description='Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the\ntokenizer) to an associated bias value from -100 to 100. Mathematically,\nthe bias is added to the logits generated by the model prior to sampling.\nThe exact effect will vary per model, but values between -1 and 1 should\ndecrease or increase likelihood of selection; values like -100 or 100\nshould result in a ban or exclusive selection of the relevant token.\n' + description="A list of integrations to enable for this fine-tuning job.", + max_items=5, ), ] = None - logprobs: Annotated[ - Optional[bool], - Field( - description='Whether to return log probabilities of the output tokens or not. If true,\nreturns the log probabilities of each output token returned in the\n`content` of `message`.\n' - ), - ] = False - max_tokens: Annotated[ + seed: Annotated[int, Field(description="The seed used for the fine-tuning job.")] + estimated_finish: Annotated[ Optional[int], Field( - description='The maximum number of [tokens](/tokenizer) that can be generated in the\nchat completion. This value can be used to control\n[costs](https://openai.com/api/pricing/) for text generated via API.\n\nThis value is now deprecated in favor of `max_completion_tokens`, and is\nnot compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning).\n' + description="The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running." ), ] = None - n: Annotated[ - Optional[int], - Field( - description='How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs.', - example=1, - ge=1, - le=128, - ), - ] = 1 - prediction: Annotated[ - Optional[PredictionContent], + + +class AssistantObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["assistant"], + Field(description="The object type, which is always `assistant`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the assistant was created."), + ] + name: Annotated[ + str, Field( - description='Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs),\nwhich can greatly improve response times when large parts of the model\nresponse are known ahead of time. This is most common when you are\nregenerating a file with only minor changes to most of the content.\n', - discriminator='type', + description="The name of the assistant. The maximum length is 256 characters.\n", + max_length=256, ), - ] = None - seed: Annotated[ - Optional[int], + ] + description: Annotated[ + str, Field( - description='This feature is in Beta.\nIf specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n', - ge=-9223372036854776000, - le=9223372036854776000, + description="The description of the assistant. The maximum length is 512 characters.\n", + max_length=512, ), - ] = None - stream_options: Optional[ChatCompletionStreamOptions] = None - tools: Annotated[ - Optional[List[Tools]], + ] + model: Annotated[ + str, Field( - description='A list of tools the model may call. You can provide either\n[custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or\n[function tools](https://platform.openai.com/docs/guides/function-calling).\n' + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n" ), - ] = None - tool_choice: Optional[ChatCompletionToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - function_call: Annotated[ - Optional[Union[Literal['none', 'auto'], ChatCompletionFunctionCallOption]], + ] + instructions: Annotated[ + str, Field( - description='Deprecated in favor of `tool_choice`.\n\nControls which (if any) function is called by the model.\n\n`none` means the model will not call a function and instead generates a\nmessage.\n\n`auto` means the model can pick between generating a message or calling a\nfunction.\n\nSpecifying a particular function via `{"name": "my_function"}` forces the\nmodel to call that function.\n\n`none` is the default when no functions are present. `auto` is the default\nif functions are present.\n' + description="The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + max_length=256000, ), - ] = None - functions: Annotated[ - Optional[List[ChatCompletionFunctions]], + ] + tools: Annotated[ + List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]], Field( - description='Deprecated in favor of `tools`.\n\nA list of functions the model may generate JSON inputs for.\n', + description="A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", max_items=128, - min_items=1, ), - ] = None - - -class InputMessages(BaseModel): - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `template`.'), ] - template: Annotated[ - List[Union[EasyInputMessage, EvalItem]], + tool_resources: Annotated[ + Optional[ToolResources], Field( - description='A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.' + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), - ] - - -class CreateEvalCompletionsRunDataSource(BaseModel): - type: Annotated[ - Literal['CreateEvalCompletionsRunDataSource'], - Field(description='The type of run data source. Always `completions`.'), - ] - input_messages: Annotated[ - Optional[Union[InputMessages, InputMessages1]], + ] = None + metadata: Annotated[ + Dict[str, Any], Field( - description='Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.', - discriminator='type', + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = None - sampling_params: Optional[SamplingParams] = None - model: Annotated[ - Optional[str], + ] + temperature: Annotated[ + Optional[float], Field( - description='The name of the model to use for generating completions (e.g. "o3-mini").' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + example=1, + ge=0.0, + le=2.0, ), - ] = None - source: Annotated[ - Union[ - EvalJsonlFileContentSource, - EvalJsonlFileIdSource, - EvalStoredCompletionsSource, - ], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - description="Determines what populates the `item` namespace in this run's data source.", - discriminator='type', + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + example=1, + ge=0.0, + le=1.0, ), - ] - - -class TestingCriteria(BaseModel): - __root__: Annotated[ - Union[ - CreateEvalLabelModelGrader, - EvalGraderStringCheck, - EvalGraderTextSimilarity, - EvalGraderPython, - EvalGraderScoreModel, - ], - Field(discriminator='type'), - ] + ] = 1 + response_format: Optional[AssistantsApiResponseFormatOption] = None -class CreateEvalRequest(BaseModel): - name: Annotated[Optional[str], Field(description='The name of the evaluation.')] = ( - None - ) - metadata: Optional[Metadata] = None - data_source_config: Annotated[ +class CreateAssistantRequest(BaseModel): + class Config: + extra = Extra.forbid + + model: Annotated[ Union[ - CreateEvalCustomDataSourceConfig, - CreateEvalLogsDataSourceConfig, - CreateEvalStoredCompletionsDataSourceConfig, + str, + Literal[ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], ], Field( - description='The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation.', - discriminator='type', + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n", + example="gpt-4o", ), ] - testing_criteria: Annotated[ - List[TestingCriteria], + name: Annotated[ + Optional[str], Field( - description="A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`)." + description="The name of the assistant. The maximum length is 256 characters.\n", + max_length=256, ), - ] - - -class SamplingParams1(BaseModel): - reasoning_effort: Optional[ReasoningEffort] = None - temperature: Annotated[ - float, - Field(description='A higher temperature increases randomness in the outputs.'), - ] = 1 - max_completion_tokens: Annotated[ - Optional[int], - Field(description='The maximum number of tokens in the generated output.'), ] = None - top_p: Annotated[ - float, + description: Annotated[ + Optional[str], Field( - description='An alternative to temperature for nucleus sampling; 1.0 includes all tokens.' + description="The description of the assistant. The maximum length is 512 characters.\n", + max_length=512, ), - ] = 1 - seed: Annotated[ - int, + ] = None + instructions: Annotated[ + Optional[str], Field( - description='A seed value to initialize the randomness, during sampling.' + description="The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + max_length=256000, ), - ] = 42 + ] = None tools: Annotated[ - Optional[List[Tool]], + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]]], Field( - description="An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nThe two categories of tools you can provide the model are:\n\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n [built-in tools](https://platform.openai.com/docs/guides/tools).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code. Learn more about\n [function calling](https://platform.openai.com/docs/guides/function-calling).\n" + description="A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + max_items=128, ), - ] = None - text: Annotated[ - Optional[Text], + ] = [] + tool_resources: Annotated[ + Optional[ToolResources1], Field( - description='Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n' + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), ] = None - - -class CreateEvalResponsesRunDataSource(BaseModel): - type: Annotated[ - Literal['CreateEvalResponsesRunDataSource'], - Field(description='The type of run data source. Always `responses`.'), - ] - input_messages: Annotated[ - Optional[Union[InputMessages2, InputMessages3]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.', - discriminator='type', + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - sampling_params: Optional[SamplingParams1] = None - model: Annotated[ - Optional[str], + temperature: Annotated[ + Optional[float], Field( - description='The name of the model to use for generating completions (e.g. "o3-mini").' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + example=1, + ge=0.0, + le=2.0, ), - ] = None - source: Annotated[ - Union[EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalResponsesSource], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - description="Determines what populates the `item` namespace in this run's data source.", - discriminator='type', + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + example=1, + ge=0.0, + le=1.0, ), - ] - - -class CreateEvalRunRequest(BaseModel): - name: Annotated[Optional[str], Field(description='The name of the run.')] = None - metadata: Optional[Metadata] = None - data_source: Annotated[ - Union[ - CreateEvalJsonlRunDataSource, - CreateEvalCompletionsRunDataSource, - CreateEvalResponsesRunDataSource, - ], - Field(description="Details about the run's data source."), - ] + ] = 1 + response_format: Optional[AssistantsApiResponseFormatOption] = None -class CreateRunRequest(BaseModel): +class ModifyAssistantRequest(BaseModel): class Config: extra = Extra.forbid - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' - ), - ] model: Annotated[ - Optional[Union[Optional[str], AssistantSupportedModels]], + Optional[str], Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n" ), ] = None - reasoning_effort: Optional[ReasoningEffort] = None - instructions: Annotated[ + name: Annotated[ Optional[str], Field( - description='Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.' + description="The name of the assistant. The maximum length is 256 characters.\n", + max_length=256, ), ] = None - additional_instructions: Annotated[ + description: Annotated[ Optional[str], Field( - description='Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.' + description="The description of the assistant. The maximum length is 512 characters.\n", + max_length=512, ), ] = None - additional_messages: Annotated[ - Optional[List[CreateMessageRequest]], + instructions: Annotated[ + Optional[str], Field( - description='Adds additional messages to the thread before creating the run.' + description="The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + max_length=256000, ), ] = None tools: Annotated[ - Optional[List[AssistantTool]], + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]]], Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', - max_items=20, + description="A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + max_items=128, + ), + ] = [] + tool_resources: Annotated[ + Optional[ToolResources2], + Field( + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - metadata: Optional[Metadata] = None temperature: Annotated[ Optional[float], Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", example=1, ge=0.0, le=2.0, @@ -18880,1653 +4441,1392 @@ class Config: top_p: Annotated[ Optional[float], Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", example=1, ge=0.0, le=1.0, ), ] = 1 - stream: Annotated[ - Optional[bool], - Field( - description='If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n' - ), - ] = None - max_prompt_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), - ] = None - max_completion_tokens: Annotated[ - Optional[int], + response_format: Optional[AssistantsApiResponseFormatOption] = None + + +class ListAssistantsResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[AssistantObject] + first_id: Annotated[str, Field(example="asst_abc123")] + last_id: Annotated[str, Field(example="asst_abc456")] + has_more: Annotated[bool, Field(example=False)] + + +class AssistantsApiToolChoiceOption(BaseModel): + __root__: Annotated[ + Union[Literal["none", "auto", "required"], AssistantsNamedToolChoice], Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, + description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n' ), - ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None + ] -class CreateThreadAndRunRequest(BaseModel): - class Config: - extra = Extra.forbid +class SubmitToolOutputs(BaseModel): + tool_calls: Annotated[ + List[RunToolCallObject], Field(description="A list of the relevant tool calls.") + ] + + +class RequiredAction(BaseModel): + type: Annotated[ + Literal["submit_tool_outputs"], + Field(description="For now, this is always `submit_tool_outputs`."), + ] + submit_tool_outputs: Annotated[ + SubmitToolOutputs, + Field(description="Details on the tool outputs needed for this run to continue."), + ] + +class RunObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["thread.run"], + Field(description="The object type, which is always `thread.run`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run was created."), + ] + thread_id: Annotated[ + str, + Field( + description="The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run." + ), + ] assistant_id: Annotated[ str, Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' + description="The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run." ), ] - thread: Optional[CreateThreadRequest] = None - model: Annotated[ - Optional[ - Union[ - Optional[str], - Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ], - ] + status: Annotated[ + Literal[ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired", ], Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' + description="The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`." ), - ] = None + ] + required_action: Annotated[ + RequiredAction, + Field( + description="Details on the action required to continue the run. Will be `null` if no action is required." + ), + ] + last_error: Annotated[ + LastError, + Field( + description="The last error associated with this run. Will be `null` if there are no errors." + ), + ] + expires_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run will expire."), + ] + started_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run was started."), + ] + cancelled_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run was cancelled."), + ] + failed_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run failed."), + ] + completed_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run was completed."), + ] + incomplete_details: Annotated[ + IncompleteDetails, + Field( + description="Details on why the run is incomplete. Will be `null` if the run is not incomplete." + ), + ] + model: Annotated[ + str, + Field( + description="The model that the [assistant](/docs/api-reference/assistants) used for this run." + ), + ] instructions: Annotated[ - Optional[str], + str, Field( - description='Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.' + description="The instructions that the [assistant](/docs/api-reference/assistants) used for this run." ), - ] = None + ] tools: Annotated[ - Optional[List[AssistantTool]], + List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]], Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', + description="The list of tools that the [assistant](/docs/api-reference/assistants) used for this run.", max_items=20, ), - ] = None - tool_resources: Annotated[ - Optional[ToolResources2], + ] + metadata: Annotated[ + Dict[str, Any], Field( - description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = None - metadata: Optional[Metadata] = None + ] + usage: RunCompletionUsage temperature: Annotated[ Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - example=1, - ge=0.0, - le=2.0, - ), - ] = 1 + Field(description="The sampling temperature used for this run. If not set, defaults to 1."), + ] = None top_p: Annotated[ Optional[float], Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - example=1, - ge=0.0, - le=1.0, + description="The nucleus sampling value used for this run. If not set, defaults to 1." ), - ] = 1 - stream: Annotated[ - Optional[bool], + ] = None + max_prompt_tokens: Annotated[ + int, + Field( + description="The maximum number of prompt tokens specified to have been used over the course of the run.\n", + ge=256, + ), + ] + max_completion_tokens: Annotated[ + int, + Field( + description="The maximum number of completion tokens specified to have been used over the course of the run.\n", + ge=256, + ), + ] + truncation_strategy: TruncationObject + tool_choice: AssistantsApiToolChoiceOption + parallel_tool_calls: ParallelToolCalls + response_format: AssistantsApiResponseFormatOption + + +class ListRunsResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[RunObject] + first_id: Annotated[str, Field(example="run_abc123")] + last_id: Annotated[str, Field(example="run_abc456")] + has_more: Annotated[bool, Field(example=False)] + + +class Content4(BaseModel): + __root__: Annotated[ + List[ + Union[ + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageRequestContentTextObject, + ] + ], + Field( + description="An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models/overview).", + min_items=1, + title="Array of content parts", + ), + ] + + +class CreateMessageRequest(BaseModel): + class Config: + extra = Extra.forbid + + role: Annotated[ + Literal["user", "assistant"], Field( - description='If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n' + description="The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n" ), - ] = None - max_prompt_tokens: Annotated[ - Optional[int], + ] + content: Union[str, Content4] + attachments: Annotated[ + Optional[List[Attachment]], Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, + description="A list of files attached to the message, and the tools they should be added to." ), ] = None - max_completion_tokens: Annotated[ - Optional[int], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None -class Eval(BaseModel): - object: Annotated[Literal['eval'], Field(description='The object type.')] - id: Annotated[str, Field(description='Unique identifier for the evaluation.')] - name: Annotated[ - str, - Field( - description='The name of the evaluation.', - example='Chatbot effectiveness Evaluation', - ), - ] - data_source_config: Annotated[ +class Text(BaseModel): + value: Annotated[str, Field(description="The data that makes up the text.")] + annotations: List[ Union[ - EvalCustomDataSourceConfig, - EvalLogsDataSourceConfig, - EvalStoredCompletionsDataSourceConfig, - ], - Field( - description='Configuration of data sources used in runs of the evaluation.', - discriminator='type', - ), + MessageContentTextAnnotationsFileCitationObject, + MessageContentTextAnnotationsFilePathObject, + ] ] - testing_criteria: Annotated[ + + +class MessageContentTextObject(BaseModel): + type: Annotated[Literal["text"], Field(description="Always `text`.")] + text: Text + + +class Text1(BaseModel): + value: Annotated[Optional[str], Field(description="The data that makes up the text.")] = None + annotations: Optional[ + List[ + Union[ + MessageDeltaContentTextAnnotationsFileCitationObject, + MessageDeltaContentTextAnnotationsFilePathObject, + ] + ] + ] = None + + +class MessageDeltaContentTextObject(BaseModel): + index: Annotated[int, Field(description="The index of the content part in the message.")] + type: Annotated[Literal["text"], Field(description="Always `text`.")] + text: Optional[Text1] = None + + +class CodeInterpreter7(BaseModel): + input: Annotated[str, Field(description="The input to the Code Interpreter tool call.")] + outputs: Annotated[ List[ Union[ - EvalGraderLabelModel, - EvalGraderStringCheck, - EvalGraderTextSimilarity, - EvalGraderPython, - EvalGraderScoreModel, + RunStepDetailsToolCallsCodeOutputLogsObject, + RunStepDetailsToolCallsCodeOutputImageObject, ] ], - Field(description='A list of testing criteria.'), - ] - created_at: Annotated[ - int, Field( - description='The Unix timestamp (in seconds) for when the eval was created.' + description="The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type." ), ] - metadata: Metadata -class EvalList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[List[Eval], Field(description='An array of eval objects.\n')] - first_id: Annotated[ - str, Field(description='The identifier of the first eval in the data array.') - ] - last_id: Annotated[ - str, Field(description='The identifier of the last eval in the data array.') +class RunStepDetailsToolCallsCodeObject(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call.")] + type: Annotated[ + Literal["code_interpreter"], + Field( + description="The type of tool call. This is always going to be `code_interpreter` for this type of tool call." + ), ] - has_more: Annotated[ - bool, Field(description='Indicates whether there are more evals available.') + code_interpreter: Annotated[ + CodeInterpreter7, + Field(description="The Code Interpreter tool call definition."), ] -class EvalRun(BaseModel): - object: Annotated[ - Literal['eval.run'], - Field(description='The type of the object. Always "eval.run".'), - ] - id: Annotated[str, Field(description='Unique identifier for the evaluation run.')] - eval_id: Annotated[ - str, Field(description='The identifier of the associated evaluation.') - ] - status: Annotated[str, Field(description='The status of the evaluation run.')] - model: Annotated[ - str, Field(description='The model that is evaluated, if applicable.') - ] - name: Annotated[str, Field(description='The name of the evaluation run.')] - created_at: Annotated[ - int, +class CodeInterpreter8(BaseModel): + input: Annotated[ + Optional[str], Field(description="The input to the Code Interpreter tool call.") + ] = None + outputs: Annotated[ + Optional[ + List[ + Union[ + RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, + RunStepDeltaStepDetailsToolCallsCodeOutputImageObject, + ] + ] + ], Field( - description='Unix timestamp (in seconds) when the evaluation run was created.' + description="The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type." ), - ] - report_url: Annotated[ - str, + ] = None + + +class RunStepDeltaStepDetailsToolCallsCodeObject(BaseModel): + index: Annotated[int, Field(description="The index of the tool call in the tool calls array.")] + id: Annotated[Optional[str], Field(description="The ID of the tool call.")] = None + type: Annotated[ + Literal["code_interpreter"], Field( - description='The URL to the rendered evaluation run report on the UI dashboard.' + description="The type of tool call. This is always going to be `code_interpreter` for this type of tool call." ), ] - result_counts: Annotated[ - ResultCounts, - Field(description='Counters summarizing the outcomes of the evaluation run.'), - ] - per_model_usage: Annotated[ - List[PerModelUsageItem], - Field(description='Usage statistics for each model during the evaluation run.'), - ] - per_testing_criteria_results: Annotated[ - List[PerTestingCriteriaResult], + code_interpreter: Annotated[ + Optional[CodeInterpreter8], + Field(description="The Code Interpreter tool call definition."), + ] = None + + +class CreateVectorStoreRequest(BaseModel): + class Config: + extra = Extra.forbid + + file_ids: Annotated[ + Optional[List[str]], Field( - description='Results per testing criteria applied during the evaluation run.' + description="A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.", + max_items=500, ), - ] - data_source: Annotated[ - Union[ - CreateEvalJsonlRunDataSource, - CreateEvalCompletionsRunDataSource, - CreateEvalResponsesRunDataSource, - ], + ] = None + name: Annotated[Optional[str], Field(description="The name of the vector store.")] = None + expires_after: Optional[VectorStoreExpirationAfter] = None + chunking_strategy: Annotated[ + Optional[Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam]], Field( - description="Information about the run's data source.", discriminator='type' + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty." ), - ] - metadata: Metadata - error: EvalApiError + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None -class EvalRunList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[List[EvalRun], Field(description='An array of eval run objects.\n')] - first_id: Annotated[ - str, - Field(description='The identifier of the first eval run in the data array.'), - ] - last_id: Annotated[ - str, Field(description='The identifier of the last eval run in the data array.') - ] - has_more: Annotated[ - bool, Field(description='Indicates whether there are more evals available.') - ] +class StaticChunkingStrategyResponseParam(BaseModel): + class Config: + extra = Extra.forbid + + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: StaticChunkingStrategy -class FineTuneReinforcementMethod(BaseModel): - grader: Annotated[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ], - Field(description='The grader used for the fine-tuning job.'), - ] - hyperparameters: Optional[FineTuneReinforcementHyperparameters] = None +class RunStreamEvent1(BaseModel): + event: Literal["thread.run.created"] + data: RunObject -class Item(BaseModel): - __root__: Annotated[ - Union[ - InputMessage, - OutputMessage, - FileSearchToolCall, - ComputerToolCall, - ComputerCallOutputItemParam, - WebSearchToolCall, - FunctionToolCall, - FunctionCallOutputItemParam, - ReasoningItem, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCallItemParam, - FunctionShellCallOutputItemParam, - ApplyPatchToolCallItemParam, - ApplyPatchToolCallOutputItemParam, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponse, - MCPToolCall, - CustomToolCallOutput, - CustomToolCall, - ], - Field( - description='Content item used to generate a response.\n', - discriminator='type', - ), - ] +class RunStreamEvent2(BaseModel): + event: Literal["thread.run.queued"] + data: RunObject -class ItemResource(BaseModel): - __root__: Annotated[ - Union[ - InputMessageResource, - OutputMessage, - FileSearchToolCall, - ComputerToolCall, - ComputerToolCallOutputResource, - WebSearchToolCall, - FunctionToolCallResource, - FunctionToolCallOutputResource, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponseResource, - MCPToolCall, - ], - Field( - description='Content item used to generate a response.\n', - discriminator='type', - ), - ] +class RunStreamEvent3(BaseModel): + event: Literal["thread.run.in_progress"] + data: RunObject -class ListAssistantsResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[AssistantObject] - first_id: Annotated[str, Field(example='asst_abc123')] - last_id: Annotated[str, Field(example='asst_abc456')] - has_more: Annotated[bool, Field(example=False)] +class RunStreamEvent4(BaseModel): + event: Literal["thread.run.requires_action"] + data: RunObject -class ListAuditLogsResponse(BaseModel): - object: Literal['list'] - data: List[AuditLog] - first_id: Annotated[str, Field(example='audit_log-defb456h8dks')] - last_id: Annotated[str, Field(example='audit_log-hnbkd8s93s')] - has_more: bool +class RunStreamEvent5(BaseModel): + event: Literal["thread.run.completed"] + data: RunObject -class ListMessagesResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[MessageObject] - first_id: Annotated[str, Field(example='msg_abc123')] - last_id: Annotated[str, Field(example='msg_abc123')] - has_more: Annotated[bool, Field(example=False)] +class RunStreamEvent6(BaseModel): + event: Literal["thread.run.incomplete"] + data: RunObject -class ListRunStepsResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[RunStepObject] - first_id: Annotated[str, Field(example='step_abc123')] - last_id: Annotated[str, Field(example='step_abc456')] - has_more: Annotated[bool, Field(example=False)] +class RunStreamEvent7(BaseModel): + event: Literal["thread.run.failed"] + data: RunObject -class ModelIds(BaseModel): - __root__: Union[ModelIdsShared, ModelIdsResponses] +class RunStreamEvent8(BaseModel): + event: Literal["thread.run.cancelling"] + data: RunObject -class ModifyAssistantRequest(BaseModel): - class Config: - extra = Extra.forbid +class RunStreamEvent9(BaseModel): + event: Literal["thread.run.cancelled"] + data: RunObject - model: Annotated[ - Optional[Union[str, AssistantSupportedModels]], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n' - ), - ] = None - reasoning_effort: Optional[ReasoningEffort] = None - name: Optional[Name] = None - description: Optional[Description] = None - instructions: Optional[Instructions] = None - tools: Annotated[ - List[AssistantTool], - Field( - description='A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n', - max_items=128, - ), - ] = [] - tool_resources: Optional[ToolResources4] = None - metadata: Optional[Metadata] = None - temperature: Optional[Temperature3] = None - top_p: Optional[TopP3] = None - response_format: Optional[AssistantsApiResponseFormatOption] = None +class RunStreamEvent10(BaseModel): + event: Literal["thread.run.expired"] + data: RunObject -class OutputItem1(BaseModel): - __root__: Annotated[ - Union[ - OutputMessage, - FileSearchToolCall, - FunctionToolCall, - WebSearchToolCall, - ComputerToolCall, - ReasoningItem, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPToolCall, - MCPListTools, - MCPApprovalRequest, - CustomToolCall, - ], - Field(discriminator='type'), + +class RunStreamEvent(BaseModel): + __root__: Union[ + RunStreamEvent1, + RunStreamEvent2, + RunStreamEvent3, + RunStreamEvent4, + RunStreamEvent5, + RunStreamEvent6, + RunStreamEvent7, + RunStreamEvent8, + RunStreamEvent9, + RunStreamEvent10, + ] + + +class ProjectServiceAccountCreateResponse(BaseModel): + object: Literal["organization.project.service_account"] + id: str + name: str + role: Annotated[ + Literal["member"], + Field(description="Service accounts can only have one role of type `member`"), ] + created_at: int + api_key: ProjectServiceAccountApiKey -class RealtimeBetaClientEventConversationItemCreate(BaseModel): - event_id: Annotated[ +class ChatCompletionRequestAssistantMessage(BaseModel): + content: Annotated[ + Optional[Union[str, Content2]], + Field( + description="The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.\n" + ), + ] = None + refusal: Annotated[ + Optional[str], Field(description="The refusal message by the assistant.") + ] = None + role: Annotated[ + Literal["assistant"], + Field(description="The role of the messages author, in this case `assistant`."), + ] + name: Annotated[ Optional[str], Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, + description="An optional name for the participant. Provides the model information to differentiate between participants of the same role." ), ] = None - type: Annotated[ - str, + tool_calls: Optional[ChatCompletionMessageToolCalls] = None + function_call: Annotated[ + Optional[FunctionCall], Field( - const=True, - description='The event type, must be `conversation.item.create`.', + description="Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." ), - ] = 'conversation.item.create' - previous_item_id: Annotated[ - Optional[str], + ] = None + + +class FineTuneChatCompletionRequestAssistantMessage(ChatCompletionRequestAssistantMessage): + weight: Annotated[ + Optional[Literal[0, 1]], + Field(description="Controls whether the assistant message is trained against (0 or 1)"), + ] = None + role: Annotated[ + Literal["assistant"], + Field(description="The role of the messages author, in this case `assistant`."), + ] + + +class ListPaginatedFineTuningJobsResponse(BaseModel): + data: List[FineTuningJob] + has_more: bool + object: Literal["list"] + + +class FinetuneChatRequestInput(BaseModel): + messages: Annotated[ + Optional[ + List[ + Union[ + ChatCompletionRequestSystemMessage, + ChatCompletionRequestUserMessage, + FineTuneChatCompletionRequestAssistantMessage, + ChatCompletionRequestToolMessage, + ChatCompletionRequestFunctionMessage, + ] + ] + ], + Field(min_items=1), + ] = None + tools: Annotated[ + Optional[List[ChatCompletionTool]], + Field(description="A list of tools the model may generate JSON inputs for."), + ] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + functions: Annotated[ + Optional[List[ChatCompletionFunctions]], Field( - description='The ID of the preceding item after which the new item will be inserted. \nIf not set, the new item will be appended to the end of the conversation.\nIf set to `root`, the new item will be added to the beginning of the conversation.\nIf set to an existing ID, it allows an item to be inserted mid-conversation. If the\nID cannot be found, an error will be returned and the item will not be added.\n' + description="A list of functions the model may generate JSON inputs for.", + max_items=128, + min_items=1, ), ] = None - item: RealtimeConversationItem -class RealtimeBetaClientEventSessionUpdate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, Field(const=True, description='The event type, must be `session.update`.') - ] = 'session.update' - session: RealtimeSessionCreateRequest - +class CreateRunRequest(BaseModel): + class Config: + extra = Extra.forbid -class RealtimeBetaResponse(BaseModel): - id: Annotated[ - Optional[str], Field(description='The unique ID of the response.') - ] = None - object: Annotated[ + assistant_id: Annotated[ str, - Field(const=True, description='The object type, must be `realtime.response`.'), - ] = 'realtime.response' - status: Annotated[ + Field( + description="The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run." + ), + ] + model: Annotated[ Optional[ - Literal['completed', 'cancelled', 'failed', 'incomplete', 'in_progress'] + Union[ + str, + Literal[ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] ], Field( - description='The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n' + description="The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + example="gpt-4o", ), ] = None - status_details: Annotated[ - Optional[StatusDetails], - Field(description='Additional details about the status.'), - ] = None - output: Annotated[ - Optional[List[RealtimeConversationItem]], - Field(description='The list of output items generated by the response.'), - ] = None - metadata: Optional[Metadata] = None - usage: Annotated[ - Optional[Usage3], + instructions: Annotated[ + Optional[str], Field( - description='Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n' + description="Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis." ), ] = None - conversation_id: Annotated[ + additional_instructions: Annotated[ Optional[str], Field( - description='Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nby server VAD, the response will be added to the default conversation, thus\nthe `conversation_id` will be an id like `conv_1234`.\n' + description="Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions." ), ] = None - voice: Annotated[ - Optional[VoiceIdsShared], - Field( - description='The voice the model used to respond.\nCurrent voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' - ), + additional_messages: Annotated[ + Optional[List[CreateMessageRequest]], + Field(description="Adds additional messages to the thread before creating the run."), ] = None - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], + tools: Annotated[ + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]]], Field( - description='The set of modalities the model used to respond. If there are multiple modalities,\nthe model will pick one, for example if `modalities` is `["text", "audio"]`, the model\ncould be responding in either text or audio.\n' + description="Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + max_items=20, ), ] = None - output_audio_format: Annotated[ - Optional[Literal['pcm16', 'g711_ulaw', 'g711_alaw']], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None temperature: Annotated[ Optional[float], Field( - description='Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n' - ), - ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n' - ), - ] = None - - -class RealtimeBetaResponseCreateParams(BaseModel): - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + example=1, + ge=0.0, + le=2.0, ), - ] = None - instructions: Annotated[ - Optional[str], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - description='The default system instructions (i.e. system message) prepended to model \ncalls. This field allows the client to guide the model on desired \nresponses. The model can be instructed on response content and format, \n(e.g. "be extremely succinct", "act friendly", "here are examples of good \nresponses") and on audio behavior (e.g. "talk quickly", "inject emotion \ninto your voice", "laugh frequently"). The instructions are not guaranteed \nto be followed by the model, but they provide guidance to the model on the \ndesired behavior.\n\nNote that the server sets default instructions which will be used if this \nfield is not set and are visible in the `session.created` event at the \nstart of the session.\n' + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + example=1, + ge=0.0, + le=1.0, ), - ] = None - voice: Annotated[ - Optional[VoiceIdsShared], + ] = 1 + stream: Annotated[ + Optional[bool], Field( - description='The voice the model uses to respond. Voice cannot be changed during the \nsession once the model has responded with audio at least once. Current \nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' + description="If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" ), ] = None - output_audio_format: Annotated[ - Optional[Literal['pcm16', 'g711_ulaw', 'g711_alaw']], + max_prompt_tokens: Annotated[ + Optional[int], Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' + description="The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, ), ] = None - tools: Annotated[ - Optional[List[Tool1]], - Field(description='Tools (functions) available to the model.'), - ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - temperature: Annotated[ - Optional[float], + max_completion_tokens: Annotated[ + Optional[int], Field( - description='Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n' + description="The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, ), ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + truncation_strategy: Optional[TruncationObject] = None + tool_choice: Optional[AssistantsApiToolChoiceOption] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + response_format: Optional[AssistantsApiResponseFormatOption] = None + + +class CreateThreadRequest(BaseModel): + class Config: + extra = Extra.forbid + + messages: Annotated[ + Optional[List[CreateMessageRequest]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="A list of [messages](/docs/api-reference/messages) to start the thread with." ), ] = None - conversation: Annotated[ - Optional[Union[str, Literal['auto', 'none']]], + tool_resources: Annotated[ + Optional[ToolResources5], Field( - description='Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which \nwill not add items to default conversation.\n' + description="A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), ] = None - metadata: Optional[Metadata] = None - prompt: Optional[Prompt2] = None - input: Annotated[ - Optional[List[RealtimeConversationItem]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items from the default conversation.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None -class RealtimeBetaServerEventConversationItemCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ +class MessageObject(BaseModel): + id: Annotated[ str, - Field( - const=True, - description='The event type, must be `conversation.item.created`.', - ), - ] = 'conversation.item.created' - previous_item_id: Optional[str] = None - item: RealtimeConversationItem - - -class RealtimeBetaServerEventConversationItemRetrieved(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["thread.message"], + Field(description="The object type, which is always `thread.message`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the message was created."), + ] + thread_id: Annotated[ str, Field( - const=True, - description='The event type, must be `conversation.item.retrieved`.', + description="The [thread](/docs/api-reference/threads) ID that this message belongs to." ), - ] = 'conversation.item.retrieved' - item: RealtimeConversationItem - - -class RealtimeBetaServerEventResponseCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, - Field(const=True, description='The event type, must be `response.created`.'), - ] = 'response.created' - response: RealtimeBetaResponse - - -class RealtimeBetaServerEventResponseDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, Field(const=True, description='The event type, must be `response.done`.') - ] = 'response.done' - response: RealtimeBetaResponse - - -class RealtimeBetaServerEventResponseOutputItemAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, + ] + status: Annotated[ + Literal["in_progress", "incomplete", "completed"], Field( - const=True, - description='The event type, must be `response.output_item.added`.', + description="The status of the message, which can be either `in_progress`, `incomplete`, or `completed`." ), - ] = 'response.output_item.added' - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') + incomplete_details: Annotated[ + IncompleteDetails1, + Field(description="On an incomplete message, details about why the message is incomplete."), ] - item: RealtimeConversationItem - - -class RealtimeBetaServerEventResponseOutputItemDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, + completed_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the message was completed."), + ] + incomplete_at: Annotated[ + int, Field( - const=True, - description='The event type, must be `response.output_item.done`.', + description="The Unix timestamp (in seconds) for when the message was marked as incomplete." ), - ] = 'response.output_item.done' - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') + role: Annotated[ + Literal["user", "assistant"], + Field(description="The entity that produced the message. One of `user` or `assistant`."), + ] + content: Annotated[ + List[ + Union[ + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageContentTextObject, + MessageContentRefusalObject, + ] + ], + Field(description="The content of the message in array of text and/or images."), ] - item: RealtimeConversationItem - - -class RealtimeBetaServerEventSessionCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, Field(const=True, description='The event type, must be `session.created`.') - ] = 'session.created' - session: RealtimeSession - - -class RealtimeBetaServerEventSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - str, Field(const=True, description='The event type, must be `session.updated`.') - ] = 'session.updated' - session: RealtimeSession - - -class RealtimeCallCreateRequest(BaseModel): - class Config: - extra = Extra.forbid - - sdp: Annotated[ + assistant_id: Annotated[ str, Field( - description='WebRTC Session Description Protocol (SDP) offer generated by the caller.' + description="If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message." ), ] - session: Annotated[ - Optional[RealtimeSessionCreateRequestGA], - Field( - description='Optional session configuration to apply before the realtime session is\ncreated. Use the same parameters you would send in a [`create client secret`](https://platform.openai.com/docs/api-reference/realtime-sessions/create-realtime-client-secret)\nrequest.', - title='Session configuration', - ), - ] = None - - -class RealtimeClientEventConversationItemCreate(BaseModel): - event_id: Annotated[ - Optional[str], + run_id: Annotated[ + str, Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, + description="The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints." ), - ] = None - type: Annotated[ - Literal['conversation.item.create'], + ] + attachments: Annotated[ + List[Attachment], Field( - const=True, - description='The event type, must be `conversation.item.create`.', + description="A list of files attached to the message, and the tools they were added to." ), ] - previous_item_id: Annotated[ - Optional[str], + metadata: Annotated[ + Dict[str, Any], Field( - description='The ID of the preceding item after which the new item will be inserted. \nIf not set, the new item will be appended to the end of the conversation.\nIf set to `root`, the new item will be added to the beginning of the conversation.\nIf set to an existing ID, it allows an item to be inserted mid-conversation. If the\nID cannot be found, an error will be returned and the item will not be added.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = None - item: RealtimeConversationItem + ] -class RealtimeClientEventResponseCreate(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), +class Delta(BaseModel): + role: Annotated[ + Optional[Literal["user", "assistant"]], + Field(description="The entity that produced the message. One of `user` or `assistant`."), + ] = None + content: Annotated[ + Optional[ + List[ + Union[ + MessageDeltaContentImageFileObject, + MessageDeltaContentTextObject, + MessageDeltaContentRefusalObject, + MessageDeltaContentImageUrlObject, + ] + ] + ], + Field(description="The content of the message in array of text and/or images."), ] = None - type: Annotated[ - Literal['response.create'], - Field(const=True, description='The event type, must be `response.create`.'), - ] - response: Optional[RealtimeResponseCreateParams] = None -class RealtimeClientEventSessionUpdate(BaseModel): - event_id: Annotated[ - Optional[str], +class MessageDeltaObject(BaseModel): + id: Annotated[ + str, Field( - description='Optional client-generated ID used to identify this event. This is an arbitrary string that a client may assign. It will be passed back if there is an error with the event, but the corresponding `session.updated` event will not include it.', - max_length=512, + description="The identifier of the message, which can be referenced in API endpoints." ), - ] = None - type: Annotated[ - Literal['session.update'], - Field(const=True, description='The event type, must be `session.update`.'), ] - session: Annotated[ - Union[ - RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA + object: Annotated[ + Literal["thread.message.delta"], + Field(description="The object type, which is always `thread.message.delta`."), + ] + delta: Annotated[ + Delta, + Field(description="The delta containing the fields that have changed on the Message."), + ] + + +class ListMessagesResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[MessageObject] + first_id: Annotated[str, Field(example="msg_abc123")] + last_id: Annotated[str, Field(example="msg_abc123")] + has_more: Annotated[bool, Field(example=False)] + + +class RunStepDetailsToolCallsObject(BaseModel): + type: Annotated[Literal["tool_calls"], Field(description="Always `tool_calls`.")] + tool_calls: Annotated[ + List[ + Union[ + RunStepDetailsToolCallsCodeObject, + RunStepDetailsToolCallsFileSearchObject, + RunStepDetailsToolCallsFunctionObject, + ] ], Field( - description='Update the Realtime session. Choose either a realtime\nsession or a transcription session.\n' + description="An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n" ), ] -class RealtimeCreateClientSecretRequest(BaseModel): - expires_after: Annotated[ - Optional[ExpiresAfter2], - Field( - description='Configuration for the client secret expiration. Expiration refers to the time after which\na client secret will no longer be valid for creating sessions. The session itself may\ncontinue after that time once started. A secret can be used to create multiple sessions\nuntil it expires.\n', - title='Client secret expiration', - ), - ] = None - session: Annotated[ +class RunStepDeltaStepDetailsToolCallsObject(BaseModel): + type: Annotated[Literal["tool_calls"], Field(description="Always `tool_calls`.")] + tool_calls: Annotated[ Optional[ - Union[ - RealtimeSessionCreateRequestGA, - RealtimeTranscriptionSessionCreateRequestGA, + List[ + Union[ + RunStepDeltaStepDetailsToolCallsCodeObject, + RunStepDeltaStepDetailsToolCallsFileSearchObject, + RunStepDeltaStepDetailsToolCallsFunctionObject, + ] ] ], Field( - description='Session configuration to use for the client secret. Choose either a realtime\nsession or a transcription session.\n', - discriminator='type', - title='Session configuration', + description="An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n" ), ] = None -class RealtimeCreateClientSecretResponse(BaseModel): - value: Annotated[str, Field(description='The generated client secret value.')] - expires_at: Annotated[ +class VectorStoreFileObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["vector_store.file"], + Field(description="The object type, which is always `vector_store.file`."), + ] + usage_bytes: Annotated[ int, Field( - description='Expiration timestamp for the client secret, in seconds since epoch.' + description="The total vector store usage in bytes. Note that this may be different from the original file size." ), ] - session: Annotated[ - Union[ - RealtimeSessionCreateResponseGA, - RealtimeTranscriptionSessionCreateResponseGA, - ], + created_at: Annotated[ + int, Field( - description='The session configuration for either a realtime or transcription session.\n', - discriminator='type', - title='Session configuration', + description="The Unix timestamp (in seconds) for when the vector store file was created." ), ] - - -class RealtimeServerEventSessionCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['session.created'], - Field(const=True, description='The event type, must be `session.created`.'), + vector_store_id: Annotated[ + str, + Field( + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to." + ), ] - session: Annotated[ - Union[ - RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA - ], - Field(description='The session configuration.'), + status: Annotated[ + Literal["in_progress", "completed", "cancelled", "failed"], + Field( + description="The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use." + ), + ] + last_error: Annotated[ + LastError2, + Field( + description="The last error associated with this vector store file. Will be `null` if there are no errors." + ), ] + chunking_strategy: Annotated[ + Optional[Union[StaticChunkingStrategyResponseParam, OtherChunkingStrategyResponseParam]], + Field(description="The strategy used to chunk the file."), + ] = None -class RealtimeServerEventSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['session.updated'], - Field(const=True, description='The event type, must be `session.updated`.'), - ] - session: Annotated[ - Union[ - RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA - ], - Field(description='The session configuration.'), - ] +class ListVectorStoreFilesResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[VectorStoreFileObject] + first_id: Annotated[str, Field(example="file-abc123")] + last_id: Annotated[str, Field(example="file-abc456")] + has_more: Annotated[bool, Field(example=False)] + + +class MessageStreamEvent1(BaseModel): + event: Literal["thread.message.created"] + data: MessageObject -class ResponseItemList(BaseModel): - object: Annotated[ - str, - Field(const=True, description='The type of object returned, must be `list`.'), - ] = 'list' - data: Annotated[ - List[ItemResource], - Field(description='A list of items used to generate this response.'), - ] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - first_id: Annotated[str, Field(description='The ID of the first item in the list.')] - last_id: Annotated[str, Field(description='The ID of the last item in the list.')] +class MessageStreamEvent2(BaseModel): + event: Literal["thread.message.in_progress"] + data: MessageObject -class ResponseOutputItemAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseOutputItemAddedEvent'], - Field( - description='The type of the event. Always `response.output_item.added`.\n' - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item that was added.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - item: Annotated[OutputItem1, Field(description='The output item that was added.\n')] +class MessageStreamEvent3(BaseModel): + event: Literal["thread.message.delta"] + data: MessageDeltaObject -class ResponseOutputItemDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseOutputItemDoneEvent'], - Field( - description='The type of the event. Always `response.output_item.done`.\n' - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item that was marked done.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - item: Annotated[ - OutputItem1, Field(description='The output item that was marked done.\n') - ] +class MessageStreamEvent4(BaseModel): + event: Literal["thread.message.completed"] + data: MessageObject -class ResponseProperties(BaseModel): - previous_response_id: Optional[str] = None - model: Annotated[ - Optional[ModelIdsResponses], - Field( - description='Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\nto browse and compare available models.\n' - ), - ] = None - reasoning: Optional[Reasoning] = None - background: Optional[bool] = None - max_output_tokens: Optional[int] = None - max_tool_calls: Optional[int] = None - text: Optional[ResponseTextParam] = None - tools: Optional[ToolsArray] = None - tool_choice: Optional[ToolChoiceParam] = None - prompt: Optional[Prompt2] = None - truncation: Optional[Literal['auto', 'disabled']] = None +class MessageStreamEvent5(BaseModel): + event: Literal["thread.message.incomplete"] + data: MessageObject -class RunObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), +class MessageStreamEvent(BaseModel): + __root__: Union[ + MessageStreamEvent1, + MessageStreamEvent2, + MessageStreamEvent3, + MessageStreamEvent4, + MessageStreamEvent5, ] - object: Annotated[ - Literal['thread.run'], - Field(description='The object type, which is always `thread.run`.'), + + +class ChatCompletionRequestMessage(BaseModel): + __root__: Annotated[ + Union[ + ChatCompletionRequestSystemMessage, + ChatCompletionRequestUserMessage, + ChatCompletionRequestAssistantMessage, + ChatCompletionRequestToolMessage, + ChatCompletionRequestFunctionMessage, + ], + Field(discriminator="role"), ] - created_at: Annotated[ - int, + + +class CreateChatCompletionRequest(BaseModel): + messages: Annotated[ + List[ChatCompletionRequestMessage], Field( - description='The Unix timestamp (in seconds) for when the run was created.' + description="A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models).", + min_items=1, ), ] - thread_id: Annotated[ - str, + model: Annotated[ + Union[ + str, + Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "chatgpt-4o-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ], Field( - description='The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed on as a part of this run.' + description="ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API.", + example="gpt-4o", ), ] - assistant_id: Annotated[ - str, + frequency_penalty: Annotated[ + Optional[float], Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for execution of this run.' + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] - status: RunStatus - required_action: Annotated[ - Optional[RequiredAction], + ] = 0 + logit_bias: Annotated[ + Optional[Dict[str, int]], Field( - description='Details on the action required to continue the run. Will be `null` if no action is required.' + description="Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n" ), - ] - last_error: Annotated[ - Optional[LastError], + ] = None + logprobs: Annotated[ + Optional[bool], Field( - description='The last error associated with this run. Will be `null` if there are no errors.' + description="Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`." ), - ] - expires_at: Annotated[ + ] = False + top_logprobs: Annotated[ Optional[int], Field( - description='The Unix timestamp (in seconds) for when the run will expire.' + description="An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used.", + ge=0, + le=20, ), - ] - started_at: Annotated[ + ] = None + max_tokens: Annotated[ Optional[int], Field( - description='The Unix timestamp (in seconds) for when the run was started.' + description="The maximum number of [tokens](/tokenizer) that can be generated in the chat completion.\n\nThe total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n" ), - ] - cancelled_at: Annotated[ + ] = None + n: Annotated[ Optional[int], Field( - description='The Unix timestamp (in seconds) for when the run was cancelled.' + description="How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs.", + example=1, + ge=1, + le=128, ), - ] - failed_at: Annotated[ - Optional[int], - Field(description='The Unix timestamp (in seconds) for when the run failed.'), - ] - completed_at: Annotated[ - Optional[int], + ] = 1 + presence_penalty: Annotated[ + Optional[float], Field( - description='The Unix timestamp (in seconds) for when the run was completed.' + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] - incomplete_details: Annotated[ - Optional[IncompleteDetails2], + ] = 0 + response_format: Annotated[ + Optional[Union[ResponseFormatText, ResponseFormatJsonObject, ResponseFormatJsonSchema]], Field( - description='Details on why the run is incomplete. Will be `null` if the run is not incomplete.' + description='An object specifying the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4o mini](/docs/models/gpt-4o-mini), [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n' ), - ] - model: Annotated[ - str, + ] = None + seed: Annotated[ + Optional[int], Field( - description='The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.' + description="This feature is in Beta.\nIf specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n", + ge=-9223372036854775808, + le=9223372036854775807, ), - ] - instructions: Annotated[ - str, + ] = None + service_tier: Annotated[ + Optional[Literal["auto", "default"]], Field( - description='The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.' + description="Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:\n - If set to 'auto', the system will utilize scale tier credits until they are exhausted.\n - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee.\n - When not set, the default behavior is 'auto'.\n\n When this parameter is set, the response body will include the `service_tier` utilized.\n" ), - ] - tools: Annotated[ - List[AssistantTool], + ] = None + stop: Annotated[ + Optional[Union[str, Stop1]], + Field(description="Up to 4 sequences where the API will stop generating further tokens.\n"), + ] = None + stream: Annotated[ + Optional[bool], Field( - description='The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.', - max_items=20, + description="If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n" ), - ] - metadata: Metadata - usage: RunCompletionUsage + ] = False + stream_options: Optional[ChatCompletionStreamOptions] = None temperature: Annotated[ Optional[float], Field( - description='The sampling temperature used for this run. If not set, defaults to 1.' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n", + example=1, + ge=0.0, + le=2.0, ), - ] = None + ] = 1 top_p: Annotated[ Optional[float], Field( - description='The nucleus sampling value used for this run. If not set, defaults to 1.' + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n", + example=1, + ge=0.0, + le=1.0, + ), + ] = 1 + tools: Annotated[ + Optional[List[ChatCompletionTool]], + Field( + description="A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n" ), ] = None - max_prompt_tokens: Annotated[ - Optional[int], + tool_choice: Optional[ChatCompletionToolChoiceOption] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + user: Annotated[ + Optional[str], Field( - description='The maximum number of prompt tokens specified to have been used over the course of the run.\n', - ge=256, + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + example="user-1234", ), - ] - max_completion_tokens: Annotated[ - Optional[int], + ] = None + function_call: Annotated[ + Optional[Union[Literal["none", "auto"], ChatCompletionFunctionCallOption]], Field( - description='The maximum number of completion tokens specified to have been used over the course of the run.\n', - ge=256, + description='Deprecated in favor of `tool_choice`.\n\nControls which (if any) function is called by the model.\n`none` means the model will not call a function and instead generates a message.\n`auto` means the model can pick between generating a message or calling a function.\nSpecifying a particular function via `{"name": "my_function"}` forces the model to call that function.\n\n`none` is the default when no functions are present. `auto` is the default if functions are present.\n' ), - ] - truncation_strategy: TruncationObject - tool_choice: AssistantsApiToolChoiceOption - parallel_tool_calls: ParallelToolCalls - response_format: Annotated[Optional[AssistantsApiResponseFormatOption], Field(...)] - - -class RunStepDeltaObject(BaseModel): - id: Annotated[ - str, + ] = None + functions: Annotated[ + Optional[List[ChatCompletionFunctions]], Field( - description='The identifier of the run step, which can be referenced in API endpoints.' + description="Deprecated in favor of `tools`.\n\nA list of functions the model may generate JSON inputs for.\n", + max_items=128, + min_items=1, ), - ] - object: Annotated[ - Literal['thread.run.step.delta'], - Field(description='The object type, which is always `thread.run.step.delta`.'), - ] - delta: RunStepDeltaObjectDelta - - -class RunStepStreamEvent3(BaseModel): - event: Literal['2#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepDeltaObject - - -class RunStepStreamEvent(BaseModel): - __root__: Annotated[ - Union[ - RunStepStreamEvent1, - RunStepStreamEvent2, - RunStepStreamEvent3, - RunStepStreamEvent4, - RunStepStreamEvent5, - RunStepStreamEvent6, - RunStepStreamEvent7, - ], - Field(discriminator='event'), - ] - - -class RunStreamEvent1(BaseModel): - event: Literal['0#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent2(BaseModel): - event: Literal['1#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent3(BaseModel): - event: Literal['2#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent4(BaseModel): - event: Literal['3#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent5(BaseModel): - event: Literal['4#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent6(BaseModel): - event: Literal['5#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent7(BaseModel): - event: Literal['6#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent8(BaseModel): - event: Literal['7#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent9(BaseModel): - event: Literal['8#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - + ] = None -class RunStreamEvent10(BaseModel): - event: Literal['9#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject +class CreateThreadAndRunRequest(BaseModel): + class Config: + extra = Extra.forbid -class RunStreamEvent(BaseModel): - __root__: Annotated[ - Union[ - RunStreamEvent1, - RunStreamEvent2, - RunStreamEvent3, - RunStreamEvent4, - RunStreamEvent5, - RunStreamEvent6, - RunStreamEvent7, - RunStreamEvent8, - RunStreamEvent9, - RunStreamEvent10, - ], - Field(discriminator='event'), + assistant_id: Annotated[ + str, + Field( + description="The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run." + ), ] - - -class AssistantStreamEvent(BaseModel): - __root__: Annotated[ - Union[ - ThreadStreamEvent, - RunStreamEvent, - RunStepStreamEvent, - MessageStreamEvent, - ErrorEvent, + thread: Annotated[ + Optional[CreateThreadRequest], + Field(description="If no thread is provided, an empty thread will be created."), + ] = None + model: Annotated[ + Optional[ + Union[ + str, + Literal[ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] ], Field( - description='Represents an event emitted when streaming a Run.\n\nEach event in a server-sent events stream has an `event` and `data` property:\n\n```\nevent: thread.created\ndata: {"id": "thread_123", "object": "thread", ...}\n```\n\nWe emit events whenever a new object is created, transitions to a new state, or is being\nstreamed in parts (deltas). For example, we emit `thread.run.created` when a new run\nis created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses\nto create a message during a run, we emit a `thread.message.created event`, a\n`thread.message.in_progress` event, many `thread.message.delta` events, and finally a\n`thread.message.completed` event.\n\nWe may add additional events over time, so we recommend handling unknown events gracefully\nin your code. See the [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn how to\nintegrate the Assistants API with streaming.\n', - discriminator='event', + description="The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + example="gpt-4o", + ), + ] = None + instructions: Annotated[ + Optional[str], + Field( + description="Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis." ), - ] - - -class FineTuneMethod(BaseModel): - type: Annotated[ - Literal['supervised', 'dpo', 'reinforcement'], + ] = None + tools: Annotated[ + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]]], Field( - description='The type of method. Is either `supervised`, `dpo`, or `reinforcement`.' + description="Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + max_items=20, ), - ] - supervised: Optional[FineTuneSupervisedMethod] = None - dpo: Optional[FineTuneDPOMethod] = None - reinforcement: Optional[FineTuneReinforcementMethod] = None + ] = None + tool_resources: Annotated[ + Optional[ToolResources3], + Field( + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None + temperature: Annotated[ + Optional[float], + Field( + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + example=1, + ge=0.0, + le=2.0, + ), + ] = 1 + top_p: Annotated[ + Optional[float], + Field( + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + example=1, + ge=0.0, + le=1.0, + ), + ] = 1 + stream: Annotated[ + Optional[bool], + Field( + description="If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + ), + ] = None + max_prompt_tokens: Annotated[ + Optional[int], + Field( + description="The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, + ), + ] = None + max_completion_tokens: Annotated[ + Optional[int], + Field( + description="The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, + ), + ] = None + truncation_strategy: Optional[TruncationObject] = None + tool_choice: Optional[AssistantsApiToolChoiceOption] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + response_format: Optional[AssistantsApiResponseFormatOption] = None -class FineTuningJob(BaseModel): +class RunStepObject(BaseModel): id: Annotated[ str, Field( - description='The object identifier, which can be referenced in the API endpoints.' + description="The identifier of the run step, which can be referenced in API endpoints." ), ] + object: Annotated[ + Literal["thread.run.step"], + Field(description="The object type, which is always `thread.run.step`."), + ] created_at: Annotated[ int, - Field( - description='The Unix timestamp (in seconds) for when the fine-tuning job was created.' - ), + Field(description="The Unix timestamp (in seconds) for when the run step was created."), ] - error: Optional[Error2] - fine_tuned_model: Optional[str] - finished_at: Optional[int] - hyperparameters: Annotated[ - Hyperparameters1, + assistant_id: Annotated[ + str, Field( - description='The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs.' + description="The ID of the [assistant](/docs/api-reference/assistants) associated with the run step." ), ] - model: Annotated[str, Field(description='The base model that is being fine-tuned.')] - object: Annotated[ - Literal['fine_tuning.job'], - Field(description='The object type, which is always "fine_tuning.job".'), + thread_id: Annotated[ + str, + Field(description="The ID of the [thread](/docs/api-reference/threads) that was run."), ] - organization_id: Annotated[ - str, Field(description='The organization that owns the fine-tuning job.') + run_id: Annotated[ + str, + Field( + description="The ID of the [run](/docs/api-reference/runs) that this run step is a part of." + ), ] - result_files: Annotated[ - List[str], + type: Annotated[ + Literal["message_creation", "tool_calls"], Field( - description='The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).' + description="The type of run step, which can be either `message_creation` or `tool_calls`." ), ] status: Annotated[ - Literal[ - 'validating_files', 'queued', 'running', 'succeeded', 'failed', 'cancelled' - ], + Literal["in_progress", "cancelled", "failed", "completed", "expired"], Field( - description='The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.' + description="The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`." ), ] - trained_tokens: Optional[int] - training_file: Annotated[ - str, + step_details: Annotated[ + Union[RunStepDetailsMessageCreationObject, RunStepDetailsToolCallsObject], + Field(description="The details of the run step."), + ] + last_error: Annotated[ + LastError1, Field( - description='The file ID used for training. You can retrieve the training data with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).' + description="The last error associated with this run step. Will be `null` if there are no errors." ), ] - validation_file: Optional[str] - integrations: Optional[Integrations] = None - seed: Annotated[int, Field(description='The seed used for the fine-tuning job.')] - estimated_finish: Optional[int] = None - method: Optional[FineTuneMethod] = None - metadata: Optional[Metadata] = None - - -class InputItem1(BaseModel): - __root__: Annotated[ - Union[EasyInputMessage, Item, ItemReferenceParam], Field(discriminator='type') - ] - - -class InputParam(BaseModel): - __root__: Annotated[ - Union[str, List[InputItem1]], + expired_at: Annotated[ + int, Field( - description='Text, image, or file inputs to the model, used to generate a response.\n\nLearn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Image inputs](https://platform.openai.com/docs/guides/images)\n- [File inputs](https://platform.openai.com/docs/guides/pdf-files)\n- [Conversation state](https://platform.openai.com/docs/guides/conversation-state)\n- [Function calling](https://platform.openai.com/docs/guides/function-calling)\n' + description="The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired." ), ] - - -class ListPaginatedFineTuningJobsResponse(BaseModel): - data: List[FineTuningJob] - has_more: bool - object: Literal['list'] - - -class ListRunsResponse(BaseModel): - object: Annotated[str, Field(example='list')] - data: List[RunObject] - first_id: Annotated[str, Field(example='run_abc123')] - last_id: Annotated[str, Field(example='run_abc456')] - has_more: Annotated[bool, Field(example=False)] - - -class RealtimeBetaClientEventResponseCreate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - str, Field(const=True, description='The event type, must be `response.create`.') - ] = 'response.create' - response: Optional[RealtimeBetaResponseCreateParams] = None - - -class RealtimeClientEvent(BaseModel): - __root__: Annotated[ - Union[ - RealtimeClientEventConversationItemCreate, - RealtimeClientEventConversationItemDelete, - RealtimeClientEventConversationItemRetrieve, - RealtimeClientEventConversationItemTruncate, - RealtimeClientEventInputAudioBufferAppend, - RealtimeClientEventInputAudioBufferClear, - RealtimeClientEventOutputAudioBufferClear, - RealtimeClientEventInputAudioBufferCommit, - RealtimeClientEventResponseCancel, - RealtimeClientEventResponseCreate, - RealtimeClientEventSessionUpdate, - ], - Field(description='A realtime client event.\n', discriminator='type'), + cancelled_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run step was cancelled."), ] - - -class RealtimeServerEvent(BaseModel): - __root__: Annotated[ - Union[ - RealtimeServerEventConversationCreated, - RealtimeServerEventConversationItemCreated, - RealtimeServerEventConversationItemDeleted, - RealtimeServerEventConversationItemInputAudioTranscriptionCompleted, - RealtimeServerEventConversationItemInputAudioTranscriptionDelta, - RealtimeServerEventConversationItemInputAudioTranscriptionFailed, - RealtimeServerEventConversationItemRetrieved, - RealtimeServerEventConversationItemTruncated, - RealtimeServerEventError, - RealtimeServerEventInputAudioBufferCleared, - RealtimeServerEventInputAudioBufferCommitted, - RealtimeServerEventInputAudioBufferSpeechStarted, - RealtimeServerEventInputAudioBufferSpeechStopped, - RealtimeServerEventRateLimitsUpdated, - RealtimeServerEventResponseAudioDelta, - RealtimeServerEventResponseAudioDone, - RealtimeServerEventResponseAudioTranscriptDelta, - RealtimeServerEventResponseAudioTranscriptDone, - RealtimeServerEventResponseContentPartAdded, - RealtimeServerEventResponseContentPartDone, - RealtimeServerEventResponseCreated, - RealtimeServerEventResponseDone, - RealtimeServerEventResponseFunctionCallArgumentsDelta, - RealtimeServerEventResponseFunctionCallArgumentsDone, - RealtimeServerEventResponseOutputItemAdded, - RealtimeServerEventResponseOutputItemDone, - RealtimeServerEventResponseTextDelta, - RealtimeServerEventResponseTextDone, - RealtimeServerEventSessionCreated, - RealtimeServerEventSessionUpdated, - RealtimeServerEventOutputAudioBufferStarted, - RealtimeServerEventOutputAudioBufferStopped, - RealtimeServerEventOutputAudioBufferCleared, - RealtimeServerEventConversationItemAdded, - RealtimeServerEventConversationItemDone, - RealtimeServerEventInputAudioBufferTimeoutTriggered, - RealtimeServerEventConversationItemInputAudioTranscriptionSegment, - RealtimeServerEventMCPListToolsInProgress, - RealtimeServerEventMCPListToolsCompleted, - RealtimeServerEventMCPListToolsFailed, - RealtimeServerEventResponseMCPCallArgumentsDelta, - RealtimeServerEventResponseMCPCallArgumentsDone, - RealtimeServerEventResponseMCPCallInProgress, - RealtimeServerEventResponseMCPCallCompleted, - RealtimeServerEventResponseMCPCallFailed, - ], - Field(description='A realtime server event.\n', discriminator='type'), + failed_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run step failed."), ] - - -class Response1(ModelResponseProperties, ResponseProperties): - id: Annotated[str, Field(description='Unique identifier for this Response.\n')] - object: Annotated[ - Literal['response'], + completed_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run step completed."), + ] + metadata: Annotated[ + Dict[str, Any], Field( - description='The object type of this resource - always set to `response`.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] - status: Annotated[ + usage: RunStepCompletionUsage + + +class Delta1(BaseModel): + step_details: Annotated[ Optional[ - Literal[ - 'completed', - 'failed', - 'in_progress', - 'cancelled', - 'queued', - 'incomplete', + Union[ + RunStepDeltaStepDetailsMessageCreationObject, + RunStepDeltaStepDetailsToolCallsObject, ] ], - Field( - description='The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n' - ), + Field(description="The details of the run step."), ] = None - created_at: Annotated[ - float, - Field( - description='Unix timestamp (in seconds) of when this Response was created.\n' - ), - ] - error: ResponseError - incomplete_details: Optional[IncompleteDetails1] - output: Annotated[ - List[OutputItem1], - Field( - description="An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" - ), - ] - instructions: Optional[Union[str, List[InputItem1]]] - output_text: Optional[str] = None - usage: Optional[ResponseUsage] = None - parallel_tool_calls: Annotated[ - bool, - Field( - description='Whether to allow the model to run tool calls in parallel.\n' - ), - ] - conversation: Optional[Conversation2] = None -class ResponseCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseCompletedEvent'], - Field(description='The type of the event. Always `response.completed`.\n'), +class RunStepDeltaObject(BaseModel): + id: Annotated[ + str, + Field( + description="The identifier of the run step, which can be referenced in API endpoints." + ), ] - response: Annotated[ - Response1, Field(description='Properties of the completed response.\n') + object: Annotated[ + Literal["thread.run.step.delta"], + Field(description="The object type, which is always `thread.run.step.delta`."), ] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') + delta: Annotated[ + Delta1, + Field(description="The delta containing the fields that have changed on the run step."), ] -class ResponseCreatedEvent(BaseModel): - type: Annotated[ - Literal['ResponseCreatedEvent'], - Field(description='The type of the event. Always `response.created`.\n'), - ] - response: Annotated[ - Response1, Field(description='The response that was created.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] +class ListRunStepsResponse(BaseModel): + object: Annotated[str, Field(example="list")] + data: List[RunStepObject] + first_id: Annotated[str, Field(example="step_abc123")] + last_id: Annotated[str, Field(example="step_abc456")] + has_more: Annotated[bool, Field(example=False)] -class ResponseFailedEvent(BaseModel): - type: Annotated[ - Literal['ResponseFailedEvent'], - Field(description='The type of the event. Always `response.failed`.\n'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - response: Annotated[Response1, Field(description='The response that failed.\n')] +class RunStepStreamEvent1(BaseModel): + event: Literal["thread.run.step.created"] + data: RunStepObject -class ResponseInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseInProgressEvent'], - Field(description='The type of the event. Always `response.in_progress`.\n'), - ] - response: Annotated[ - Response1, Field(description='The response that is in progress.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] +class RunStepStreamEvent2(BaseModel): + event: Literal["thread.run.step.in_progress"] + data: RunStepObject -class ResponseIncompleteEvent(BaseModel): - type: Annotated[ - Literal['ResponseIncompleteEvent'], - Field(description='The type of the event. Always `response.incomplete`.\n'), - ] - response: Annotated[ - Response1, Field(description='The response that was incomplete.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] +class RunStepStreamEvent3(BaseModel): + event: Literal["thread.run.step.delta"] + data: RunStepDeltaObject -class ResponseQueuedEvent(BaseModel): - type: Annotated[ - Literal['ResponseQueuedEvent'], - Field(description="The type of the event. Always 'response.queued'."), - ] - response: Annotated[ - Response1, Field(description='The full response object that is queued.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] +class RunStepStreamEvent4(BaseModel): + event: Literal["thread.run.step.completed"] + data: RunStepObject -class ResponseStreamEvent(BaseModel): - __root__: Annotated[ - Union[ - ResponseAudioDeltaEvent, - ResponseAudioDoneEvent, - ResponseAudioTranscriptDeltaEvent, - ResponseAudioTranscriptDoneEvent, - ResponseCodeInterpreterCallCodeDeltaEvent, - ResponseCodeInterpreterCallCodeDoneEvent, - ResponseCodeInterpreterCallCompletedEvent, - ResponseCodeInterpreterCallInProgressEvent, - ResponseCodeInterpreterCallInterpretingEvent, - ResponseCompletedEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, - ResponseCreatedEvent, - ResponseErrorEvent, - ResponseFileSearchCallCompletedEvent, - ResponseFileSearchCallInProgressEvent, - ResponseFileSearchCallSearchingEvent, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - ResponseInProgressEvent, - ResponseFailedEvent, - ResponseIncompleteEvent, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseReasoningSummaryPartAddedEvent, - ResponseReasoningSummaryPartDoneEvent, - ResponseReasoningSummaryTextDeltaEvent, - ResponseReasoningSummaryTextDoneEvent, - ResponseReasoningTextDeltaEvent, - ResponseReasoningTextDoneEvent, - ResponseRefusalDeltaEvent, - ResponseRefusalDoneEvent, - ResponseTextDeltaEvent, - ResponseTextDoneEvent, - ResponseWebSearchCallCompletedEvent, - ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent, - ResponseImageGenCallCompletedEvent, - ResponseImageGenCallGeneratingEvent, - ResponseImageGenCallInProgressEvent, - ResponseImageGenCallPartialImageEvent, - ResponseMCPCallArgumentsDeltaEvent, - ResponseMCPCallArgumentsDoneEvent, - ResponseMCPCallCompletedEvent, - ResponseMCPCallFailedEvent, - ResponseMCPCallInProgressEvent, - ResponseMCPListToolsCompletedEvent, - ResponseMCPListToolsFailedEvent, - ResponseMCPListToolsInProgressEvent, - ResponseOutputTextAnnotationAddedEvent, - ResponseQueuedEvent, - ResponseCustomToolCallInputDeltaEvent, - ResponseCustomToolCallInputDoneEvent, - ], - Field(discriminator='type'), - ] +class RunStepStreamEvent5(BaseModel): + event: Literal["thread.run.step.failed"] + data: RunStepObject -class Items(BaseModel): - __root__: Annotated[ - List[InputItem1], - Field( - description='Initial items to include in the conversation context. You may add up to 20 items at a time.', - max_items=20, - ), - ] +class RunStepStreamEvent6(BaseModel): + event: Literal["thread.run.step.cancelled"] + data: RunStepObject -class CreateConversationBody(BaseModel): - metadata: Optional[Metadata] = None - items: Optional[Items] = None +class RunStepStreamEvent7(BaseModel): + event: Literal["thread.run.step.expired"] + data: RunStepObject -class TokenCountsBody(BaseModel): - model: Optional[str] = None - input: Optional[Union[Input10, List[InputItem1]]] = None - previous_response_id: Optional[str] = None - tools: Optional[List[Tool]] = None - text: Optional[ResponseTextParam] = None - reasoning: Optional[Reasoning] = None - truncation: Annotated[ - Optional[TruncationEnum], - Field( - description="The truncation strategy to use for the model response. - `auto`: If the input to this Response exceeds the model's context window size, the model will truncate the response to fit the context window by dropping items from the beginning of the conversation. - `disabled` (default): If the input size will exceed the context window size for a model, the request will fail with a 400 error." - ), - ] = None - instructions: Optional[str] = None - conversation: Optional[ConversationParam] = None - tool_choice: Optional[ToolChoiceParam] = None - parallel_tool_calls: Optional[bool] = None +class RunStepStreamEvent(BaseModel): + __root__: Union[ + RunStepStreamEvent1, + RunStepStreamEvent2, + RunStepStreamEvent3, + RunStepStreamEvent4, + RunStepStreamEvent5, + RunStepStreamEvent6, + RunStepStreamEvent7, + ] -class CreateFineTuningJobRequest(BaseModel): - model: Annotated[ +class AssistantStreamEvent(BaseModel): + __root__: Annotated[ Union[ - str, Literal['babbage-002', 'davinci-002', 'gpt-3.5-turbo', 'gpt-4o-mini'] + ThreadStreamEvent, + RunStreamEvent, + RunStepStreamEvent, + MessageStreamEvent, + ErrorEvent, + DoneEvent, ], Field( - description='The name of the model to fine-tune. You can select one of the\n[supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned).\n', - example='gpt-4o-mini', + description='Represents an event emitted when streaming a Run.\n\nEach event in a server-sent events stream has an `event` and `data` property:\n\n```\nevent: thread.created\ndata: {"id": "thread_123", "object": "thread", ...}\n```\n\nWe emit events whenever a new object is created, transitions to a new state, or is being\nstreamed in parts (deltas). For example, we emit `thread.run.created` when a new run\nis created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses\nto create a message during a run, we emit a `thread.message.created event`, a\n`thread.message.in_progress` event, many `thread.message.delta` events, and finally a\n`thread.message.completed` event.\n\nWe may add additional events over time, so we recommend handling unknown events gracefully\nin your code. See the [Assistants API quickstart](/docs/assistants/overview) to learn how to\nintegrate the Assistants API with streaming.\n' ), ] - training_file: Annotated[ - str, - Field( - description='The ID of an uploaded file that contains training data.\n\nSee [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.\n\nYour dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n\nThe contents of the file should differ depending on if the model uses the [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format.\n\nSee the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n', - example='file-abc123', - ), - ] - hyperparameters: Annotated[ - Optional[Hyperparameters], - Field( - description='The hyperparameters used for the fine-tuning job.\nThis value is now deprecated in favor of `method`, and should be passed in under the `method` parameter.\n' - ), - ] = None - suffix: Annotated[ - Optional[str], - Field( - description='A string of up to 64 characters that will be added to your fine-tuned model name.\n\nFor example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n', - max_length=64, - min_length=1, - ), - ] = None - validation_file: Annotated[ - Optional[str], - Field( - description='The ID of an uploaded file that contains validation data.\n\nIf you provide this file, the data is used to generate validation\nmetrics periodically during fine-tuning. These metrics can be viewed in\nthe fine-tuning results file.\nThe same data should not be present in both train and validation files.\n\nYour dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n\nSee the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n', - example='file-abc123', - ), - ] = None - integrations: Annotated[ - Optional[List[Integration]], - Field(description='A list of integrations to enable for your fine-tuning job.'), - ] = None - seed: Annotated[ - Optional[int], - Field( - description='The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\nIf a seed is not specified, one will be generated for you.\n', - example=42, - ge=0, - le=2147483647, - ), - ] = None - method: Optional[FineTuneMethod] = None - metadata: Optional[Metadata] = None - - -class CreateResponse(CreateModelResponseProperties, ResponseProperties): - input: Optional[InputParam] = None - include: Optional[List[IncludeEnum]] = None - parallel_tool_calls: Optional[bool] = None - store: Optional[bool] = None - instructions: Optional[str] = None - stream: Optional[bool] = None - stream_options: Optional[ResponseStreamOptions] = None - conversation: Optional[ConversationParam] = None diff --git a/model-engine/model_engine_server/common/types/gen/openai.py b/model-engine/model_engine_server/common/types/gen/openai.py index 67d5986c6..c206d98f2 100644 --- a/model-engine/model_engine_server/common/types/gen/openai.py +++ b/model-engine/model_engine_server/common/types/gen/openai.py @@ -1,10 +1,10 @@ # generated by datamodel-codegen: # filename: openai-spec.yaml -# timestamp: 2025-12-02T21:52:14+00:00 +# timestamp: 2024-10-15T23:20:07+00:00 from __future__ import annotations -from typing import Annotated, Any, Dict, List, Literal, Optional, Union +from typing import Any, Dict, List, Literal, Optional, Union from model_engine_server.common.pydantic_types import ( AnyUrl, @@ -13,16541 +13,1724 @@ Field, RootModel, ) +from typing_extensions import Annotated -class AddUploadPartRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - data: Annotated[bytes, Field(description='The chunk of bytes for this Part.\n')] +class Error(BaseModel): + code: Annotated[Optional[str], Field(...)] = None + message: str + param: Annotated[Optional[str], Field(...)] = None + type: str -class Owner(BaseModel): - type: Annotated[ - Optional[str], Field(description='Always `user`', examples=['user']) - ] = None - object: Annotated[ - Optional[str], +class ErrorResponse(BaseModel): + error: Error + + +class DeleteModelResponse(BaseModel): + id: str + deleted: bool + object: str + + +class Prompt(RootModel[Optional[List[int]]]): + root: Annotated[ + Optional[List[int]], Field( - description='The object type, which is always organization.user', - examples=['organization.user'], + description="The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n", + examples=["[1212, 318, 257, 1332, 13]"], + min_length=1, ), - ] = None - id: Annotated[ - Optional[str], + ] = "<|endoftext|>" + + +class Prompt1Item(RootModel[List[int]]): + root: Annotated[List[int], Field(min_length=1)] + + +class Prompt1(RootModel[Optional[List[Prompt1Item]]]): + root: Annotated[ + Optional[List[Prompt1Item]], Field( - description='The identifier, which can be referenced in API endpoints', - examples=['sa_456'], + description="The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n", + examples=["[[1212, 318, 257, 1332, 13]]"], + min_length=1, ), - ] = None - name: Annotated[ - Optional[str], - Field(description='The name of the user', examples=['My Service Account']), - ] = None - created_at: Annotated[ - Optional[int], + ] = "<|endoftext|>" + + +class Stop(RootModel[Optional[List[str]]]): + root: Annotated[ + Optional[List[str]], Field( - description='The Unix timestamp (in seconds) of when the user was created', - examples=[1711471533], + description="Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.\n", + max_length=4, + min_length=1, ), ] = None - role: Annotated[ - Optional[str], Field(description='Always `owner`', examples=['owner']) - ] = None -class AdminApiKey(BaseModel): - object: Annotated[ - str, +class Logprobs(BaseModel): + text_offset: Optional[List[int]] = None + token_logprobs: Optional[List[float]] = None + tokens: Optional[List[str]] = None + top_logprobs: Optional[List[Dict[str, float]]] = None + + +class Choice(BaseModel): + finish_reason: Annotated[ + Optional[Literal["stop", "length", "content_filter"]], Field( - description='The object type, which is always `organization.admin_api_key`', - examples=['organization.admin_api_key'], + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\nor `content_filter` if content was omitted due to a flag from our content filters.\n" ), ] - id: Annotated[ - str, + index: int + logprobs: Annotated[Optional[Logprobs], Field(...)] + text: str + + +class ChatCompletionRequestMessageContentPartText(BaseModel): + type: Annotated[Literal["text"], Field(description="The type of the content part.")] + text: Annotated[str, Field(description="The text content.")] + + +class ImageUrl(BaseModel): + url: Annotated[ + AnyUrl, + Field(description="Either a URL of the image or the base64 encoded image data."), + ] + detail: Annotated[ + Literal["auto", "low", "high"], Field( - description='The identifier, which can be referenced in API endpoints', - examples=['key_abc'], + description="Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding)." ), + ] = "auto" + + +class ChatCompletionRequestMessageContentPartImage(BaseModel): + type: Annotated[Literal["image_url"], Field(description="The type of the content part.")] + image_url: ImageUrl + + +class ChatCompletionRequestMessageContentPartRefusal(BaseModel): + type: Annotated[Literal["refusal"], Field(description="The type of the content part.")] + refusal: Annotated[str, Field(description="The refusal message generated by the model.")] + + +class ChatCompletionRequestSystemMessageContentPart( + RootModel[ChatCompletionRequestMessageContentPartText] +): + root: ChatCompletionRequestMessageContentPartText + + +class ChatCompletionRequestUserMessageContentPart( + RootModel[ + Union[ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartImage, + ] ] - name: Annotated[ - str, - Field(description='The name of the API key', examples=['Administration Key']), +): + root: Union[ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartImage, ] - redacted_value: Annotated[ - str, + + +class ChatCompletionRequestAssistantMessageContentPart( + RootModel[ + Union[ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartRefusal, + ] + ] +): + root: Union[ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartRefusal, + ] + + +class ChatCompletionRequestToolMessageContentPart( + RootModel[ChatCompletionRequestMessageContentPartText] +): + root: ChatCompletionRequestMessageContentPartText + + +class Content(RootModel[List[ChatCompletionRequestSystemMessageContentPart]]): + root: Annotated[ + List[ChatCompletionRequestSystemMessageContentPart], Field( - description='The redacted value of the API key', examples=['sk-admin...def'] + description="An array of content parts with a defined type. For system messages, only type `text` is supported.", + min_length=1, + title="Array of content parts", ), ] - value: Annotated[ + + +class ChatCompletionRequestSystemMessage(BaseModel): + content: Annotated[ + Union[str, Content], Field(description="The contents of the system message.") + ] + role: Annotated[ + Literal["system"], + Field(description="The role of the messages author, in this case `system`."), + ] + name: Annotated[ Optional[str], Field( - description='The value of the API key. Only shown on create.', - examples=['sk-admin-1234abcd'], + description="An optional name for the participant. Provides the model information to differentiate between participants of the same role." ), ] = None - created_at: Annotated[ - int, + + +class Content1(RootModel[List[ChatCompletionRequestUserMessageContentPart]]): + root: Annotated[ + List[ChatCompletionRequestUserMessageContentPart], Field( - description='The Unix timestamp (in seconds) of when the API key was created', - examples=[1711471533], + description="An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4o` model.", + min_length=1, + title="Array of content parts", ), ] - last_used_at: Optional[int] = None - owner: Owner - -class ApiKeyList(BaseModel): - object: Annotated[Optional[str], Field(examples=['list'])] = None - data: Optional[List[AdminApiKey]] = None - has_more: Annotated[Optional[bool], Field(examples=[False])] = None - first_id: Annotated[Optional[str], Field(examples=['key_abc'])] = None - last_id: Annotated[Optional[str], Field(examples=['key_xyz'])] = None - -class AssignedRoleDetails(BaseModel): - id: Annotated[str, Field(description='Identifier for the role.')] - name: Annotated[str, Field(description='Name of the role.')] - permissions: Annotated[ - List[str], Field(description='Permissions associated with the role.') - ] - resource_type: Annotated[ - str, Field(description='Resource type the role applies to.') +class ChatCompletionRequestUserMessage(BaseModel): + content: Annotated[ + Union[str, Content1], Field(description="The contents of the user message.\n") ] - predefined_role: Annotated[ - bool, Field(description='Whether the role is predefined by OpenAI.') + role: Annotated[ + Literal["user"], + Field(description="The role of the messages author, in this case `user`."), ] - description: Annotated[ - Optional[str], Field(description='Description of the role.') - ] = None - created_at: Annotated[ - Optional[int], Field(description='When the role was created.') - ] = None - updated_at: Annotated[ - Optional[int], Field(description='When the role was last updated.') - ] = None - created_by: Annotated[ + name: Annotated[ Optional[str], - Field(description='Identifier of the actor who created the role.'), - ] = None - created_by_user_obj: Annotated[ - Optional[Dict[str, Any]], Field( - description='User details for the actor that created the role, when available.' + description="An optional name for the participant. Provides the model information to differentiate between participants of the same role." ), ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Arbitrary metadata stored on the role.'), - ] = None -class Name(RootModel[str]): +class Content2(RootModel[Optional[List[ChatCompletionRequestAssistantMessageContentPart]]]): root: Annotated[ - str, + Optional[List[ChatCompletionRequestAssistantMessageContentPart]], Field( - description='The name of the assistant. The maximum length is 256 characters.\n', - max_length=256, + description="An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.", + min_length=1, + title="Array of content parts", ), - ] + ] = None -class Description(RootModel[str]): - root: Annotated[ +class FunctionCall(BaseModel): + arguments: Annotated[ str, Field( - description='The description of the assistant. The maximum length is 512 characters.\n', - max_length=512, + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." ), ] + name: Annotated[str, Field(description="The name of the function to call.")] -class Instructions(RootModel[str]): +class Content3(RootModel[List[ChatCompletionRequestToolMessageContentPart]]): root: Annotated[ - str, + List[ChatCompletionRequestToolMessageContentPart], Field( - description='The system instructions that the assistant uses. The maximum length is 256,000 characters.\n', - max_length=256000, + description="An array of content parts with a defined type. For tool messages, only type `text` is supported.", + min_length=1, + title="Array of content parts", ), ] -class CodeInterpreter(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n', - max_length=20, - ), - ] = [] +class ChatCompletionRequestToolMessage(BaseModel): + role: Annotated[ + Literal["tool"], + Field(description="The role of the messages author, in this case `tool`."), + ] + content: Annotated[Union[str, Content3], Field(description="The contents of the tool message.")] + tool_call_id: Annotated[str, Field(description="Tool call that this message is responding to.")] -class FileSearch(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), +class ChatCompletionRequestFunctionMessage(BaseModel): + role: Annotated[ + Literal["function"], + Field(description="The role of the messages author, in this case `function`."), + ] + content: Annotated[ + Optional[str], Field(description="The contents of the function message.") ] = None + name: Annotated[str, Field(description="The name of the function to call.")] -class ToolResources(BaseModel): - code_interpreter: Optional[CodeInterpreter] = None - file_search: Optional[FileSearch] = None +class FunctionParameters(BaseModel): + pass + model_config = ConfigDict( + extra="allow", + ) -class Temperature(RootModel[float]): - root: Annotated[ - float, +class ChatCompletionFunctions(BaseModel): + description: Annotated[ + Optional[str], Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - examples=[1], - ge=0.0, - le=2.0, + description="A description of what the function does, used by the model to choose when and how to call the function." ), - ] - - -class TopP(RootModel[float]): - root: Annotated[ - float, + ] = None + name: Annotated[ + str, Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - examples=[1], - ge=0.0, - le=1.0, + description="The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." ), ] + parameters: Optional[FunctionParameters] = None -class AssistantSupportedModels( - RootModel[ - Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'o3-mini', - 'o3-mini-2025-01-31', - 'o1', - 'o1-2024-12-17', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ] - ] -): - root: Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'o3-mini', - 'o3-mini-2025-01-31', - 'o1', - 'o1-2024-12-17', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', +class ChatCompletionFunctionCallOption(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] + + +class FunctionObject(BaseModel): + description: Annotated[ + Optional[str], + Field( + description="A description of what the function does, used by the model to choose when and how to call the function." + ), + ] = None + name: Annotated[ + str, + Field( + description="The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." + ), ] + parameters: Optional[FunctionParameters] = None + strict: Annotated[ + Optional[bool], + Field( + description="Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling)." + ), + ] = None -class AssistantToolsCode(BaseModel): +class ResponseFormatText(BaseModel): type: Annotated[ - Literal['AssistantToolsCode'], - Field(description='The type of tool being defined: `code_interpreter`'), + Literal["text"], + Field(description="The type of response format being defined: `text`"), ] -class AssistantToolsFileSearchTypeOnly(BaseModel): +class ResponseFormatJsonObject(BaseModel): type: Annotated[ - Literal['AssistantToolsFileSearchTypeOnly'], - Field(description='The type of tool being defined: `file_search`'), + Literal["json_object"], + Field(description="The type of response format being defined: `json_object`"), ] -class Function(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] +class ResponseFormatJsonSchemaSchema(BaseModel): + pass + model_config = ConfigDict( + extra="allow", + ) -class AssistantsNamedToolChoice(BaseModel): - type: Annotated[ - Literal['function', 'code_interpreter', 'file_search'], +class JsonSchema(BaseModel): + description: Annotated[ + Optional[str], Field( - description='The type of the tool. If type is `function`, the function name must be set' - ), - ] - function: Optional[Function] = None - - -class AudioResponseFormat( - RootModel[Literal['json', 'text', 'srt', 'verbose_json', 'vtt', 'diarized_json']] -): - root: Annotated[ - Literal['json', 'text', 'srt', 'verbose_json', 'vtt', 'diarized_json'], - Field( - description='The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, `vtt`, or `diarized_json`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. For `gpt-4o-transcribe-diarize`, the supported formats are `json`, `text`, and `diarized_json`, with `diarized_json` required to receive speaker annotations.\n' - ), - ] - - -class AudioTranscription(BaseModel): - model: Annotated[ - Optional[ - Literal[ - 'whisper-1', - 'gpt-4o-mini-transcribe', - 'gpt-4o-transcribe', - 'gpt-4o-transcribe-diarize', - ] - ], - Field( - description='The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, and `gpt-4o-transcribe-diarize`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n' + description="A description of what the response format is for, used by the model to determine how to respond in the format." ), ] = None - language: Annotated[ - Optional[str], + name: Annotated[ + str, Field( - description='The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n' + description="The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." ), - ] = None - prompt: Annotated[ - Optional[str], + ] + schema_: Annotated[Optional[ResponseFormatJsonSchemaSchema], Field(alias="schema")] = None + strict: Annotated[ + Optional[bool], Field( - description='An optional text to guide the model\'s style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example "expect words related to technology".\n' + description="Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs)." ), - ] = None + ] = False -class Project(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - name: Annotated[Optional[str], Field(description='The project title.')] = None +class ResponseFormatJsonSchema(BaseModel): + type: Annotated[ + Literal["json_schema"], + Field(description="The type of response format being defined: `json_schema`"), + ] + json_schema: JsonSchema -class Data(BaseModel): - scopes: Annotated[ - Optional[List[str]], - Field( - description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`' - ), - ] = None +class Function(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] -class ApiKeyCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking ID of the API key.') - ] = None - data: Annotated[ - Optional[Data], Field(description='The payload used to create the API key.') - ] = None +class ChatCompletionNamedToolChoice(BaseModel): + type: Annotated[ + Literal["function"], + Field(description="The type of the tool. Currently, only `function` is supported."), + ] + function: Function -class ChangesRequested(BaseModel): - scopes: Annotated[ - Optional[List[str]], +class ParallelToolCalls(RootModel[bool]): + root: Annotated[ + bool, Field( - description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`' + description="Whether to enable [parallel function calling](/docs/guides/function-calling/parallel-function-calling) during tool use." ), - ] = None + ] -class ApiKeyUpdated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking ID of the API key.') - ] = None - changes_requested: Annotated[ - Optional[ChangesRequested], - Field(description='The payload used to update the API key.'), - ] = None +class Function1(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] + arguments: Annotated[ + str, + Field( + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + ), + ] -class ApiKeyDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking ID of the API key.') - ] = None +class ChatCompletionMessageToolCall(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call.")] + type: Annotated[ + Literal["function"], + Field(description="The type of the tool. Currently, only `function` is supported."), + ] + function: Annotated[Function1, Field(description="The function that the model called.")] -class Data1(BaseModel): - project_id: Annotated[ +class Function2(BaseModel): + name: Annotated[Optional[str], Field(description="The name of the function to call.")] = None + arguments: Annotated[ Optional[str], Field( - description='The ID of the project that the checkpoint permission was created for.' + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." ), ] = None - fine_tuned_model_checkpoint: Annotated[ - Optional[str], Field(description='The ID of the fine-tuned model checkpoint.') - ] = None - - -class CheckpointPermissionCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the checkpoint permission.') - ] = None - data: Annotated[ - Optional[Data1], - Field(description='The payload used to create the checkpoint permission.'), - ] = None - - -class CheckpointPermissionDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the checkpoint permission.') - ] = None - - -class ExternalKeyRegistered(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the external key configuration.') - ] = None - data: Annotated[ - Optional[Dict[str, Any]], - Field(description='The configuration for the external key.'), - ] = None -class ExternalKeyRemoved(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the external key configuration.') +class ChatCompletionMessageToolCallChunk(BaseModel): + index: int + id: Annotated[Optional[str], Field(description="The ID of the tool call.")] = None + type: Annotated[ + Optional[Literal["function"]], + Field(description="The type of the tool. Currently, only `function` is supported."), ] = None + function: Optional[Function2] = None -class Data2(BaseModel): - group_name: Annotated[Optional[str], Field(description='The group name.')] = None +class ChatCompletionRole(RootModel[Literal["system", "user", "assistant", "tool", "function"]]): + root: Annotated[ + Literal["system", "user", "assistant", "tool", "function"], + Field(description="The role of the author of a message"), + ] -class GroupCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the group.')] = None - data: Annotated[ - Optional[Data2], Field(description='Information about the created group.') +class ChatCompletionStreamOptions(BaseModel): + include_usage: Annotated[ + Optional[bool], + Field( + description="If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value.\n" + ), ] = None -class ChangesRequested1(BaseModel): - group_name: Annotated[ - Optional[str], Field(description='The updated group name.') +class FunctionCall2(BaseModel): + arguments: Annotated[ + Optional[str], + Field( + description="The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + ), ] = None + name: Annotated[Optional[str], Field(description="The name of the function to call.")] = None -class GroupUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the group.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested1], - Field(description='The payload used to update the group.'), +class ChatCompletionStreamResponseDelta(BaseModel): + content: Annotated[Optional[str], Field(description="The contents of the chunk message.")] = ( + None + ) + function_call: Annotated[ + Optional[FunctionCall2], + Field( + description="Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + ), ] = None - - -class GroupDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the group.')] = None - - -class ScimEnabled(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the SCIM was enabled for.') + tool_calls: Optional[List[ChatCompletionMessageToolCallChunk]] = None + role: Annotated[ + Optional[Literal["system", "user", "assistant", "tool"]], + Field(description="The role of the author of this message."), ] = None - - -class ScimDisabled(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the SCIM was disabled for.') + refusal: Annotated[ + Optional[str], Field(description="The refusal message generated by the model.") ] = None -class Data3(BaseModel): - email: Annotated[ - Optional[str], Field(description='The email invited to the organization.') - ] = None - role: Annotated[ - Optional[str], +class Stop1(RootModel[List[str]]): + root: Annotated[ + List[str], Field( - description='The role the email was invited to be. Is either `owner` or `member`.' + description="Up to 4 sequences where the API will stop generating further tokens.\n", + max_length=4, + min_length=1, ), - ] = None - - -class InviteSent(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the invite.')] = None - data: Annotated[ - Optional[Data3], Field(description='The payload used to create the invite.') - ] = None - - -class InviteAccepted(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the invite.')] = None - - -class InviteDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The ID of the invite.')] = None + ] -class IpAllowlistCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the IP allowlist configuration.') - ] = None - allowed_ips: Annotated[ - Optional[List[str]], +class TopLogprob(BaseModel): + token: Annotated[str, Field(description="The token.")] + logprob: Annotated[ + float, Field( - description='The IP addresses or CIDR ranges included in the configuration.' + description="The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." ), - ] = None - - -class IpAllowlistUpdated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - allowed_ips: Annotated[ - Optional[List[str]], + ] + bytes: Annotated[ + Optional[List[int]], Field( - description='The updated set of IP addresses or CIDR ranges in the configuration.' + description="A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." ), - ] = None + ] -class IpAllowlistDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the IP allowlist configuration.') - ] = None - allowed_ips: Annotated[ - Optional[List[str]], +class ChatCompletionTokenLogprob(BaseModel): + token: Annotated[str, Field(description="The token.")] + logprob: Annotated[ + float, Field( - description='The IP addresses or CIDR ranges that were in the configuration.' + description="The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." ), - ] = None - - -class Config(BaseModel): - id: Annotated[ - Optional[str], Field(description='The ID of the IP allowlist configuration.') - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the IP allowlist configuration.') - ] = None - - -class IpAllowlistConfigActivated(BaseModel): - configs: Annotated[ - Optional[List[Config]], - Field(description='The configurations that were activated.'), - ] = None + ] + bytes: Annotated[ + Optional[List[int]], + Field( + description="A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + ), + ] + top_logprobs: Annotated[ + List[TopLogprob], + Field( + description="List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned." + ), + ] -class IpAllowlistConfigDeactivated(BaseModel): - configs: Annotated[ - Optional[List[Config]], - Field(description='The configurations that were deactivated.'), +class Logprobs2(BaseModel): + content: Annotated[ + Optional[List[ChatCompletionTokenLogprob]], + Field(description="A list of message content tokens with log probability information."), + ] + refusal: Annotated[ + Optional[List[ChatCompletionTokenLogprob]], + Field(description="A list of message refusal tokens with log probability information."), ] = None -class LoginFailed(BaseModel): - error_code: Annotated[ - Optional[str], Field(description='The error code of the failure.') - ] = None - error_message: Annotated[ - Optional[str], Field(description='The error message of the failure.') +class Choice3(BaseModel): + delta: ChatCompletionStreamResponseDelta + logprobs: Annotated[ + Optional[Logprobs2], + Field(description="Log probability information for the choice."), ] = None + finish_reason: Annotated[ + Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]], + Field( + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" + ), + ] + index: Annotated[int, Field(description="The index of the choice in the list of choices.")] -class LogoutFailed(BaseModel): - error_code: Annotated[ - Optional[str], Field(description='The error code of the failure.') - ] = None - error_message: Annotated[ - Optional[str], Field(description='The error message of the failure.') - ] = None +class Usage(BaseModel): + completion_tokens: Annotated[ + int, Field(description="Number of tokens in the generated completion.") + ] + prompt_tokens: Annotated[int, Field(description="Number of tokens in the prompt.")] + total_tokens: Annotated[ + int, + Field(description="Total number of tokens used in the request (prompt + completion)."), + ] -class ChangesRequested2(BaseModel): - title: Annotated[Optional[str], Field(description='The organization title.')] = None - description: Annotated[ - Optional[str], Field(description='The organization description.') - ] = None - name: Annotated[Optional[str], Field(description='The organization name.')] = None - threads_ui_visibility: Annotated[ - Optional[str], +class CreateChatCompletionStreamResponse(BaseModel): + id: Annotated[ + str, Field( - description='Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`.' + description="A unique identifier for the chat completion. Each chunk has the same ID." ), - ] = None - usage_dashboard_visibility: Annotated[ - Optional[str], + ] + choices: Annotated[ + List[Choice3], Field( - description='Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`.' + description='A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the\nlast chunk if you set `stream_options: {"include_usage": true}`.\n' + ), + ] + created: Annotated[ + int, + Field( + description="The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp." + ), + ] + model: Annotated[str, Field(description="The model to generate the completion.")] + service_tier: Annotated[ + Optional[Literal["scale", "default"]], + Field( + description="The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.", + examples=["scale"], ), ] = None - api_call_logging: Annotated[ + system_fingerprint: Annotated[ Optional[str], Field( - description='How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects`' + description="This fingerprint represents the backend configuration that the model runs with.\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None - api_call_logging_project_ids: Annotated[ - Optional[str], + object: Annotated[ + Literal["chat.completion.chunk"], + Field(description="The object type, which is always `chat.completion.chunk`."), + ] + usage: Annotated[ + Optional[Usage], Field( - description='The list of project ids if api_call_logging is set to `enabled_for_selected_projects`' + description='An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request.\nWhen present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request.\n' ), ] = None -class OrganizationUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The organization ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested2], - Field(description='The payload used to update the organization settings.'), - ] = None - - -class Data4(BaseModel): - name: Annotated[Optional[str], Field(description='The project name.')] = None - title: Annotated[ - Optional[str], - Field(description='The title of the project as seen on the dashboard.'), - ] = None - - -class ProjectCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - data: Annotated[ - Optional[Data4], Field(description='The payload used to create the project.') - ] = None - - -class ChangesRequested3(BaseModel): - title: Annotated[ - Optional[str], - Field(description='The title of the project as seen on the dashboard.'), - ] = None - - -class ProjectUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested3], - Field(description='The payload used to update the project.'), - ] = None - - -class ProjectArchived(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - - -class ProjectDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - - -class ChangesRequested4(BaseModel): - max_requests_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum requests per minute.') - ] = None - max_tokens_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum tokens per minute.') - ] = None - max_images_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum images per minute. Only relevant for certain models.' - ), - ] = None - max_audio_megabytes_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum audio megabytes per minute. Only relevant for certain models.' - ), - ] = None - max_requests_per_1_day: Annotated[ - Optional[int], - Field( - description='The maximum requests per day. Only relevant for certain models.' - ), - ] = None - batch_1_day_max_input_tokens: Annotated[ - Optional[int], - Field( - description='The maximum batch input tokens per day. Only relevant for certain models.' - ), - ] = None - - -class RateLimitUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The rate limit ID')] = None - changes_requested: Annotated[ - Optional[ChangesRequested4], - Field(description='The payload used to update the rate limits.'), - ] = None - - -class RateLimitDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The rate limit ID')] = None - - -class RoleCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The role ID.')] = None - role_name: Annotated[Optional[str], Field(description='The name of the role.')] = ( - None - ) - permissions: Annotated[ - Optional[List[str]], Field(description='The permissions granted by the role.') - ] = None - resource_type: Annotated[ - Optional[str], Field(description='The type of resource the role belongs to.') - ] = None - resource_id: Annotated[ - Optional[str], Field(description='The resource the role is scoped to.') - ] = None - - -class ChangesRequested5(BaseModel): - role_name: Annotated[ - Optional[str], Field(description='The updated role name, when provided.') - ] = None - resource_id: Annotated[ - Optional[str], Field(description='The resource the role is scoped to.') - ] = None - resource_type: Annotated[ - Optional[str], Field(description='The type of resource the role belongs to.') - ] = None - permissions_added: Annotated[ - Optional[List[str]], Field(description='The permissions added to the role.') - ] = None - permissions_removed: Annotated[ - Optional[List[str]], Field(description='The permissions removed from the role.') - ] = None - description: Annotated[ - Optional[str], Field(description='The updated role description, when provided.') - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Additional metadata stored on the role.'), - ] = None - - -class RoleUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The role ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested5], - Field(description='The payload used to update the role.'), - ] = None - - -class RoleDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The role ID.')] = None - - -class RoleAssignmentCreated(BaseModel): - id: Annotated[ - Optional[str], Field(description='The identifier of the role assignment.') - ] = None - principal_id: Annotated[ - Optional[str], - Field(description='The principal (user or group) that received the role.'), - ] = None - principal_type: Annotated[ - Optional[str], - Field( - description='The type of principal (user or group) that received the role.' - ), - ] = None - resource_id: Annotated[ - Optional[str], - Field(description='The resource the role assignment is scoped to.'), - ] = None - resource_type: Annotated[ - Optional[str], - Field(description='The type of resource the role assignment is scoped to.'), - ] = None - - -class RoleAssignmentDeleted(BaseModel): - id: Annotated[ - Optional[str], Field(description='The identifier of the role assignment.') - ] = None - principal_id: Annotated[ - Optional[str], - Field(description='The principal (user or group) that had the role removed.'), - ] = None - principal_type: Annotated[ - Optional[str], - Field( - description='The type of principal (user or group) that had the role removed.' - ), - ] = None - resource_id: Annotated[ - Optional[str], - Field(description='The resource the role assignment was scoped to.'), - ] = None - resource_type: Annotated[ - Optional[str], - Field(description='The type of resource the role assignment was scoped to.'), - ] = None - - -class Data5(BaseModel): - role: Annotated[ - Optional[str], - Field( - description='The role of the service account. Is either `owner` or `member`.' - ), - ] = None - - -class ServiceAccountCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The service account ID.')] = None - data: Annotated[ - Optional[Data5], - Field(description='The payload used to create the service account.'), - ] = None - - -class ChangesRequested6(BaseModel): - role: Annotated[ - Optional[str], - Field( - description='The role of the service account. Is either `owner` or `member`.' - ), - ] = None - - -class ServiceAccountUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The service account ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested6], - Field(description='The payload used to updated the service account.'), - ] = None - - -class ServiceAccountDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The service account ID.')] = None - - -class Data6(BaseModel): - role: Annotated[ - Optional[str], - Field(description='The role of the user. Is either `owner` or `member`.'), - ] = None - - -class UserAdded(BaseModel): - id: Annotated[Optional[str], Field(description='The user ID.')] = None - data: Annotated[ - Optional[Data6], - Field(description='The payload used to add the user to the project.'), - ] = None - - -class ChangesRequested7(BaseModel): - role: Annotated[ - Optional[str], - Field(description='The role of the user. Is either `owner` or `member`.'), - ] = None - - -class UserUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The project ID.')] = None - changes_requested: Annotated[ - Optional[ChangesRequested7], - Field(description='The payload used to update the user.'), - ] = None - - -class UserDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The user ID.')] = None - - -class CertificateCreated(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - - -class CertificateUpdated(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - - -class CertificateDeleted(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - certificate: Annotated[ - Optional[str], Field(description='The certificate content in PEM format.') - ] = None - - -class Certificate(BaseModel): - id: Annotated[Optional[str], Field(description='The certificate ID.')] = None - name: Annotated[ - Optional[str], Field(description='The name of the certificate.') - ] = None - - -class CertificatesActivated(BaseModel): - certificates: Optional[List[Certificate]] = None - - -class CertificatesDeactivated(BaseModel): - certificates: Optional[List[Certificate]] = None - - -class AuditLogActorServiceAccount(BaseModel): - id: Annotated[Optional[str], Field(description='The service account id.')] = None - - -class AuditLogActorUser(BaseModel): - id: Annotated[Optional[str], Field(description='The user id.')] = None - email: Annotated[Optional[str], Field(description='The user email.')] = None - - -class AuditLogEventType( - RootModel[ - Literal[ - 'api_key.created', - 'api_key.updated', - 'api_key.deleted', - 'certificate.created', - 'certificate.updated', - 'certificate.deleted', - 'certificates.activated', - 'certificates.deactivated', - 'checkpoint.permission.created', - 'checkpoint.permission.deleted', - 'external_key.registered', - 'external_key.removed', - 'group.created', - 'group.updated', - 'group.deleted', - 'invite.sent', - 'invite.accepted', - 'invite.deleted', - 'ip_allowlist.created', - 'ip_allowlist.updated', - 'ip_allowlist.deleted', - 'ip_allowlist.config.activated', - 'ip_allowlist.config.deactivated', - 'login.succeeded', - 'login.failed', - 'logout.succeeded', - 'logout.failed', - 'organization.updated', - 'project.created', - 'project.updated', - 'project.archived', - 'project.deleted', - 'rate_limit.updated', - 'rate_limit.deleted', - 'resource.deleted', - 'role.created', - 'role.updated', - 'role.deleted', - 'role.assignment.created', - 'role.assignment.deleted', - 'scim.enabled', - 'scim.disabled', - 'service_account.created', - 'service_account.updated', - 'service_account.deleted', - 'user.added', - 'user.updated', - 'user.deleted', - ] - ] -): - root: Annotated[ - Literal[ - 'api_key.created', - 'api_key.updated', - 'api_key.deleted', - 'certificate.created', - 'certificate.updated', - 'certificate.deleted', - 'certificates.activated', - 'certificates.deactivated', - 'checkpoint.permission.created', - 'checkpoint.permission.deleted', - 'external_key.registered', - 'external_key.removed', - 'group.created', - 'group.updated', - 'group.deleted', - 'invite.sent', - 'invite.accepted', - 'invite.deleted', - 'ip_allowlist.created', - 'ip_allowlist.updated', - 'ip_allowlist.deleted', - 'ip_allowlist.config.activated', - 'ip_allowlist.config.deactivated', - 'login.succeeded', - 'login.failed', - 'logout.succeeded', - 'logout.failed', - 'organization.updated', - 'project.created', - 'project.updated', - 'project.archived', - 'project.deleted', - 'rate_limit.updated', - 'rate_limit.deleted', - 'resource.deleted', - 'role.created', - 'role.updated', - 'role.deleted', - 'role.assignment.created', - 'role.assignment.deleted', - 'scim.enabled', - 'scim.disabled', - 'service_account.created', - 'service_account.updated', - 'service_account.deleted', - 'user.added', - 'user.updated', - 'user.deleted', - ], - Field(description='The event type.'), - ] - - -class AutoChunkingStrategyRequestParam(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['AutoChunkingStrategyRequestParam'], Field(description='Always `auto`.') - ] - - -class InputTokensDetails(BaseModel): - cached_tokens: Annotated[ - int, - Field( - description='The number of tokens that were retrieved from the cache. [More on\nprompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n' - ), - ] - - -class OutputTokensDetails(BaseModel): - reasoning_tokens: Annotated[ - int, Field(description='The number of reasoning tokens.') - ] - - -class Usage(BaseModel): - input_tokens: Annotated[int, Field(description='The number of input tokens.')] - input_tokens_details: Annotated[ - InputTokensDetails, - Field(description='A detailed breakdown of the input tokens.'), - ] - output_tokens: Annotated[int, Field(description='The number of output tokens.')] - output_tokens_details: Annotated[ - OutputTokensDetails, - Field(description='A detailed breakdown of the output tokens.'), - ] - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - - -class BatchFileExpirationAfter(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created.' - ), - ] - seconds: Annotated[ - int, - Field( - description='The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).', - ge=3600, - le=2592000, - ), - ] - - -class BatchRequestInput(BaseModel): - custom_id: Annotated[ - Optional[str], - Field( - description='A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch.' - ), - ] = None - method: Annotated[ - Optional[Literal['POST']], - Field( - description='The HTTP method to be used for the request. Currently only `POST` is supported.' - ), - ] = None - url: Annotated[ - Optional[str], - Field( - description='The OpenAI API relative URL to be used for the request. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, and `/v1/moderations` are supported.' - ), - ] = None - - -class Response(BaseModel): - status_code: Annotated[ - Optional[int], Field(description='The HTTP status code of the response') - ] = None - request_id: Annotated[ - Optional[str], - Field( - description='An unique identifier for the OpenAI API request. Please include this request ID when contacting support.' - ), - ] = None - body: Annotated[ - Optional[Dict[str, Any]], Field(description='The JSON body of the response') - ] = None - - -class Error(BaseModel): - code: Annotated[ - Optional[str], - Field( - description='A machine-readable error code.\n\nPossible values:\n- `batch_expired`: The request could not be executed before the\n completion window ended.\n- `batch_cancelled`: The batch was cancelled before this request\n executed.\n- `request_timeout`: The underlying call to the model timed out.\n' - ), - ] = None - message: Annotated[ - Optional[str], Field(description='A human-readable error message.') - ] = None - - -class BatchRequestOutput(BaseModel): - id: Optional[str] = None - custom_id: Annotated[ - Optional[str], - Field( - description='A developer-provided per-request id that will be used to match outputs to inputs.' - ), - ] = None - response: Optional[Response] = None - error: Optional[Error] = None - - -class CertificateDetails(BaseModel): - valid_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) of when the certificate becomes valid.' - ), - ] = None - expires_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) of when the certificate expires.' - ), - ] = None - content: Annotated[ - Optional[str], - Field(description='The content of the certificate in PEM format.'), - ] = None - - -class Certificate2(BaseModel): - object: Annotated[ - Literal[ - 'certificate', - 'organization.certificate', - 'organization.project.certificate', - ], - Field( - description='The object type.\n\n- If creating, updating, or getting a specific certificate, the object type is `certificate`.\n- If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`.\n- If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`.\n' - ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the certificate.')] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the certificate was uploaded.' - ), - ] - certificate_details: CertificateDetails - active: Annotated[ - Optional[bool], - Field( - description='Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate.' - ), - ] = None - - -class ChatCompletionAllowedTools(BaseModel): - mode: Annotated[ - Literal['auto', 'required'], - Field( - description='Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n' - ), - ] - tools: Annotated[ - List[Dict[str, Any]], - Field( - description='A list of tool definitions that the model should be allowed to call.\n\nFor the Chat Completions API, the list of tool definitions might look like:\n```json\n[\n { "type": "function", "function": { "name": "get_weather" } },\n { "type": "function", "function": { "name": "get_time" } }\n]\n```\n' - ), - ] - - -class ChatCompletionAllowedToolsChoice(BaseModel): - type: Annotated[ - Literal['allowed_tools'], - Field(description='Allowed tool configuration type. Always `allowed_tools`.'), - ] - allowed_tools: ChatCompletionAllowedTools - - -class ChatCompletionDeleted(BaseModel): - object: Annotated[ - Literal['chat.completion.deleted'], - Field(description='The type of object being deleted.'), - ] - id: Annotated[ - str, Field(description='The ID of the chat completion that was deleted.') - ] - deleted: Annotated[ - bool, Field(description='Whether the chat completion was deleted.') - ] - - -class ChatCompletionFunctionCallOption(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] - - -class Custom(BaseModel): - name: Annotated[str, Field(description='The name of the custom tool to call.')] - input: Annotated[ - str, - Field(description='The input for the custom tool call generated by the model.'), - ] - - -class ChatCompletionMessageCustomToolCall(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call.')] - type: Annotated[ - Literal['ChatCompletionMessageCustomToolCall'], - Field(description='The type of the tool. Always `custom`.'), - ] - custom: Annotated[ - Custom, Field(description='The custom tool that the model called.') - ] - - -class Function1(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] - arguments: Annotated[ - str, - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] - - -class ChatCompletionMessageToolCall(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call.')] - type: Annotated[ - Literal['ChatCompletionMessageToolCall'], - Field( - description='The type of the tool. Currently, only `function` is supported.' - ), - ] - function: Annotated[ - Function1, Field(description='The function that the model called.') - ] - - -class Function2(BaseModel): - name: Annotated[ - Optional[str], Field(description='The name of the function to call.') - ] = None - arguments: Annotated[ - Optional[str], - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] = None - - -class ChatCompletionMessageToolCallChunk(BaseModel): - index: int - id: Annotated[Optional[str], Field(description='The ID of the tool call.')] = None - type: Annotated[ - Optional[Literal['function']], - Field( - description='The type of the tool. Currently, only `function` is supported.' - ), - ] = None - function: Optional[Function2] = None - - -class ChatCompletionMessageToolCalls1( - RootModel[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]] -): - root: Annotated[ - Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall], - Field(discriminator='type'), - ] - - -class ChatCompletionMessageToolCalls(RootModel[List[ChatCompletionMessageToolCalls1]]): - root: Annotated[ - List[ChatCompletionMessageToolCalls1], - Field( - description='The tool calls generated by the model, such as function calls.' - ), - ] - - -class ChatCompletionModalities(RootModel[Optional[List[Literal['text', 'audio']]]]): - root: Optional[List[Literal['text', 'audio']]] - - -class Function3(BaseModel): - name: Annotated[str, Field(description='The name of the function to call.')] - - -class ChatCompletionNamedToolChoice(BaseModel): - type: Annotated[ - Literal['function'], - Field(description='For function calling, the type is always `function`.'), - ] - function: Function3 - - -class Custom1(BaseModel): - name: Annotated[str, Field(description='The name of the custom tool to call.')] - - -class ChatCompletionNamedToolChoiceCustom(BaseModel): - type: Annotated[ - Literal['custom'], - Field(description='For custom tool calling, the type is always `custom`.'), - ] - custom: Custom1 - - -class Audio(BaseModel): - id: Annotated[ - str, - Field( - description='Unique identifier for a previous audio response from the model.\n' - ), - ] - - -class FunctionCall(BaseModel): - arguments: Annotated[ - str, - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] - name: Annotated[str, Field(description='The name of the function to call.')] - - -class ChatCompletionRequestFunctionMessage(BaseModel): - role: Annotated[ - Literal['ChatCompletionRequestFunctionMessage'], - Field(description='The role of the messages author, in this case `function`.'), - ] - content: Optional[str] = None - name: Annotated[str, Field(description='The name of the function to call.')] - - -class InputAudio(BaseModel): - data: Annotated[str, Field(description='Base64 encoded audio data.')] - format: Annotated[ - Literal['wav', 'mp3'], - Field( - description='The format of the encoded audio data. Currently supports "wav" and "mp3".\n' - ), - ] - - -class ChatCompletionRequestMessageContentPartAudio(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartAudio'], - Field(description='The type of the content part. Always `input_audio`.'), - ] - input_audio: InputAudio - - -class File(BaseModel): - filename: Annotated[ - Optional[str], - Field( - description='The name of the file, used when passing the file to the model as a \nstring.\n' - ), - ] = None - file_data: Annotated[ - Optional[str], - Field( - description='The base64 encoded file data, used when passing the file to the model \nas a string.\n' - ), - ] = None - file_id: Annotated[ - Optional[str], - Field(description='The ID of an uploaded file to use as input.\n'), - ] = None - - -class ChatCompletionRequestMessageContentPartFile(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartFile'], - Field(description='The type of the content part. Always `file`.'), - ] - file: File - - -class ImageUrl(BaseModel): - url: Annotated[ - AnyUrl, - Field( - description='Either a URL of the image or the base64 encoded image data.' - ), - ] - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).' - ), - ] = 'auto' - - -class ChatCompletionRequestMessageContentPartImage(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartImage'], - Field(description='The type of the content part.'), - ] - image_url: ImageUrl - - -class ChatCompletionRequestMessageContentPartRefusal(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartRefusal'], - Field(description='The type of the content part.'), - ] - refusal: Annotated[ - str, Field(description='The refusal message generated by the model.') - ] - - -class ChatCompletionRequestMessageContentPartText(BaseModel): - type: Annotated[ - Literal['ChatCompletionRequestMessageContentPartText'], - Field(description='The type of the content part.'), - ] - text: Annotated[str, Field(description='The text content.')] - - -class ChatCompletionRequestSystemMessageContentPart( - RootModel[ChatCompletionRequestMessageContentPartText] -): - root: ChatCompletionRequestMessageContentPartText - - -class ChatCompletionRequestToolMessageContentPart( - RootModel[ChatCompletionRequestMessageContentPartText] -): - root: ChatCompletionRequestMessageContentPartText - - -class ChatCompletionRequestUserMessageContentPart( - RootModel[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartImage, - ChatCompletionRequestMessageContentPartAudio, - ChatCompletionRequestMessageContentPartFile, - ] - ] -): - root: Annotated[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartImage, - ChatCompletionRequestMessageContentPartAudio, - ChatCompletionRequestMessageContentPartFile, - ], - Field(discriminator='type'), - ] - - -class UrlCitation(BaseModel): - end_index: Annotated[ - int, - Field( - description='The index of the last character of the URL citation in the message.' - ), - ] - start_index: Annotated[ - int, - Field( - description='The index of the first character of the URL citation in the message.' - ), - ] - url: Annotated[str, Field(description='The URL of the web resource.')] - title: Annotated[str, Field(description='The title of the web resource.')] - - -class Annotation(BaseModel): - type: Annotated[ - Literal['url_citation'], - Field(description='The type of the URL citation. Always `url_citation`.'), - ] - url_citation: Annotated[ - UrlCitation, Field(description='A URL citation when using web search.') - ] - - -class Audio1(BaseModel): - id: Annotated[str, Field(description='Unique identifier for this audio response.')] - expires_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when this audio response will\nno longer be accessible on the server for use in multi-turn\nconversations.\n' - ), - ] - data: Annotated[ - str, - Field( - description='Base64 encoded audio bytes generated by the model, in the format\nspecified in the request.\n' - ), - ] - transcript: Annotated[ - str, Field(description='Transcript of the audio generated by the model.') - ] - - -class ChatCompletionResponseMessage(BaseModel): - content: Optional[str] = None - refusal: Optional[str] = None - tool_calls: Optional[ChatCompletionMessageToolCalls] = None - annotations: Annotated[ - Optional[List[Annotation]], - Field( - description='Annotations for the message, when applicable, as when using the\n[web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n' - ), - ] = None - role: Annotated[ - Literal['assistant'], - Field(description='The role of the author of this message.'), - ] - function_call: Annotated[ - Optional[FunctionCall], - Field( - description='Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.' - ), - ] = None - audio: Optional[Audio1] = None - - -class ChatCompletionRole( - RootModel[Literal['developer', 'system', 'user', 'assistant', 'tool', 'function']] -): - root: Annotated[ - Literal['developer', 'system', 'user', 'assistant', 'tool', 'function'], - Field(description='The role of the author of a message'), - ] - - -class ChatCompletionStreamOptions1(BaseModel): - include_usage: Annotated[ - Optional[bool], - Field( - description='If set, an additional chunk will be streamed before the `data: [DONE]`\nmessage. The `usage` field on this chunk shows the token usage statistics\nfor the entire request, and the `choices` field will always be an empty\narray.\n\nAll other chunks will also include a `usage` field, but with a null\nvalue. **NOTE:** If the stream is interrupted, you may not receive the\nfinal usage chunk which contains the total token usage for the request.\n' - ), - ] = None - include_obfuscation: Annotated[ - Optional[bool], - Field( - description='When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n' - ), - ] = None - - -class ChatCompletionStreamOptions(RootModel[Optional[ChatCompletionStreamOptions1]]): - root: Optional[ChatCompletionStreamOptions1] - - -class FunctionCall2(BaseModel): - arguments: Annotated[ - Optional[str], - Field( - description='The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.' - ), - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the function to call.') - ] = None - - -class ChatCompletionStreamResponseDelta(BaseModel): - content: Optional[str] = None - function_call: Annotated[ - Optional[FunctionCall2], - Field( - description='Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.' - ), - ] = None - tool_calls: Optional[List[ChatCompletionMessageToolCallChunk]] = None - role: Annotated[ - Optional[Literal['developer', 'system', 'user', 'assistant', 'tool']], - Field(description='The role of the author of this message.'), - ] = None - refusal: Optional[str] = None - - -class TopLogprob(BaseModel): - token: Annotated[str, Field(description='The token.')] - logprob: Annotated[ - float, - Field( - description='The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.' - ), - ] - bytes: Optional[List[int]] = None - - -class ChatCompletionTokenLogprob(BaseModel): - token: Annotated[str, Field(description='The token.')] - logprob: Annotated[ - float, - Field( - description='The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.' - ), - ] - bytes: Optional[List[int]] = None - top_logprobs: Annotated[ - List[TopLogprob], - Field( - description='List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned.' - ), - ] - - -class ChatCompletionToolChoiceOption( - RootModel[ - Union[ - Literal['none', 'auto', 'required'], - ChatCompletionAllowedToolsChoice, - ChatCompletionNamedToolChoice, - ChatCompletionNamedToolChoiceCustom, - ] - ] -): - root: Annotated[ - Union[ - Literal['none', 'auto', 'required'], - ChatCompletionAllowedToolsChoice, - ChatCompletionNamedToolChoice, - ChatCompletionNamedToolChoiceCustom, - ], - Field( - description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tool and instead generates a message.\n`auto` means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools.\nSpecifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n\n`none` is the default when no tools are present. `auto` is the default if tools are present.\n' - ), - ] - - -class File1(BaseModel): - mime_type: Annotated[str, Field(description='The MIME type of the file.\n')] - file_id: Annotated[str, Field(description='The ID of the file.\n')] - - -class CodeInterpreterFileOutput(BaseModel): - type: Annotated[ - Literal['files'], - Field( - description='The type of the code interpreter file output. Always `files`.\n' - ), - ] - files: List[File1] - - -class CodeInterpreterTextOutput(BaseModel): - type: Annotated[ - Literal['logs'], - Field( - description='The type of the code interpreter text output. Always `logs`.\n' - ), - ] - logs: Annotated[ - str, Field(description='The logs of the code interpreter tool call.\n') - ] - - -class CompleteUploadRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - part_ids: Annotated[List[str], Field(description='The ordered list of Part IDs.\n')] - md5: Annotated[ - Optional[str], - Field( - description='The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n' - ), - ] = None - - -class CompletionTokensDetails(BaseModel): - accepted_prediction_tokens: Annotated[ - int, - Field( - description='When using Predicted Outputs, the number of tokens in the\nprediction that appeared in the completion.\n' - ), - ] = 0 - audio_tokens: Annotated[ - int, Field(description='Audio input tokens generated by the model.') - ] = 0 - reasoning_tokens: Annotated[ - int, Field(description='Tokens generated by the model for reasoning.') - ] = 0 - rejected_prediction_tokens: Annotated[ - int, - Field( - description='When using Predicted Outputs, the number of tokens in the\nprediction that did not appear in the completion. However, like\nreasoning tokens, these tokens are still counted in the total\ncompletion tokens for purposes of billing, output, and context window\nlimits.\n' - ), - ] = 0 - - -class PromptTokensDetails(BaseModel): - audio_tokens: Annotated[ - int, Field(description='Audio input tokens present in the prompt.') - ] = 0 - cached_tokens: Annotated[ - int, Field(description='Cached tokens present in the prompt.') - ] = 0 - - -class CompletionUsage(BaseModel): - completion_tokens: Annotated[ - int, Field(description='Number of tokens in the generated completion.') - ] - prompt_tokens: Annotated[int, Field(description='Number of tokens in the prompt.')] - total_tokens: Annotated[ - int, - Field( - description='Total number of tokens used in the request (prompt + completion).' - ), - ] - completion_tokens_details: Annotated[ - Optional[CompletionTokensDetails], - Field(description='Breakdown of tokens used in a completion.'), - ] = None - prompt_tokens_details: Annotated[ - Optional[PromptTokensDetails], - Field(description='Breakdown of tokens used in the prompt.'), - ] = None - - -class ComputerScreenshotImage(BaseModel): - type: Annotated[ - Literal['computer_screenshot'], - Field( - description='Specifies the event type. For a computer screenshot, this property is \nalways set to `computer_screenshot`.\n' - ), - ] - image_url: Annotated[ - Optional[str], Field(description='The URL of the screenshot image.') - ] = None - file_id: Annotated[ - Optional[str], - Field( - description='The identifier of an uploaded file that contains the screenshot.' - ), - ] = None - - -class ContainerFileResource(BaseModel): - id: Annotated[str, Field(description='Unique identifier for the file.')] - object: Annotated[ - Literal['container.file'], - Field(description='The type of this object (`container.file`).'), - ] - container_id: Annotated[ - str, Field(description='The container this file belongs to.') - ] - created_at: Annotated[ - int, Field(description='Unix timestamp (in seconds) when the file was created.') - ] - bytes: Annotated[int, Field(description='Size of the file in bytes.')] - path: Annotated[str, Field(description='Path of the file in the container.')] - source: Annotated[ - str, Field(description='Source of the file (e.g., `user`, `assistant`).') - ] - - -class ExpiresAfter(BaseModel): - anchor: Annotated[ - Optional[Literal['last_active_at']], - Field(description='The reference point for the expiration.'), - ] = None - minutes: Annotated[ - Optional[int], - Field( - description='The number of minutes after the anchor before the container expires.' - ), - ] = None - - -class ContainerResource(BaseModel): - id: Annotated[str, Field(description='Unique identifier for the container.')] - object: Annotated[str, Field(description='The type of this object.')] - name: Annotated[str, Field(description='Name of the container.')] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) when the container was created.' - ), - ] - status: Annotated[ - str, Field(description='Status of the container (e.g., active, deleted).') - ] - expires_after: Annotated[ - Optional[ExpiresAfter], - Field( - description='The container will expire after this time period.\nThe anchor is the reference point for the expiration.\nThe minutes is the number of minutes after the anchor before the container expires.\n' - ), - ] = None - - -class Amount(BaseModel): - value: Annotated[ - Optional[float], Field(description='The numeric value of the cost.') - ] = None - currency: Annotated[ - Optional[str], Field(description='Lowercase ISO-4217 currency e.g. "usd"') - ] = None - - -class CostsResult(BaseModel): - object: Literal['CostsResult'] - amount: Annotated[ - Optional[Amount], - Field(description='The monetary value in its associated currency.'), - ] = None - line_item: Optional[str] = None - project_id: Optional[str] = None - - -class CodeInterpreter1(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n', - max_length=20, - ), - ] = [] - - -class ChunkingStrategy(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class Static(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - max_chunk_size_tokens: Annotated[ - int, - Field( - description='The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.', - ge=100, - le=4096, - ), - ] - chunk_overlap_tokens: Annotated[ - int, - Field( - description='The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n' - ), - ] - - -class ChunkingStrategy1(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class ChunkingStrategy2(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class ChunkingStrategy3(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class Logprobs(BaseModel): - content: Optional[List[ChatCompletionTokenLogprob]] = None - refusal: Optional[List[ChatCompletionTokenLogprob]] = None - - -class Choice(BaseModel): - finish_reason: Annotated[ - Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call'], - Field( - description='The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n' - ), - ] - index: Annotated[ - int, Field(description='The index of the choice in the list of choices.') - ] - message: ChatCompletionResponseMessage - logprobs: Optional[Logprobs] = None - - -class Logprobs1(BaseModel): - content: Annotated[ - Optional[List[ChatCompletionTokenLogprob]], - Field( - description='A list of message content tokens with log probability information.' - ), - ] - refusal: Annotated[ - Optional[List[ChatCompletionTokenLogprob]], - Field( - description='A list of message refusal tokens with log probability information.' - ), - ] - - -class Choice1(BaseModel): - delta: ChatCompletionStreamResponseDelta - logprobs: Annotated[ - Optional[Logprobs1], - Field(description='Log probability information for the choice.'), - ] = None - finish_reason: Annotated[ - Optional[ - Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call'] - ], - Field( - description='The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n' - ), - ] - index: Annotated[ - int, Field(description='The index of the choice in the list of choices.') - ] - - -class Prompt(RootModel[Optional[List[int]]]): - root: Annotated[ - Optional[List[int]], - Field( - description='The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n', - min_length=1, - title='Array of tokens', - ), - ] = None - - -class Prompt1Item(RootModel[List[int]]): - root: Annotated[List[int], Field(min_length=1)] - - -class Prompt1(RootModel[Optional[List[Prompt1Item]]]): - root: Annotated[ - Optional[List[Prompt1Item]], - Field( - description='The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n', - min_length=1, - title='Array of token arrays', - ), - ] = None - - -class Logprobs2(BaseModel): - text_offset: Optional[List[int]] = None - token_logprobs: Optional[List[float]] = None - tokens: Optional[List[str]] = None - top_logprobs: Optional[List[Dict[str, float]]] = None - - -class Choice2(BaseModel): - finish_reason: Annotated[ - Literal['stop', 'length', 'content_filter'], - Field( - description='The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\nor `content_filter` if content was omitted due to a flag from our content filters.\n' - ), - ] - index: int - logprobs: Optional[Logprobs2] = None - text: str - - -class CreateCompletionResponse(BaseModel): - id: Annotated[str, Field(description='A unique identifier for the completion.')] - choices: Annotated[ - List[Choice2], - Field( - description='The list of completion choices the model generated for the input prompt.' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the completion was created.' - ), - ] - model: Annotated[str, Field(description='The model used for completion.')] - system_fingerprint: Annotated[ - Optional[str], - Field( - description='This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n' - ), - ] = None - object: Annotated[ - Literal['text_completion'], - Field(description='The object type, which is always "text_completion"'), - ] - usage: Optional[CompletionUsage] = None - - -class ExpiresAfter1(BaseModel): - anchor: Annotated[ - Literal['last_active_at'], - Field( - description="Time anchor for the expiration time. Currently only 'last_active_at' is supported." - ), - ] - minutes: int - - -class CreateContainerBody(BaseModel): - name: Annotated[str, Field(description='Name of the container to create.')] - file_ids: Annotated[ - Optional[List[str]], Field(description='IDs of files to copy to the container.') - ] = None - expires_after: Annotated[ - Optional[ExpiresAfter1], - Field( - description="Container expiration time in seconds relative to the 'anchor' time." - ), - ] = None - - -class CreateContainerFileBody(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='Name of the file to create.') - ] = None - file: Annotated[ - Optional[bytes], - Field(description='The File object (not file name) to be uploaded.\n'), - ] = None - - -class Input(RootModel[List[str]]): - root: Annotated[ - List[str], - Field( - description='The array of strings that will be turned into an embedding.', - examples=['The quick brown fox jumped over the lazy dog'], - max_length=2048, - min_length=1, - title='Array of strings', - ), - ] - - -class Input1(RootModel[List[int]]): - root: Annotated[ - List[int], - Field( - description='The array of integers that will be turned into an embedding.', - examples=['The quick brown fox jumped over the lazy dog'], - max_length=2048, - min_length=1, - title='Array of tokens', - ), - ] - - -class Input2Item(RootModel[List[int]]): - root: Annotated[List[int], Field(min_length=1)] - - -class Input2(RootModel[List[Input2Item]]): - root: Annotated[ - List[Input2Item], - Field( - description='The array of arrays containing integers that will be turned into an embedding.', - examples=['The quick brown fox jumped over the lazy dog'], - max_length=2048, - min_length=1, - title='Array of token arrays', - ), - ] - - -class CreateEmbeddingRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - input: Annotated[ - Union[str, Input, Input1, Input2], - Field( - description='Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request.\n', - examples=['The quick brown fox jumped over the lazy dog'], - ), - ] - model: Annotated[ - Union[ - str, - Literal[ - 'text-embedding-ada-002', - 'text-embedding-3-small', - 'text-embedding-3-large', - ], - ], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n', - examples=['text-embedding-3-small'], - ), - ] - encoding_format: Annotated[ - Literal['float', 'base64'], - Field( - description='The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).', - examples=['float'], - ), - ] = 'float' - dimensions: Annotated[ - Optional[int], - Field( - description='The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n', - ge=1, - ), - ] = None - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - examples=['user-1234'], - ), - ] = None - - -class Usage1(BaseModel): - prompt_tokens: Annotated[ - int, Field(description='The number of tokens used by the prompt.') - ] - total_tokens: Annotated[ - int, Field(description='The total number of tokens used by the request.') - ] - - -class InputMessages1(BaseModel): - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `item_reference`.'), - ] - item_reference: Annotated[ - str, - Field( - description='A reference to a variable in the `item` namespace. Ie, "item.input_trajectory"' - ), - ] - - -class CreateEvalCustomDataSourceConfig(BaseModel): - type: Annotated[ - Literal['CreateEvalCustomDataSourceConfig'], - Field(description='The type of data source. Always `custom`.'), - ] - item_schema: Annotated[ - Dict[str, Any], - Field(description='The json schema for each row in the data source.'), - ] - include_sample_schema: Annotated[ - bool, - Field( - description='Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source)' - ), - ] = False - - -class CreateEvalItem1(BaseModel): - role: Annotated[ - str, - Field( - description='The role of the message (e.g. "system", "assistant", "user").' - ), - ] - content: Annotated[str, Field(description='The content of the message.')] - - -class CreateEvalLogsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['CreateEvalLogsDataSourceConfig'], - Field(description='The type of data source. Always `logs`.'), - ] - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Metadata filters for the logs data source.'), - ] = None - - -class Template(BaseModel): - role: Annotated[ - str, - Field( - description='The role of the message (e.g. "system", "assistant", "user").' - ), - ] - content: Annotated[str, Field(description='The content of the message.')] - - -class InputMessages3(BaseModel): - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `item_reference`.'), - ] - item_reference: Annotated[ - str, - Field( - description='A reference to a variable in the `item` namespace. Ie, "item.name"' - ), - ] - - -class CreateEvalStoredCompletionsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['CreateEvalStoredCompletionsDataSourceConfig'], - Field(description='The type of data source. Always `stored_completions`.'), - ] - metadata: Annotated[ - Optional[Dict[str, Any]], - Field(description='Metadata filters for the stored completions data source.'), - ] = None - - -class CreateFineTuningCheckpointPermissionRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - project_ids: Annotated[ - List[str], Field(description='The project identifiers to grant access to.') - ] - - -class BatchSize(RootModel[int]): - root: Annotated[ - int, - Field( - description='Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n', - ge=1, - le=256, - ), - ] - - -class LearningRateMultiplier(RootModel[float]): - root: Annotated[ - float, - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n', - gt=0.0, - ), - ] - - -class NEpochs(RootModel[int]): - root: Annotated[ - int, - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n', - ge=1, - le=50, - ), - ] - - -class Hyperparameters(BaseModel): - batch_size: Annotated[ - Union[Literal['auto'], BatchSize], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n' - ), - ] = 'auto' - - -class Wandb(BaseModel): - project: Annotated[ - str, - Field( - description='The name of the project that the new run will be created under.\n', - examples=['my-wandb-project'], - ), - ] - name: Annotated[ - Optional[str], - Field( - description='A display name to set for the run. If not set, we will use the Job ID as the name.\n' - ), - ] = None - entity: Annotated[ - Optional[str], - Field( - description='The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n' - ), - ] = None - tags: Annotated[ - Optional[List[str]], - Field( - description='A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}".\n' - ), - ] = None - - -class Integration(BaseModel): - type: Annotated[ - Literal['wandb'], - Field( - description='The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported.\n' - ), - ] - wandb: Annotated[ - Wandb, - Field( - description='The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n' - ), - ] - - -class CreateGroupBody(BaseModel): - name: Annotated[ - str, - Field( - description='Human readable name for the group.', - max_length=255, - min_length=1, - ), - ] - - -class CreateGroupUserBody(BaseModel): - user_id: Annotated[ - str, Field(description='Identifier of the user to add to the group.') - ] - - -class Image(RootModel[List[bytes]]): - root: Annotated[ - List[bytes], - Field( - description='The image(s) to edit. Must be a supported image file or an array of images.\n\nFor `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less\nthan 50MB. You can provide up to 16 images.\n\nFor `dall-e-2`, you can only provide one image, and it should be a square\n`png` file less than 4MB.\n', - max_length=16, - ), - ] - - -class CreateImageVariationRequest(BaseModel): - image: Annotated[ - bytes, - Field( - description='The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.' - ), - ] - model: Annotated[ - Optional[Union[Optional[str], Literal['dall-e-2']]], - Field( - description='The model to use for image generation. Only `dall-e-2` is supported at this time.' - ), - ] = None - n: Annotated[ - Optional[int], - Field( - description='The number of images to generate. Must be between 1 and 10.', - examples=[1], - ge=1, - le=10, - ), - ] = 1 - response_format: Annotated[ - Optional[Literal['url', 'b64_json']], - Field( - description='The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.', - examples=['url'], - ), - ] = 'url' - size: Annotated[ - Optional[Literal['256x256', '512x512', '1024x1024']], - Field( - description='The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.', - examples=['1024x1024'], - ), - ] = '1024x1024' - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - examples=['user-1234'], - ), - ] = None - - -class Tools1(RootModel[Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly]]): - root: Annotated[ - Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly], - Field(discriminator='type'), - ] - - -class Attachment(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The ID of the file to attach to the message.') - ] = None - tools: Annotated[ - Optional[List[Tools1]], Field(description='The tools to add this file to.') - ] = None - - -class Categories(BaseModel): - hate: Annotated[ - bool, - Field( - description='Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment.' - ), - ] - hate_threatening: Annotated[ - bool, - Field( - alias='hate/threatening', - description='Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.', - ), - ] - harassment: Annotated[ - bool, - Field( - description='Content that expresses, incites, or promotes harassing language towards any target.' - ), - ] - harassment_threatening: Annotated[ - bool, - Field( - alias='harassment/threatening', - description='Harassment content that also includes violence or serious harm towards any target.', - ), - ] - illicit: Optional[bool] = None - illicit_violent: Annotated[Optional[bool], Field(alias='illicit/violent')] = None - self_harm: Annotated[ - bool, - Field( - alias='self-harm', - description='Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.', - ), - ] - self_harm_intent: Annotated[ - bool, - Field( - alias='self-harm/intent', - description='Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders.', - ), - ] - self_harm_instructions: Annotated[ - bool, - Field( - alias='self-harm/instructions', - description='Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts.', - ), - ] - sexual: Annotated[ - bool, - Field( - description='Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness).' - ), - ] - sexual_minors: Annotated[ - bool, - Field( - alias='sexual/minors', - description='Sexual content that includes an individual who is under 18 years old.', - ), - ] - violence: Annotated[ - bool, - Field(description='Content that depicts death, violence, or physical injury.'), - ] - violence_graphic: Annotated[ - bool, - Field( - alias='violence/graphic', - description='Content that depicts death, violence, or physical injury in graphic detail.', - ), - ] - - -class CategoryScores(BaseModel): - hate: Annotated[float, Field(description="The score for the category 'hate'.")] - hate_threatening: Annotated[ - float, - Field( - alias='hate/threatening', - description="The score for the category 'hate/threatening'.", - ), - ] - harassment: Annotated[ - float, Field(description="The score for the category 'harassment'.") - ] - harassment_threatening: Annotated[ - float, - Field( - alias='harassment/threatening', - description="The score for the category 'harassment/threatening'.", - ), - ] - illicit: Annotated[ - float, Field(description="The score for the category 'illicit'.") - ] - illicit_violent: Annotated[ - float, - Field( - alias='illicit/violent', - description="The score for the category 'illicit/violent'.", - ), - ] - self_harm: Annotated[ - float, - Field(alias='self-harm', description="The score for the category 'self-harm'."), - ] - self_harm_intent: Annotated[ - float, - Field( - alias='self-harm/intent', - description="The score for the category 'self-harm/intent'.", - ), - ] - self_harm_instructions: Annotated[ - float, - Field( - alias='self-harm/instructions', - description="The score for the category 'self-harm/instructions'.", - ), - ] - sexual: Annotated[float, Field(description="The score for the category 'sexual'.")] - sexual_minors: Annotated[ - float, - Field( - alias='sexual/minors', - description="The score for the category 'sexual/minors'.", - ), - ] - violence: Annotated[ - float, Field(description="The score for the category 'violence'.") - ] - violence_graphic: Annotated[ - float, - Field( - alias='violence/graphic', - description="The score for the category 'violence/graphic'.", - ), - ] - - -class CategoryAppliedInputTypes(BaseModel): - hate: Annotated[ - List[Literal['text']], - Field(description="The applied input type(s) for the category 'hate'."), - ] - hate_threatening: Annotated[ - List[Literal['text']], - Field( - alias='hate/threatening', - description="The applied input type(s) for the category 'hate/threatening'.", - ), - ] - harassment: Annotated[ - List[Literal['text']], - Field(description="The applied input type(s) for the category 'harassment'."), - ] - harassment_threatening: Annotated[ - List[Literal['text']], - Field( - alias='harassment/threatening', - description="The applied input type(s) for the category 'harassment/threatening'.", - ), - ] - illicit: Annotated[ - List[Literal['text']], - Field(description="The applied input type(s) for the category 'illicit'."), - ] - illicit_violent: Annotated[ - List[Literal['text']], - Field( - alias='illicit/violent', - description="The applied input type(s) for the category 'illicit/violent'.", - ), - ] - self_harm: Annotated[ - List[Literal['text', 'image']], - Field( - alias='self-harm', - description="The applied input type(s) for the category 'self-harm'.", - ), - ] - self_harm_intent: Annotated[ - List[Literal['text', 'image']], - Field( - alias='self-harm/intent', - description="The applied input type(s) for the category 'self-harm/intent'.", - ), - ] - self_harm_instructions: Annotated[ - List[Literal['text', 'image']], - Field( - alias='self-harm/instructions', - description="The applied input type(s) for the category 'self-harm/instructions'.", - ), - ] - sexual: Annotated[ - List[Literal['text', 'image']], - Field(description="The applied input type(s) for the category 'sexual'."), - ] - sexual_minors: Annotated[ - List[Literal['text']], - Field( - alias='sexual/minors', - description="The applied input type(s) for the category 'sexual/minors'.", - ), - ] - violence: Annotated[ - List[Literal['text', 'image']], - Field(description="The applied input type(s) for the category 'violence'."), - ] - violence_graphic: Annotated[ - List[Literal['text', 'image']], - Field( - alias='violence/graphic', - description="The applied input type(s) for the category 'violence/graphic'.", - ), - ] - - -class Result(BaseModel): - flagged: Annotated[ - bool, Field(description='Whether any of the below categories are flagged.') - ] - categories: Annotated[ - Categories, - Field( - description='A list of the categories, and whether they are flagged or not.' - ), - ] - category_scores: Annotated[ - CategoryScores, - Field( - description='A list of the categories along with their scores as predicted by model.' - ), - ] - category_applied_input_types: Annotated[ - CategoryAppliedInputTypes, - Field( - description='A list of the categories along with the input type(s) that the score applies to.' - ), - ] - - -class CreateModerationResponse(BaseModel): - id: Annotated[ - str, Field(description='The unique identifier for the moderation request.') - ] - model: Annotated[ - str, Field(description='The model used to generate the moderation results.') - ] - results: Annotated[List[Result], Field(description='A list of moderation objects.')] - - -class ToolResources2(BaseModel): - code_interpreter: Optional[CodeInterpreter1] = None - file_search: Optional[FileSearch] = None - - -class ChunkingStrategy4(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class ChunkingStrategy5(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class ChunkingStrategy6(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `auto`.'), - ] - - -class ChunkingStrategy7(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Always `static`.'), - ] - static: Static - - -class Logprob(BaseModel): - token: Annotated[ - Optional[str], Field(description='The token in the transcription.') - ] = None - logprob: Annotated[ - Optional[float], Field(description='The log probability of the token.') - ] = None - bytes: Annotated[ - Optional[List[float]], Field(description='The bytes of the token.') - ] = None - - -class CreateTranslationRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - file: Annotated[ - bytes, - Field( - description='The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n' - ), - ] - model: Annotated[ - Union[str, Literal['whisper-1']], - Field( - description='ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n', - examples=['whisper-1'], - ), - ] - prompt: Annotated[ - Optional[str], - Field( - description="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 be in English.\n" - ), - ] = None - response_format: Annotated[ - Literal['json', 'text', 'srt', 'verbose_json', 'vtt'], - Field( - description='The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n' - ), - ] = 'json' - temperature: Annotated[ - float, - Field( - description='The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n' - ), - ] = 0 - - -class CreateTranslationResponseJson(BaseModel): - text: str - - -class CustomToolCall(BaseModel): - type: Annotated[ - Literal['CustomToolCall'], - Field( - description='The type of the custom tool call. Always `custom_tool_call`.\n' - ), - ] - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the custom tool call in the OpenAI platform.\n' - ), - ] = None - call_id: Annotated[ - str, - Field( - description='An identifier used to map this custom tool call to a tool call output.\n' - ), - ] - name: Annotated[ - str, Field(description='The name of the custom tool being called.\n') - ] - input: Annotated[ - str, - Field( - description='The input for the custom tool call generated by the model.\n' - ), - ] - - -class Format(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Unconstrained text format. Always `text`.'), - ] - - -class Grammar(BaseModel): - definition: Annotated[str, Field(description='The grammar definition.')] - syntax: Annotated[ - Literal['lark', 'regex'], - Field( - description='The syntax of the grammar definition. One of `lark` or `regex`.' - ), - ] - - -class Format1(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='Grammar format. Always `grammar`.'), - ] - grammar: Annotated[ - Grammar, Field(description='Your chosen grammar.', title='Grammar format') - ] - - -class Custom2(BaseModel): - name: Annotated[ - str, - Field( - description='The name of the custom tool, used to identify it in tool calls.' - ), - ] - description: Annotated[ - Optional[str], - Field( - description='Optional description of the custom tool, used to provide more context.\n' - ), - ] = None - format: Annotated[ - Optional[Union[Format, Format1]], - Field( - description='The input format for the custom tool. Default is unconstrained text.\n', - discriminator='type', - ), - ] = None - - -class CustomToolChatCompletions(BaseModel): - type: Annotated[ - Literal['CustomToolChatCompletions'], - Field(description='The type of the custom tool. Always `custom`.'), - ] - custom: Annotated[ - Custom2, - Field( - description='Properties of the custom tool.\n', - title='Custom tool properties', - ), - ] - - -class DeleteAssistantResponse(BaseModel): - id: str - deleted: bool - object: Literal['assistant.deleted'] - - -class DeleteCertificateResponse(BaseModel): - object: Annotated[ - Literal['certificate.deleted'], - Field(description='The object type, must be `certificate.deleted`.'), - ] - id: Annotated[str, Field(description='The ID of the certificate that was deleted.')] - - -class DeleteFileResponse(BaseModel): - id: str - object: Literal['file'] - deleted: bool - - -class DeleteFineTuningCheckpointPermissionResponse(BaseModel): - id: Annotated[ - str, - Field( - description='The ID of the fine-tuned model checkpoint permission that was deleted.' - ), - ] - object: Annotated[ - Literal['checkpoint.permission'], - Field(description='The object type, which is always "checkpoint.permission".'), - ] - deleted: Annotated[ - bool, - Field( - description='Whether the fine-tuned model checkpoint permission was successfully deleted.' - ), - ] - - -class DeleteMessageResponse(BaseModel): - id: str - deleted: bool - object: Literal['thread.message.deleted'] - - -class DeleteModelResponse(BaseModel): - id: str - deleted: bool - object: str - - -class DeleteThreadResponse(BaseModel): - id: str - deleted: bool - object: Literal['thread.deleted'] - - -class DeleteVectorStoreFileResponse(BaseModel): - id: str - deleted: bool - object: Literal['vector_store.file.deleted'] - - -class DeleteVectorStoreResponse(BaseModel): - id: str - deleted: bool - object: Literal['vector_store.deleted'] - - -class DeletedRoleAssignmentResource(BaseModel): - object: Annotated[ - str, - Field( - description='Identifier for the deleted assignment, such as `group.role.deleted` or `user.role.deleted`.' - ), - ] - deleted: Annotated[bool, Field(description='Whether the assignment was removed.')] - - -class DoneEvent(BaseModel): - event: Literal['done'] - data: Literal['[DONE]'] - - -class Embedding(BaseModel): - index: Annotated[ - int, Field(description='The index of the embedding in the list of embeddings.') - ] - embedding: Annotated[ - List[float], - Field( - description='The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings).\n' - ), - ] - object: Annotated[ - Literal['embedding'], - Field(description='The object type, which is always "embedding".'), - ] - - -class Error1(BaseModel): - code: Optional[str] = None - message: str - param: Optional[str] = None - type: str - - -class ErrorEvent(BaseModel): - event: Literal['ErrorEvent'] - data: Error1 - - -class ErrorResponse(BaseModel): - error: Error1 - - -class EvalApiError(BaseModel): - code: Annotated[str, Field(description='The error code.')] - message: Annotated[str, Field(description='The error message.')] - - -class EvalCustomDataSourceConfig(BaseModel): - type: Annotated[ - Literal['EvalCustomDataSourceConfig'], - Field(description='The type of data source. Always `custom`.'), - ] - schema_: Annotated[ - Dict[str, Any], - Field( - alias='schema', - description='The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n', - ), - ] - - -class Content7(BaseModel): - type: Annotated[ - Literal['output_text'], - Field(description='The type of the output text. Always `output_text`.\n'), - ] - text: Annotated[str, Field(description='The text output from the model.\n')] - - -class Content8(BaseModel): - type: Annotated[ - Literal['input_image'], - Field(description='The type of the image input. Always `input_image`.\n'), - ] - image_url: Annotated[str, Field(description='The URL of the image input.\n')] - detail: Annotated[ - Optional[str], - Field( - description='The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n' - ), - ] = None - - -class ContentItem(BaseModel): - item: Dict[str, Any] - sample: Optional[Dict[str, Any]] = None - - -class EvalJsonlFileContentSource(BaseModel): - type: Annotated[ - Literal['EvalJsonlFileContentSource'], - Field(description='The type of jsonl source. Always `file_content`.'), - ] - content: Annotated[ - List[ContentItem], Field(description='The content of the jsonl file.') - ] - - -class EvalJsonlFileIdSource(BaseModel): - type: Annotated[ - Literal['EvalJsonlFileIdSource'], - Field(description='The type of jsonl source. Always `file_id`.'), - ] - id: Annotated[str, Field(description='The identifier of the file.')] - - -class CreatedAfter(RootModel[int]): - root: Annotated[ - int, - Field( - description='Only include items created after this timestamp (inclusive). This is a query parameter used to select responses.', - ge=0, - ), - ] - - -class CreatedBefore(RootModel[int]): - root: Annotated[ - int, - Field( - description='Only include items created before this timestamp (inclusive). This is a query parameter used to select responses.', - ge=0, - ), - ] - - -class ResultCounts(BaseModel): - total: Annotated[int, Field(description='Total number of executed output items.')] - errored: Annotated[ - int, Field(description='Number of output items that resulted in an error.') - ] - failed: Annotated[ - int, - Field(description='Number of output items that failed to pass the evaluation.'), - ] - passed: Annotated[ - int, Field(description='Number of output items that passed the evaluation.') - ] - - -class PerModelUsageItem(BaseModel): - model_name: Annotated[str, Field(description='The name of the model.')] - invocation_count: Annotated[int, Field(description='The number of invocations.')] - prompt_tokens: Annotated[ - int, Field(description='The number of prompt tokens used.') - ] - completion_tokens: Annotated[ - int, Field(description='The number of completion tokens generated.') - ] - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - cached_tokens: Annotated[ - int, Field(description='The number of tokens retrieved from cache.') - ] - - -class PerTestingCriteriaResult(BaseModel): - testing_criteria: Annotated[ - str, Field(description='A description of the testing criteria.') - ] - passed: Annotated[ - int, Field(description='Number of tests passed for this criteria.') - ] - failed: Annotated[ - int, Field(description='Number of tests failed for this criteria.') - ] - - -class InputItem(BaseModel): - role: Annotated[ - str, - Field( - description='The role of the message sender (e.g., system, user, developer).' - ), - ] - content: Annotated[str, Field(description='The content of the message.')] - - -class OutputItem(BaseModel): - role: Annotated[ - Optional[str], - Field( - description='The role of the message (e.g. "system", "assistant", "user").' - ), - ] = None - content: Annotated[ - Optional[str], Field(description='The content of the message.') - ] = None - - -class Usage2(BaseModel): - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - completion_tokens: Annotated[ - int, Field(description='The number of completion tokens generated.') - ] - prompt_tokens: Annotated[ - int, Field(description='The number of prompt tokens used.') - ] - cached_tokens: Annotated[ - int, Field(description='The number of tokens retrieved from cache.') - ] - - -class Sample(BaseModel): - input: Annotated[List[InputItem], Field(description='An array of input messages.')] - output: Annotated[ - List[OutputItem], Field(description='An array of output messages.') - ] - finish_reason: Annotated[ - str, Field(description='The reason why the sample generation was finished.') - ] - model: Annotated[ - str, Field(description='The model used for generating the sample.') - ] - usage: Annotated[Usage2, Field(description='Token usage details for the sample.')] - error: EvalApiError - temperature: Annotated[float, Field(description='The sampling temperature used.')] - max_completion_tokens: Annotated[ - int, Field(description='The maximum number of tokens allowed for completion.') - ] - top_p: Annotated[float, Field(description='The top_p value used for sampling.')] - seed: Annotated[int, Field(description='The seed used for generating the sample.')] - - -class EvalRunOutputItemResult(BaseModel): - model_config = ConfigDict( - extra='allow', - ) - name: Annotated[str, Field(description='The name of the grader.')] - type: Annotated[ - Optional[str], - Field(description='The grader type (for example, "string-check-grader").'), - ] = None - score: Annotated[ - float, Field(description='The numeric score produced by the grader.') - ] - passed: Annotated[ - bool, Field(description='Whether the grader considered the output a pass.') - ] - sample: Annotated[ - Optional[Dict[str, Any]], - Field( - description='Optional sample or intermediate data produced by the grader.' - ), - ] = None - - -class FileExpirationAfter(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.' - ), - ] - seconds: Annotated[ - int, - Field( - description='The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).', - ge=3600, - le=2592000, - ), - ] - - -class FilePath(BaseModel): - type: Annotated[ - Literal['FilePath'], - Field(description='The type of the file path. Always `file_path`.\n'), - ] - file_id: Annotated[str, Field(description='The ID of the file.\n')] - index: Annotated[ - int, Field(description='The index of the file in the list of files.\n') - ] - - -class FileSearchRanker(RootModel[Literal['auto', 'default_2024_08_21']]): - root: Annotated[ - Literal['auto', 'default_2024_08_21'], - Field( - description='The ranker to use for the file search. If not specified will use the `auto` ranker.' - ), - ] - - -class FileSearchRankingOptions(BaseModel): - ranker: Optional[FileSearchRanker] = None - score_threshold: Annotated[ - float, - Field( - description='The score threshold for the file search. All values must be a floating point number between 0 and 1.', - ge=0.0, - le=1.0, - ), - ] - - -class Beta(RootModel[float]): - root: Annotated[ - float, - Field( - description='The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n', - gt=0.0, - le=2.0, - ), - ] - - -class BatchSize1(RootModel[int]): - root: Annotated[ - int, - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n', - ge=1, - le=256, - ), - ] - - -class LearningRateMultiplier1(RootModel[float]): - root: Annotated[ - float, - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n', - gt=0.0, - ), - ] - - -class NEpochs1(RootModel[int]): - root: Annotated[ - int, - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n', - ge=1, - le=50, - ), - ] - - -class FineTuneDPOHyperparameters(BaseModel): - beta: Annotated[ - Optional[Union[Literal['auto'], Beta]], - Field( - description='The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n' - ), - ] = None - batch_size: Annotated[ - Union[Literal['auto'], BatchSize1], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier1]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs1], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n' - ), - ] = 'auto' - - -class FineTuneDPOMethod(BaseModel): - hyperparameters: Optional[FineTuneDPOHyperparameters] = None - - -class ComputeMultiplier(RootModel[float]): - root: Annotated[ - float, - Field( - description='Multiplier on amount of compute used for exploring search space during training.\n', - gt=1e-05, - le=10.0, - ), - ] - - -class EvalInterval(RootModel[int]): - root: Annotated[ - int, - Field( - description='The number of training steps between evaluation runs.\n', ge=1 - ), - ] - - -class EvalSamples(RootModel[int]): - root: Annotated[ - int, - Field( - description='Number of evaluation samples to generate per training step.\n', - ge=1, - ), - ] - - -class FineTuneReinforcementHyperparameters(BaseModel): - batch_size: Annotated[ - Union[Literal['auto'], BatchSize1], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier1]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs1], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n' - ), - ] = 'auto' - reasoning_effort: Annotated[ - Literal['default', 'low', 'medium', 'high'], - Field(description='Level of reasoning effort.\n'), - ] = 'default' - compute_multiplier: Annotated[ - Optional[Union[Literal['auto'], ComputeMultiplier]], - Field( - description='Multiplier on amount of compute used for exploring search space during training.\n' - ), - ] = None - eval_interval: Annotated[ - Union[Literal['auto'], EvalInterval], - Field(description='The number of training steps between evaluation runs.\n'), - ] = 'auto' - eval_samples: Annotated[ - Union[Literal['auto'], EvalSamples], - Field( - description='Number of evaluation samples to generate per training step.\n' - ), - ] = 'auto' - - -class FineTuneSupervisedHyperparameters(BaseModel): - batch_size: Annotated[ - Union[Literal['auto'], BatchSize1], - Field( - description='Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n' - ), - ] = 'auto' - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier1]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs1], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n' - ), - ] = 'auto' - - -class FineTuneSupervisedMethod(BaseModel): - hyperparameters: Optional[FineTuneSupervisedHyperparameters] = None - - -class FineTuningCheckpointPermission(BaseModel): - id: Annotated[ - str, - Field( - description='The permission identifier, which can be referenced in the API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the permission was created.' - ), - ] - project_id: Annotated[ - str, Field(description='The project identifier that the permission is for.') - ] - object: Annotated[ - Literal['checkpoint.permission'], - Field(description='The object type, which is always "checkpoint.permission".'), - ] - - -class Wandb1(BaseModel): - project: Annotated[ - str, - Field( - description='The name of the project that the new run will be created under.\n', - examples=['my-wandb-project'], - ), - ] - name: Optional[str] = None - entity: Optional[str] = None - tags: Annotated[ - Optional[List[str]], - Field( - description='A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}".\n' - ), - ] = None - - -class FineTuningIntegration(BaseModel): - type: Annotated[ - Literal['wandb'], - Field( - description='The type of the integration being enabled for the fine-tuning job' - ), - ] - wandb: Annotated[ - Wandb1, - Field( - description='The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n' - ), - ] - - -class Error2(BaseModel): - code: Annotated[str, Field(description='A machine-readable error code.')] - message: Annotated[str, Field(description='A human-readable error message.')] - param: Optional[str] = None - - -class BatchSize4(RootModel[int]): - root: Annotated[ - int, - Field( - description='Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n', - ge=1, - le=256, - title='Auto', - ), - ] - - -class LearningRateMultiplier4(RootModel[float]): - root: Annotated[ - float, - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n', - gt=0.0, - ), - ] - - -class NEpochs4(RootModel[int]): - root: Annotated[ - int, - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n', - ge=1, - le=50, - ), - ] - - -class Hyperparameters1(BaseModel): - batch_size: Optional[Union[Literal['auto'], BatchSize4]] = None - learning_rate_multiplier: Annotated[ - Optional[Union[Literal['auto'], LearningRateMultiplier4]], - Field( - description='Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n' - ), - ] = None - n_epochs: Annotated[ - Union[Literal['auto'], NEpochs4], - Field( - description='The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n' - ), - ] = 'auto' - - -class Integrations1(RootModel[FineTuningIntegration]): - root: Annotated[FineTuningIntegration, Field(discriminator='type')] - - -class Integrations(RootModel[List[Integrations1]]): - root: Annotated[ - List[Integrations1], - Field( - description='A list of integrations to enable for this fine-tuning job.', - max_length=5, - ), - ] - - -class Metrics(BaseModel): - step: Optional[float] = None - train_loss: Optional[float] = None - train_mean_token_accuracy: Optional[float] = None - valid_loss: Optional[float] = None - valid_mean_token_accuracy: Optional[float] = None - full_valid_loss: Optional[float] = None - full_valid_mean_token_accuracy: Optional[float] = None - - -class FineTuningJobCheckpoint(BaseModel): - id: Annotated[ - str, - Field( - description='The checkpoint identifier, which can be referenced in the API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the checkpoint was created.' - ), - ] - fine_tuned_model_checkpoint: Annotated[ - str, - Field( - description='The name of the fine-tuned checkpoint model that is created.' - ), - ] - step_number: Annotated[ - int, Field(description='The step number that the checkpoint was created at.') - ] - metrics: Annotated[ - Metrics, - Field(description='Metrics at the step number during the fine-tuning job.'), - ] - fine_tuning_job_id: Annotated[ - str, - Field( - description='The name of the fine-tuning job that this checkpoint was created from.' - ), - ] - object: Annotated[ - Literal['fine_tuning.job.checkpoint'], - Field( - description='The object type, which is always "fine_tuning.job.checkpoint".' - ), - ] - - -class FineTuningJobEvent(BaseModel): - object: Annotated[ - Literal['fine_tuning.job.event'], - Field(description='The object type, which is always "fine_tuning.job.event".'), - ] - id: Annotated[str, Field(description='The object identifier.')] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the fine-tuning job was created.' - ), - ] - level: Annotated[ - Literal['info', 'warn', 'error'], - Field(description='The log level of the event.'), - ] - message: Annotated[str, Field(description='The message of the event.')] - type: Annotated[ - Optional[Literal['message', 'metrics']], Field(description='The type of event.') - ] = None - data: Annotated[ - Optional[Dict[str, Any]], - Field(description='The data associated with the event.'), - ] = None - - -class FunctionParameters(BaseModel): - pass - model_config = ConfigDict( - extra='allow', - ) - - -class FunctionToolCall(BaseModel): - id: Annotated[ - Optional[str], Field(description='The unique ID of the function tool call.\n') - ] = None - type: Annotated[ - Literal['FunctionToolCall'], - Field( - description='The type of the function tool call. Always `function_call`.\n' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the function tool call generated by the model.\n' - ), - ] - name: Annotated[str, Field(description='The name of the function to run.\n')] - arguments: Annotated[ - str, - Field(description='A JSON string of the arguments to pass to the function.\n'), - ] - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' - ), - ] = None - - -class FunctionToolCallResource(FunctionToolCall): - id: Annotated[str, Field(description='The unique ID of the function tool call.\n')] - type: Literal['FunctionToolCallResource'] - - -class GraderPython(BaseModel): - type: Annotated[ - Literal['GraderPython'], - Field(description='The object type, which is always `python`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - source: Annotated[str, Field(description='The source code of the python script.')] - image_tag: Annotated[ - Optional[str], Field(description='The image tag to use for the python script.') - ] = None - - -class MaxCompletionsTokens(RootModel[int]): - root: Annotated[ - int, - Field( - description='The maximum number of tokens the grader model may generate in its response.\n', - ge=1, - ), - ] - - -class GraderStringCheck(BaseModel): - type: Annotated[ - Literal['GraderStringCheck'], - Field(description='The object type, which is always `string_check`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - input: Annotated[ - str, Field(description='The input text. This may include template strings.') - ] - reference: Annotated[ - str, Field(description='The reference text. This may include template strings.') - ] - operation: Annotated[ - Literal['eq', 'ne', 'like', 'ilike'], - Field( - description='The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.' - ), - ] - - -class GraderTextSimilarity(BaseModel): - type: Annotated[ - Literal['GraderTextSimilarity'], Field(description='The type of grader.') - ] - name: Annotated[str, Field(description='The name of the grader.')] - input: Annotated[str, Field(description='The text being graded.')] - reference: Annotated[str, Field(description='The text being graded against.')] - evaluation_metric: Annotated[ - Literal[ - 'cosine', - 'fuzzy_match', - 'bleu', - 'gleu', - 'meteor', - 'rouge_1', - 'rouge_2', - 'rouge_3', - 'rouge_4', - 'rouge_5', - 'rouge_l', - ], - Field( - description='The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n' - ), - ] - - -class Group(BaseModel): - object: Annotated[Literal['group'], Field(description='Always `group`.')] - id: Annotated[str, Field(description='Identifier for the group.')] - name: Annotated[str, Field(description='Display name of the group.')] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) when the group was created.'), - ] - scim_managed: Annotated[ - bool, Field(description='Whether the group is managed through SCIM.') - ] - - -class GroupDeletedResource(BaseModel): - object: Annotated[ - Literal['group.deleted'], Field(description='Always `group.deleted`.') - ] - id: Annotated[str, Field(description='Identifier of the deleted group.')] - deleted: Annotated[bool, Field(description='Whether the group was deleted.')] - - -class GroupResourceWithSuccess(BaseModel): - id: Annotated[str, Field(description='Identifier for the group.')] - name: Annotated[str, Field(description='Updated display name for the group.')] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) when the group was created.'), - ] - is_scim_managed: Annotated[ - bool, - Field( - description='Whether the group is managed through SCIM and controlled by your identity provider.' - ), - ] - - -class GroupResponse(BaseModel): - id: Annotated[str, Field(description='Identifier for the group.')] - name: Annotated[str, Field(description='Display name of the group.')] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) when the group was created.'), - ] - is_scim_managed: Annotated[ - bool, - Field( - description='Whether the group is managed through SCIM and controlled by your identity provider.' - ), - ] - - -class GroupUserAssignment(BaseModel): - object: Annotated[Literal['group.user'], Field(description='Always `group.user`.')] - user_id: Annotated[str, Field(description='Identifier of the user that was added.')] - group_id: Annotated[ - str, Field(description='Identifier of the group the user was added to.') - ] - - -class GroupUserDeletedResource(BaseModel): - object: Annotated[ - Literal['group.user.deleted'], Field(description='Always `group.user.deleted`.') - ] - deleted: Annotated[ - bool, Field(description='Whether the group membership was removed.') - ] - - -class Image1(BaseModel): - b64_json: Annotated[ - Optional[str], - Field( - description='The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`.' - ), - ] = None - url: Annotated[ - Optional[str], - Field( - description='When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for `gpt-image-1`.' - ), - ] = None - revised_prompt: Annotated[ - Optional[str], - Field( - description='For `dall-e-3` only, the revised prompt that was used to generate the image.' - ), - ] = None - - -class ImageEditPartialImageEvent(BaseModel): - type: Annotated[ - Literal['ImageEditPartialImageEvent'], - Field( - description='The type of the event. Always `image_edit.partial_image`.\n' - ), - ] - b64_json: Annotated[ - str, - Field( - description='Base64-encoded partial image data, suitable for rendering as an image.\n' - ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the requested edited image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the requested edited image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the requested edited image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the requested edited image.\n'), - ] - partial_image_index: Annotated[ - int, Field(description='0-based index for the partial image (streaming).\n') - ] - - -class ImageGenPartialImageEvent(BaseModel): - type: Annotated[ - Literal['ImageGenPartialImageEvent'], - Field( - description='The type of the event. Always `image_generation.partial_image`.\n' - ), - ] - b64_json: Annotated[ - str, - Field( - description='Base64-encoded partial image data, suitable for rendering as an image.\n' - ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the requested image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the requested image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the requested image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the requested image.\n'), - ] - partial_image_index: Annotated[ - int, Field(description='0-based index for the partial image (streaming).\n') - ] - - -class InputImageMask(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - image_url: Annotated[ - Optional[str], Field(description='Base64-encoded mask image.\n') - ] = None - file_id: Annotated[ - Optional[str], Field(description='File ID for the mask image.\n') - ] = None - - -class ImageGenToolCall(BaseModel): - type: Annotated[ - Literal['ImageGenToolCall'], - Field( - description='The type of the image generation call. Always `image_generation_call`.\n' - ), - ] - id: Annotated[ - str, Field(description='The unique ID of the image generation call.\n') - ] - status: Annotated[ - Literal['in_progress', 'completed', 'generating', 'failed'], - Field(description='The status of the image generation call.\n'), - ] - result: Optional[str] = None - - -class InputTokensDetails1(BaseModel): - text_tokens: Annotated[ - int, Field(description='The number of text tokens in the input prompt.') - ] - image_tokens: Annotated[ - int, Field(description='The number of image tokens in the input prompt.') - ] - - -class ImagesUsage(BaseModel): - total_tokens: Annotated[ - int, - Field( - description='The total number of tokens (images and text) used for the image generation.\n' - ), - ] - input_tokens: Annotated[ - int, - Field( - description='The number of tokens (images and text) in the input prompt.' - ), - ] - output_tokens: Annotated[ - int, Field(description='The number of image tokens in the output image.') - ] - input_tokens_details: Annotated[ - InputTokensDetails1, - Field( - description='The input tokens detailed information for the image generation.' - ), - ] - - -class InputAudio1(BaseModel): - data: Annotated[str, Field(description='Base64-encoded audio data.\n')] - format: Annotated[ - Literal['mp3', 'wav'], - Field( - description='The format of the audio data. Currently supported formats are `mp3` and\n`wav`.\n' - ), - ] - - -class InputAudioModel(BaseModel): - type: Annotated[ - Literal['input_audio'], - Field(description='The type of the input item. Always `input_audio`.\n'), - ] - input_audio: InputAudio1 - - -class Project1(BaseModel): - id: Annotated[Optional[str], Field(description="Project's public ID")] = None - role: Annotated[ - Optional[Literal['member', 'owner']], - Field(description='Project membership role'), - ] = None - - -class Invite(BaseModel): - object: Annotated[ - Literal['organization.invite'], - Field(description='The object type, which is always `organization.invite`'), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - email: Annotated[ - str, - Field( - description='The email address of the individual to whom the invite was sent' - ), - ] - role: Annotated[ - Literal['owner', 'reader'], Field(description='`owner` or `reader`') - ] - status: Annotated[ - Literal['accepted', 'expired', 'pending'], - Field(description='`accepted`,`expired`, or `pending`'), - ] - invited_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the invite was sent.' - ), - ] - expires_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the invite expires.' - ), - ] - accepted_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) of when the invite was accepted.' - ), - ] = None - projects: Annotated[ - Optional[List[Project1]], - Field( - description='The projects that were granted membership upon acceptance of the invite.' - ), - ] = None - - -class InviteDeleteResponse(BaseModel): - object: Annotated[ - Literal['organization.invite.deleted'], - Field( - description='The object type, which is always `organization.invite.deleted`' - ), - ] - id: str - deleted: bool - - -class InviteListResponse(BaseModel): - object: Annotated[ - Literal['list'], Field(description='The object type, which is always `list`') - ] - data: List[Invite] - first_id: Annotated[ - Optional[str], - Field(description='The first `invite_id` in the retrieved `list`'), - ] = None - last_id: Annotated[ - Optional[str], Field(description='The last `invite_id` in the retrieved `list`') - ] = None - has_more: Annotated[ - Optional[bool], - Field( - description='The `has_more` property is used for pagination to indicate there are additional results.' - ), - ] = None - - -class InviteProjectGroupBody(BaseModel): - group_id: Annotated[ - str, Field(description='Identifier of the group to add to the project.') - ] - role: Annotated[ - str, Field(description='Identifier of the project role to grant to the group.') - ] - - -class Project2(BaseModel): - id: Annotated[str, Field(description="Project's public ID")] - role: Annotated[ - Literal['member', 'owner'], Field(description='Project membership role') - ] - - -class InviteRequest(BaseModel): - email: Annotated[str, Field(description='Send an email to this address')] - role: Annotated[ - Literal['reader', 'owner'], Field(description='`owner` or `reader`') - ] - projects: Annotated[ - Optional[List[Project2]], - Field( - description='An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior.' - ), - ] = None - - -class ListCertificatesResponse(BaseModel): - data: List[Certificate2] - first_id: Annotated[Optional[str], Field(examples=['cert_abc'])] = None - last_id: Annotated[Optional[str], Field(examples=['cert_abc'])] = None - has_more: bool - object: Literal['list'] - - -class ListFineTuningCheckpointPermissionResponse(BaseModel): - data: List[FineTuningCheckpointPermission] - object: Literal['list'] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: bool - - -class ListFineTuningJobCheckpointsResponse(BaseModel): - data: List[FineTuningJobCheckpoint] - object: Literal['list'] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: bool - - -class ListFineTuningJobEventsResponse(BaseModel): - data: List[FineTuningJobEvent] - object: Literal['list'] - has_more: bool - - -class LocalShellToolCallOutput(BaseModel): - type: Annotated[ - Literal['LocalShellToolCallOutput'], - Field( - description='The type of the local shell tool call output. Always `local_shell_call_output`.\n' - ), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the local shell tool call generated by the model.\n' - ), - ] - output: Annotated[ - str, - Field( - description='A JSON string of the output of the local shell tool call.\n' - ), - ] - status: Optional[Literal['in_progress', 'completed', 'incomplete']] = None - - -class LogProbProperties(BaseModel): - token: Annotated[ - str, - Field(description='The token that was used to generate the log probability.\n'), - ] - logprob: Annotated[float, Field(description='The log probability of the token.\n')] - bytes: Annotated[ - List[int], - Field( - description='The bytes that were used to generate the log probability.\n' - ), - ] - - -class MCPApprovalRequest(BaseModel): - type: Annotated[ - Literal['MCPApprovalRequest'], - Field(description='The type of the item. Always `mcp_approval_request`.\n'), - ] - id: Annotated[str, Field(description='The unique ID of the approval request.\n')] - server_label: Annotated[ - str, Field(description='The label of the MCP server making the request.\n') - ] - name: Annotated[str, Field(description='The name of the tool to run.\n')] - arguments: Annotated[ - str, Field(description='A JSON string of arguments for the tool.\n') - ] - - -class MCPApprovalResponse(BaseModel): - type: Annotated[ - Literal['MCPApprovalResponse'], - Field(description='The type of the item. Always `mcp_approval_response`.\n'), - ] - id: Optional[str] = None - approval_request_id: Annotated[ - str, Field(description='The ID of the approval request being answered.\n') - ] - approve: Annotated[bool, Field(description='Whether the request was approved.\n')] - reason: Optional[str] = None - - -class MCPApprovalResponseResource(BaseModel): - type: Annotated[ - Literal['MCPApprovalResponseResource'], - Field(description='The type of the item. Always `mcp_approval_response`.\n'), - ] - id: Annotated[str, Field(description='The unique ID of the approval response\n')] - approval_request_id: Annotated[ - str, Field(description='The ID of the approval request being answered.\n') - ] - approve: Annotated[bool, Field(description='Whether the request was approved.\n')] - reason: Optional[str] = None - - -class MCPListToolsTool(BaseModel): - name: Annotated[str, Field(description='The name of the tool.\n')] - description: Optional[str] = None - input_schema: Annotated[ - Dict[str, Any], - Field(description="The JSON schema describing the tool's input.\n"), - ] - annotations: Optional[Dict[str, Any]] = None - - -class MCPToolFilter(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - tool_names: Annotated[ - Optional[List[str]], - Field(description='List of allowed tool names.', title='MCP allowed tools'), - ] = None - read_only: Annotated[ - Optional[bool], - Field( - description='Indicates whether or not a tool modifies data or is read-only. If an\nMCP server is [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),\nit will match this filter.\n' - ), - ] = None - - -class ImageFile(BaseModel): - file_id: Annotated[ - str, - Field( - description='The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' - ), - ] - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.' - ), - ] = 'auto' - - -class MessageContentImageFileObject(BaseModel): - type: Annotated[ - Literal['MessageContentImageFileObject'], - Field(description='Always `image_file`.'), - ] - image_file: ImageFile - - -class ImageUrl1(BaseModel): - url: Annotated[ - AnyUrl, - Field( - description='The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' - ), - ] - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`' - ), - ] = 'auto' - - -class MessageContentImageUrlObject(BaseModel): - type: Annotated[ - Literal['MessageContentImageUrlObject'], - Field(description='The type of the content part.'), - ] - image_url: ImageUrl1 - - -class MessageContentRefusalObject(BaseModel): - type: Annotated[ - Literal['MessageContentRefusalObject'], Field(description='Always `refusal`.') - ] - refusal: str - - -class FileCitation(BaseModel): - file_id: Annotated[ - str, Field(description='The ID of the specific File the citation is from.') - ] - - -class MessageContentTextAnnotationsFileCitationObject(BaseModel): - type: Annotated[ - Literal['MessageContentTextAnnotationsFileCitationObject'], - Field(description='Always `file_citation`.'), - ] - text: Annotated[ - str, - Field(description='The text in the message content that needs to be replaced.'), - ] - file_citation: FileCitation - start_index: Annotated[int, Field(ge=0)] - end_index: Annotated[int, Field(ge=0)] - - -class FilePath1(BaseModel): - file_id: Annotated[str, Field(description='The ID of the file that was generated.')] - - -class MessageContentTextAnnotationsFilePathObject(BaseModel): - type: Annotated[ - Literal['MessageContentTextAnnotationsFilePathObject'], - Field(description='Always `file_path`.'), - ] - text: Annotated[ - str, - Field(description='The text in the message content that needs to be replaced.'), - ] - file_path: FilePath1 - start_index: Annotated[int, Field(ge=0)] - end_index: Annotated[int, Field(ge=0)] - - -class ImageFile1(BaseModel): - file_id: Annotated[ - Optional[str], - Field( - description='The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' - ), - ] = None - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.' - ), - ] = 'auto' - - -class MessageDeltaContentImageFileObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the content part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentImageFileObject'], - Field(description='Always `image_file`.'), - ] - image_file: Optional[ImageFile1] = None - - -class ImageUrl2(BaseModel): - url: Annotated[ - Optional[str], - Field( - description='The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' - ), - ] = None - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`.' - ), - ] = 'auto' - - -class MessageDeltaContentImageUrlObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the content part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentImageUrlObject'], - Field(description='Always `image_url`.'), - ] - image_url: Optional[ImageUrl2] = None - - -class MessageDeltaContentRefusalObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the refusal part in the message.') - ] - type: Annotated[ - Literal['MessageDeltaContentRefusalObject'], - Field(description='Always `refusal`.'), - ] - refusal: Optional[str] = None - - -class FileCitation1(BaseModel): - file_id: Annotated[ - Optional[str], - Field(description='The ID of the specific File the citation is from.'), - ] = None - quote: Annotated[ - Optional[str], Field(description='The specific quote in the file.') - ] = None - - -class MessageDeltaContentTextAnnotationsFileCitationObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the annotation in the text content part.') - ] - type: Annotated[ - Literal['MessageDeltaContentTextAnnotationsFileCitationObject'], - Field(description='Always `file_citation`.'), - ] - text: Annotated[ - Optional[str], - Field(description='The text in the message content that needs to be replaced.'), - ] = None - file_citation: Optional[FileCitation1] = None - start_index: Annotated[Optional[int], Field(ge=0)] = None - end_index: Annotated[Optional[int], Field(ge=0)] = None - - -class FilePath2(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The ID of the file that was generated.') - ] = None - - -class MessageDeltaContentTextAnnotationsFilePathObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the annotation in the text content part.') - ] - type: Annotated[ - Literal['MessageDeltaContentTextAnnotationsFilePathObject'], - Field(description='Always `file_path`.'), - ] - text: Annotated[ - Optional[str], - Field(description='The text in the message content that needs to be replaced.'), - ] = None - file_path: Optional[FilePath2] = None - start_index: Annotated[Optional[int], Field(ge=0)] = None - end_index: Annotated[Optional[int], Field(ge=0)] = None - - -class IncompleteDetails(BaseModel): - reason: Annotated[ - Literal[ - 'content_filter', 'max_tokens', 'run_cancelled', 'run_expired', 'run_failed' - ], - Field(description='The reason the message is incomplete.'), - ] - - -class Attachment1(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The ID of the file to attach to the message.') - ] = None - tools: Annotated[ - Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly]]], - Field(description='The tools to add this file to.'), - ] = None - - -class MessageRequestContentTextObject(BaseModel): - type: Annotated[ - Literal['MessageRequestContentTextObject'], Field(description='Always `text`.') - ] - text: Annotated[str, Field(description='Text content to be sent to the model')] - - -class Metadata(RootModel[Optional[Dict[str, str]]]): - root: Optional[Dict[str, str]] - - -class Model(BaseModel): - id: Annotated[ - str, - Field( - description='The model identifier, which can be referenced in the API endpoints.' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) when the model was created.' - ), - ] - object: Annotated[ - Literal['model'], Field(description='The object type, which is always "model".') - ] - owned_by: Annotated[str, Field(description='The organization that owns the model.')] - - -class TopLogprobs(RootModel[int]): - root: Annotated[ - int, - Field( - description='An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n', - ge=0, - le=20, - ), - ] - - -class Temperature2(RootModel[float]): - root: Annotated[ - float, - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n', - examples=[1], - ge=0.0, - le=2.0, - ), - ] - - -class TopP2(RootModel[float]): - root: Annotated[ - float, - Field( - description='An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n', - examples=[1], - ge=0.0, - le=1.0, - ), - ] - - -class CodeInterpreter4(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n', - max_length=20, - ), - ] = [] - - -class FileSearch7(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), - ] = None - - -class ToolResources4(BaseModel): - code_interpreter: Optional[CodeInterpreter4] = None - file_search: Optional[FileSearch7] = None - - -class Temperature3(RootModel[float]): - root: Annotated[ - float, - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - examples=[1], - ge=0.0, - le=2.0, - ), - ] - - -class TopP3(RootModel[float]): - root: Annotated[ - float, - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - examples=[1], - ge=0.0, - le=1.0, - ), - ] - - -class ModifyCertificateRequest(BaseModel): - name: Annotated[str, Field(description='The updated name for the certificate')] - - -class ModifyMessageRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - metadata: Optional[Metadata] = None - - -class ModifyRunRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - metadata: Optional[Metadata] = None - - -class CodeInterpreter5(BaseModel): - file_ids: Annotated[ - List[str], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n', - max_length=20, - ), - ] = [] - - -class FileSearch8(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_length=1, - ), - ] = None - - -class ToolResources5(BaseModel): - code_interpreter: Optional[CodeInterpreter5] = None - file_search: Optional[FileSearch8] = None - - -class ModifyThreadRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - tool_resources: Optional[ToolResources5] = None - metadata: Optional[Metadata] = None - - -class Move(BaseModel): - type: Annotated[ - Literal['Move'], - Field( - description='Specifies the event type. For a move action, this property is \nalways set to `move`.\n' - ), - ] - x: Annotated[int, Field(description='The x-coordinate to move to.\n')] - y: Annotated[int, Field(description='The y-coordinate to move to.\n')] - - -class NoiseReductionType(RootModel[Literal['near_field', 'far_field']]): - root: Annotated[ - Literal['near_field', 'far_field'], - Field( - description='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.\n' - ), - ] - - -class OpenAIFile(BaseModel): - id: Annotated[ - str, - Field( - description='The file identifier, which can be referenced in the API endpoints.' - ), - ] - bytes: Annotated[int, Field(description='The size of the file, in bytes.')] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the file was created.' - ), - ] - expires_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the file will expire.' - ), - ] = None - filename: Annotated[str, Field(description='The name of the file.')] - object: Annotated[ - Literal['file'], Field(description='The object type, which is always `file`.') - ] - purpose: Annotated[ - Literal[ - 'assistants', - 'assistants_output', - 'batch', - 'batch_output', - 'fine-tune', - 'fine-tune-results', - 'vision', - 'user_data', - ], - Field( - description='The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.' - ), - ] - status: Annotated[ - Literal['uploaded', 'processed', 'error'], - Field( - description='Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.' - ), - ] - status_details: Annotated[ - Optional[str], - Field( - description='Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`.' - ), - ] = None - - -class OtherChunkingStrategyResponseParam(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['OtherChunkingStrategyResponseParam'], - Field(description='Always `other`.'), - ] - - -class OutputAudio(BaseModel): - type: Annotated[ - Literal['output_audio'], - Field(description='The type of the output audio. Always `output_audio`.\n'), - ] - data: Annotated[ - str, Field(description='Base64-encoded audio data from the model.\n') - ] - transcript: Annotated[ - str, Field(description='The transcript of the audio data from the model.\n') - ] - - -class ParallelToolCalls(RootModel[bool]): - root: Annotated[ - bool, - Field( - description='Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use.' - ), - ] - - -class PartialImages1(RootModel[int]): - root: Annotated[ - int, - Field( - description='The number of partial images to generate. This parameter is used for\nstreaming responses that return partial images. Value must be between 0 and 3.\nWhen set to 0, the response will be a single image sent in one streaming event.\n\nNote that the final image may be sent before the full number of partial images\nare generated if the full image is generated more quickly.\n', - examples=[1], - ge=0, - le=3, - ), - ] - - -class PartialImages(RootModel[Optional[PartialImages1]]): - root: Optional[PartialImages1] - - -class Content9(RootModel[List[ChatCompletionRequestMessageContentPartText]]): - root: Annotated[ - List[ChatCompletionRequestMessageContentPartText], - Field( - description='An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text inputs.', - min_length=1, - title='Array of content parts', - ), - ] - - -class PredictionContent(BaseModel): - type: Annotated[ - Literal['PredictionContent'], - Field( - description='The type of the predicted content you want to provide. This type is\ncurrently always `content`.\n' - ), - ] - content: Annotated[ - Union[str, Content9], - Field( - description='The content that should be matched when generating a model response.\nIf generated tokens would match this content, the entire model response\ncan be returned much more quickly.\n' - ), - ] - - -class Project3(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - object: Annotated[ - Literal['organization.project'], - Field(description='The object type, which is always `organization.project`'), - ] - name: Annotated[ - str, Field(description='The name of the project. This appears in reporting.') - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the project was created.' - ), - ] - archived_at: Optional[int] = None - status: Annotated[ - Literal['active', 'archived'], Field(description='`active` or `archived`') - ] - - -class ProjectApiKeyDeleteResponse(BaseModel): - object: Literal['organization.project.api_key.deleted'] - id: str - deleted: bool - - -class ProjectCreateRequest(BaseModel): - name: Annotated[ - str, - Field( - description='The friendly name of the project, this name appears in reports.' - ), - ] - geography: Annotated[ - Optional[Literal['US', 'EU', 'JP', 'IN', 'KR', 'CA', 'AU', 'SG']], - Field( - description='Create the project with the specified data residency region. Your organization must have access to Data residency functionality in order to use. See [data residency controls](https://platform.openai.com/docs/guides/your-data#data-residency-controls) to review the functionality and limitations of setting this field.' - ), - ] = None - - -class ProjectGroup(BaseModel): - object: Annotated[ - Literal['project.group'], Field(description='Always `project.group`.') - ] - project_id: Annotated[str, Field(description='Identifier of the project.')] - group_id: Annotated[ - str, - Field(description='Identifier of the group that has access to the project.'), - ] - group_name: Annotated[str, Field(description='Display name of the group.')] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) when the group was granted project access.' - ), - ] - - -class ProjectGroupDeletedResource(BaseModel): - object: Annotated[ - Literal['project.group.deleted'], - Field(description='Always `project.group.deleted`.'), - ] - deleted: Annotated[ - bool, - Field(description='Whether the group membership in the project was removed.'), - ] - - -class ProjectGroupListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[ProjectGroup], - Field(description='Project group memberships returned in the current page.'), - ] - has_more: Annotated[ - bool, - Field( - description='Whether additional project group memberships are available.' - ), - ] - next: Annotated[ - Optional[str], - Field( - description='Cursor to fetch the next page of results, or `null` when there are no more results.' - ), - ] = None - - -class ProjectListResponse(BaseModel): - object: Literal['list'] - data: List[Project3] - first_id: str - last_id: str - has_more: bool - - -class ProjectRateLimit(BaseModel): - object: Annotated[ - Literal['project.rate_limit'], - Field(description='The object type, which is always `project.rate_limit`'), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - model: Annotated[str, Field(description='The model this rate limit applies to.')] - max_requests_per_1_minute: Annotated[ - int, Field(description='The maximum requests per minute.') - ] - max_tokens_per_1_minute: Annotated[ - int, Field(description='The maximum tokens per minute.') - ] - max_images_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum images per minute. Only present for relevant models.' - ), - ] = None - max_audio_megabytes_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum audio megabytes per minute. Only present for relevant models.' - ), - ] = None - max_requests_per_1_day: Annotated[ - Optional[int], - Field( - description='The maximum requests per day. Only present for relevant models.' - ), - ] = None - batch_1_day_max_input_tokens: Annotated[ - Optional[int], - Field( - description='The maximum batch input tokens per day. Only present for relevant models.' - ), - ] = None - - -class ProjectRateLimitListResponse(BaseModel): - object: Literal['list'] - data: List[ProjectRateLimit] - first_id: str - last_id: str - has_more: bool - - -class ProjectRateLimitUpdateRequest(BaseModel): - max_requests_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum requests per minute.') - ] = None - max_tokens_per_1_minute: Annotated[ - Optional[int], Field(description='The maximum tokens per minute.') - ] = None - max_images_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum images per minute. Only relevant for certain models.' - ), - ] = None - max_audio_megabytes_per_1_minute: Annotated[ - Optional[int], - Field( - description='The maximum audio megabytes per minute. Only relevant for certain models.' - ), - ] = None - max_requests_per_1_day: Annotated[ - Optional[int], - Field( - description='The maximum requests per day. Only relevant for certain models.' - ), - ] = None - batch_1_day_max_input_tokens: Annotated[ - Optional[int], - Field( - description='The maximum batch input tokens per day. Only relevant for certain models.' - ), - ] = None - - -class ProjectServiceAccount(BaseModel): - object: Annotated[ - Literal['organization.project.service_account'], - Field( - description='The object type, which is always `organization.project.service_account`' - ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the service account')] - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the service account was created' - ), - ] - - -class ProjectServiceAccountApiKey(BaseModel): - object: Annotated[ - Literal['organization.project.service_account.api_key'], - Field( - description='The object type, which is always `organization.project.service_account.api_key`' - ), - ] - value: str - name: str - created_at: int - id: str - - -class ProjectServiceAccountCreateRequest(BaseModel): - name: Annotated[ - str, Field(description='The name of the service account being created.') - ] - - -class ProjectServiceAccountCreateResponse(BaseModel): - object: Literal['organization.project.service_account'] - id: str - name: str - role: Annotated[ - Literal['member'], - Field(description='Service accounts can only have one role of type `member`'), - ] - created_at: int - api_key: ProjectServiceAccountApiKey - - -class ProjectServiceAccountDeleteResponse(BaseModel): - object: Literal['organization.project.service_account.deleted'] - id: str - deleted: bool - - -class ProjectServiceAccountListResponse(BaseModel): - object: Literal['list'] - data: List[ProjectServiceAccount] - first_id: str - last_id: str - has_more: bool - - -class ProjectUpdateRequest(BaseModel): - name: Annotated[ - str, - Field( - description='The updated name of the project, this name appears in reports.' - ), - ] - - -class ProjectUser(BaseModel): - object: Annotated[ - Literal['organization.project.user'], - Field( - description='The object type, which is always `organization.project.user`' - ), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the user')] - email: Annotated[str, Field(description='The email address of the user')] - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - added_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the project was added.' - ), - ] - - -class ProjectUserCreateRequest(BaseModel): - user_id: Annotated[str, Field(description='The ID of the user.')] - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - - -class ProjectUserDeleteResponse(BaseModel): - object: Literal['organization.project.user.deleted'] - id: str - deleted: bool - - -class ProjectUserListResponse(BaseModel): - object: str - data: List[ProjectUser] - first_id: str - last_id: str - has_more: bool - - -class ProjectUserUpdateRequest(BaseModel): - role: Annotated[ - Literal['owner', 'member'], Field(description='`owner` or `member`') - ] - - -class PublicAssignOrganizationGroupRoleBody(BaseModel): - role_id: Annotated[str, Field(description='Identifier of the role to assign.')] - - -class PublicCreateOrganizationRoleBody(BaseModel): - role_name: Annotated[str, Field(description='Unique name for the role.')] - permissions: Annotated[ - List[str], Field(description='Permissions to grant to the role.') - ] - description: Annotated[ - Optional[str], Field(description='Optional description of the role.') - ] = None - - -class PublicUpdateOrganizationRoleBody(BaseModel): - permissions: Annotated[ - Optional[List[str]], - Field(description='Updated set of permissions for the role.'), - ] = None - description: Annotated[ - Optional[str], Field(description='New description for the role.') - ] = None - role_name: Annotated[Optional[str], Field(description='New name for the role.')] = ( - None - ) - - -class RealtimeAudioFormats1(BaseModel): - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The audio format. Always `audio/pcm`.'), - ] - rate: Annotated[ - Optional[Literal[24000]], - Field(description='The sample rate of the audio. Always `24000`.'), - ] = None - - -class RealtimeAudioFormats2(BaseModel): - type: Annotated[ - Literal['1#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The audio format. Always `audio/pcmu`.'), - ] - - -class RealtimeAudioFormats3(BaseModel): - type: Annotated[ - Literal['2#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The audio format. Always `audio/pcma`.'), - ] - - -class RealtimeAudioFormats( - RootModel[ - Union[RealtimeAudioFormats1, RealtimeAudioFormats2, RealtimeAudioFormats3] - ] -): - root: Annotated[ - Union[RealtimeAudioFormats1, RealtimeAudioFormats2, RealtimeAudioFormats3], - Field(discriminator='type'), - ] - - -class RealtimeBetaClientEventConversationItemDelete(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['conversation.item.delete'], - Field(description='The event type, must be `conversation.item.delete`.'), - ] - item_id: Annotated[str, Field(description='The ID of the item to delete.')] - - -class RealtimeBetaClientEventConversationItemRetrieve(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['conversation.item.retrieve'], - Field(description='The event type, must be `conversation.item.retrieve`.'), - ] - item_id: Annotated[str, Field(description='The ID of the item to retrieve.')] - - -class RealtimeBetaClientEventConversationItemTruncate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['conversation.item.truncate'], - Field(description='The event type, must be `conversation.item.truncate`.'), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the assistant message item to truncate. Only assistant message \nitems can be truncated.\n' - ), - ] - content_index: Annotated[ - int, - Field(description='The index of the content part to truncate. Set this to 0.'), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Inclusive duration up to which audio is truncated, in milliseconds. If \nthe audio_end_ms is greater than the actual audio duration, the server \nwill respond with an error.\n' - ), - ] - - -class RealtimeBetaClientEventInputAudioBufferAppend(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['input_audio_buffer.append'], - Field(description='The event type, must be `input_audio_buffer.append`.'), - ] - audio: Annotated[ - str, - Field( - description='Base64-encoded audio bytes. This must be in the format specified by the \n`input_audio_format` field in the session configuration.\n' - ), - ] - - -class RealtimeBetaClientEventInputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['input_audio_buffer.clear'], - Field(description='The event type, must be `input_audio_buffer.clear`.'), - ] - - -class RealtimeBetaClientEventInputAudioBufferCommit(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['input_audio_buffer.commit'], - Field(description='The event type, must be `input_audio_buffer.commit`.'), - ] - - -class RealtimeBetaClientEventOutputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='The unique ID of the client event used for error handling.'), - ] = None - type: Annotated[ - Literal['output_audio_buffer.clear'], - Field(description='The event type, must be `output_audio_buffer.clear`.'), - ] - - -class RealtimeBetaClientEventResponseCancel(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['response.cancel'], - Field(description='The event type, must be `response.cancel`.'), - ] - response_id: Annotated[ - Optional[str], - Field( - description='A specific response ID to cancel - if not provided, will cancel an \nin-progress response in the default conversation.\n' - ), - ] = None - - -class Error3(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - - -class StatusDetails(BaseModel): - type: Annotated[ - Optional[Literal['completed', 'cancelled', 'incomplete', 'failed']], - Field( - description='The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n' - ), - ] = None - reason: Annotated[ - Optional[ - Literal[ - 'turn_detected', - 'client_cancelled', - 'max_output_tokens', - 'content_filter', - ] - ], - Field( - description='The reason the Response did not complete. For a `cancelled` Response, \none of `turn_detected` (the server VAD detected a new start of speech) \nor `client_cancelled` (the client sent a cancel event). For an \n`incomplete` Response, one of `max_output_tokens` or `content_filter` \n(the server-side safety filter activated and cut off the response).\n' - ), - ] = None - error: Annotated[ - Optional[Error3], - Field( - description='A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n' - ), - ] = None - - -class CachedTokensDetails(BaseModel): - text_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached text tokens used as input for the Response.' - ), - ] = None - image_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached image tokens used as input for the Response.' - ), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached audio tokens used as input for the Response.' - ), - ] = None - - -class InputTokenDetails(BaseModel): - cached_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached tokens used as input for the Response.' - ), - ] = None - text_tokens: Annotated[ - Optional[int], - Field(description='The number of text tokens used as input for the Response.'), - ] = None - image_tokens: Annotated[ - Optional[int], - Field(description='The number of image tokens used as input for the Response.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='The number of audio tokens used as input for the Response.'), - ] = None - cached_tokens_details: Annotated[ - Optional[CachedTokensDetails], - Field( - description='Details about the cached tokens used as input for the Response.' - ), - ] = None - - -class OutputTokenDetails(BaseModel): - text_tokens: Annotated[ - Optional[int], - Field(description='The number of text tokens used in the Response.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='The number of audio tokens used in the Response.'), - ] = None - - -class Usage3(BaseModel): - total_tokens: Annotated[ - Optional[int], - Field( - description='The total number of tokens in the Response including input and output \ntext and audio tokens.\n' - ), - ] = None - input_tokens: Annotated[ - Optional[int], - Field( - description='The number of input tokens used in the Response, including text and \naudio tokens.\n' - ), - ] = None - output_tokens: Annotated[ - Optional[int], - Field( - description='The number of output tokens sent in the Response, including text and \naudio tokens.\n' - ), - ] = None - input_token_details: Annotated[ - Optional[InputTokenDetails], - Field(description='Details about the input tokens used in the Response.'), - ] = None - output_token_details: Annotated[ - Optional[OutputTokenDetails], - Field(description='Details about the output tokens used in the Response.'), - ] = None - - -class Tool1(BaseModel): - type: Annotated[ - Optional[Literal['function']], - Field(description='The type of the tool, i.e. `function`.'), - ] = None - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - description: Annotated[ - Optional[str], - Field( - description='The description of the function, including guidance on when and how \nto call it, and guidance about what to tell the user when calling \n(if anything).\n' - ), - ] = None - parameters: Annotated[ - Optional[Dict[str, Any]], - Field(description='Parameters of the function in JSON Schema.'), - ] = None - - -class RealtimeBetaServerEventConversationItemDeleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.deleted'], - Field(description='The event type, must be `conversation.item.deleted`.'), - ] - item_id: Annotated[str, Field(description='The ID of the item that was deleted.')] - - -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.delta'], - Field( - description='The event type, must be `conversation.item.input_audio_transcription.delta`.' - ), - ] - item_id: Annotated[str, Field(description='The ID of the item.')] - content_index: Annotated[ - Optional[int], - Field(description="The index of the content part in the item's content array."), - ] = None - delta: Annotated[Optional[str], Field(description='The text delta.')] = None - logprobs: Optional[List[LogProbProperties]] = None - - -class Error4(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - message: Annotated[ - Optional[str], Field(description='A human-readable error message.') - ] = None - param: Annotated[ - Optional[str], Field(description='Parameter related to the error, if any.') - ] = None - - -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.failed'], - Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.failed`.\n' - ), - ] - item_id: Annotated[str, Field(description='The ID of the user message item.')] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - error: Annotated[Error4, Field(description='Details of the transcription error.')] - - -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionSegment(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.segment'], - Field( - description='The event type, must be `conversation.item.input_audio_transcription.segment`.' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the item containing the input audio content.') - ] - content_index: Annotated[ - int, - Field(description='The index of the input audio content part within the item.'), - ] - text: Annotated[str, Field(description='The text for this segment.')] - id: Annotated[str, Field(description='The segment identifier.')] - speaker: Annotated[ - str, Field(description='The detected speaker label for this segment.') - ] - start: Annotated[float, Field(description='Start time of the segment in seconds.')] - end: Annotated[float, Field(description='End time of the segment in seconds.')] - - -class RealtimeBetaServerEventConversationItemTruncated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.truncated'], - Field(description='The event type, must be `conversation.item.truncated`.'), - ] - item_id: Annotated[ - str, - Field(description='The ID of the assistant message item that was truncated.'), - ] - content_index: Annotated[ - int, Field(description='The index of the content part that was truncated.') - ] - audio_end_ms: Annotated[ - int, - Field( - description='The duration up to which the audio was truncated, in milliseconds.\n' - ), - ] - - -class Error5(BaseModel): - type: Annotated[ - str, - Field( - description='The type of error (e.g., "invalid_request_error", "server_error").\n' - ), - ] - code: Optional[str] = None - message: Annotated[str, Field(description='A human-readable error message.')] - param: Optional[str] = None - event_id: Optional[str] = None - - -class RealtimeBetaServerEventError(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['error'], Field(description='The event type, must be `error`.') - ] - error: Annotated[Error5, Field(description='Details of the error.')] - - -class RealtimeBetaServerEventInputAudioBufferCleared(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.cleared'], - Field(description='The event type, must be `input_audio_buffer.cleared`.'), - ] - - -class RealtimeBetaServerEventInputAudioBufferCommitted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.committed'], - Field(description='The event type, must be `input_audio_buffer.committed`.'), - ] - previous_item_id: Optional[str] = None - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeBetaServerEventInputAudioBufferSpeechStarted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.speech_started'], - Field( - description='The event type, must be `input_audio_buffer.speech_started`.' - ), - ] - audio_start_ms: Annotated[ - int, - Field( - description='Milliseconds from the start of all audio written to the buffer during the \nsession when speech was first detected. This will correspond to the \nbeginning of audio sent to the model, and thus includes the \n`prefix_padding_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the user message item that will be created when speech stops.\n' - ), - ] - - -class RealtimeBetaServerEventInputAudioBufferSpeechStopped(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.speech_stopped'], - Field( - description='The event type, must be `input_audio_buffer.speech_stopped`.' - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Milliseconds since the session started when speech stopped. This will \ncorrespond to the end of audio sent to the model, and thus includes the \n`min_silence_duration_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeBetaServerEventMCPListToolsCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.completed'], - Field(description='The event type, must be `mcp_list_tools.completed`.'), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeBetaServerEventMCPListToolsFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.failed'], - Field(description='The event type, must be `mcp_list_tools.failed`.'), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeBetaServerEventMCPListToolsInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.in_progress'], - Field(description='The event type, must be `mcp_list_tools.in_progress`.'), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RateLimit(BaseModel): - name: Annotated[ - Optional[Literal['requests', 'tokens']], - Field(description='The name of the rate limit (`requests`, `tokens`).\n'), - ] = None - limit: Annotated[ - Optional[int], - Field(description='The maximum allowed value for the rate limit.'), - ] = None - remaining: Annotated[ - Optional[int], - Field(description='The remaining value before the limit is reached.'), - ] = None - reset_seconds: Annotated[ - Optional[float], Field(description='Seconds until the rate limit resets.') - ] = None - - -class RealtimeBetaServerEventRateLimitsUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['rate_limits.updated'], - Field(description='The event type, must be `rate_limits.updated`.'), - ] - rate_limits: Annotated[ - List[RateLimit], Field(description='List of rate limit information.') - ] - - -class RealtimeBetaServerEventResponseAudioDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio.delta'], - Field(description='The event type, must be `response.output_audio.delta`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='Base64-encoded audio data delta.')] - - -class RealtimeBetaServerEventResponseAudioDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio.done'], - Field(description='The event type, must be `response.output_audio.done`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - - -class RealtimeBetaServerEventResponseAudioTranscriptDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio_transcript.delta'], - Field( - description='The event type, must be `response.output_audio_transcript.delta`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The transcript delta.')] - - -class RealtimeBetaServerEventResponseAudioTranscriptDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio_transcript.done'], - Field( - description='The event type, must be `response.output_audio_transcript.done`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - transcript: Annotated[str, Field(description='The final transcript of the audio.')] - - -class Part(BaseModel): - type: Annotated[ - Optional[Literal['text', 'audio']], - Field(description='The content type ("text", "audio").'), - ] = None - text: Annotated[ - Optional[str], Field(description='The text content (if type is "text").') - ] = None - audio: Annotated[ - Optional[str], - Field(description='Base64-encoded audio data (if type is "audio").'), - ] = None - transcript: Annotated[ - Optional[str], - Field(description='The transcript of the audio (if type is "audio").'), - ] = None - - -class RealtimeBetaServerEventResponseContentPartAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.content_part.added'], - Field(description='The event type, must be `response.content_part.added`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[ - str, - Field(description='The ID of the item to which the content part was added.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that was added.')] - - -class RealtimeBetaServerEventResponseContentPartDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.content_part.done'], - Field(description='The event type, must be `response.content_part.done`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that is done.')] - - -class RealtimeBetaServerEventResponseFunctionCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.function_call_arguments.delta'], - Field( - description='The event type, must be `response.function_call_arguments.delta`.\n' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - delta: Annotated[str, Field(description='The arguments delta as a JSON string.')] - - -class RealtimeBetaServerEventResponseFunctionCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.function_call_arguments.done'], - Field( - description='The event type, must be `response.function_call_arguments.done`.\n' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - arguments: Annotated[ - str, Field(description='The final arguments as a JSON string.') - ] - - -class RealtimeBetaServerEventResponseMCPCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call_arguments.delta'], - Field( - description='The event type, must be `response.mcp_call_arguments.delta`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - delta: Annotated[str, Field(description='The JSON-encoded arguments delta.')] - obfuscation: Optional[str] = None - - -class RealtimeBetaServerEventResponseMCPCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call_arguments.done'], - Field( - description='The event type, must be `response.mcp_call_arguments.done`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - arguments: Annotated[ - str, Field(description='The final JSON-encoded arguments string.') - ] - - -class RealtimeBetaServerEventResponseMCPCallCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.completed'], - Field(description='The event type, must be `response.mcp_call.completed`.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeBetaServerEventResponseMCPCallFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.failed'], - Field(description='The event type, must be `response.mcp_call.failed`.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeBetaServerEventResponseMCPCallInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.in_progress'], - Field(description='The event type, must be `response.mcp_call.in_progress`.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeBetaServerEventResponseTextDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_text.delta'], - Field(description='The event type, must be `response.output_text.delta`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The text delta.')] - - -class RealtimeBetaServerEventResponseTextDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_text.done'], - Field(description='The event type, must be `response.output_text.done`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - text: Annotated[str, Field(description='The final text content.')] - - -class RealtimeCallReferRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - target_uri: Annotated[ - str, - Field( - description='URI that should appear in the SIP Refer-To header. Supports values like\n`tel:+14155550123` or `sip:agent@example.com`.', - examples=['tel:+14155550123'], - ), - ] - - -class RealtimeCallRejectRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - status_code: Annotated[ - Optional[int], - Field( - description='SIP response code to send back to the caller. Defaults to `603` (Decline)\nwhen omitted.', - examples=[486], - ), - ] = None - - -class RealtimeClientEventConversationItemDelete(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['conversation.item.delete'], - Field(description='The event type, must be `conversation.item.delete`.'), - ] - item_id: Annotated[str, Field(description='The ID of the item to delete.')] - - -class RealtimeClientEventConversationItemRetrieve(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['conversation.item.retrieve'], - Field(description='The event type, must be `conversation.item.retrieve`.'), - ] - item_id: Annotated[str, Field(description='The ID of the item to retrieve.')] - - -class RealtimeClientEventConversationItemTruncate(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['conversation.item.truncate'], - Field(description='The event type, must be `conversation.item.truncate`.'), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the assistant message item to truncate. Only assistant message \nitems can be truncated.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part to truncate. Set this to `0`.' - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Inclusive duration up to which audio is truncated, in milliseconds. If \nthe audio_end_ms is greater than the actual audio duration, the server \nwill respond with an error.\n' - ), - ] - - -class RealtimeClientEventInputAudioBufferAppend(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['input_audio_buffer.append'], - Field(description='The event type, must be `input_audio_buffer.append`.'), - ] - audio: Annotated[ - str, - Field( - description='Base64-encoded audio bytes. This must be in the format specified by the \n`input_audio_format` field in the session configuration.\n' - ), - ] - - -class RealtimeClientEventInputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['input_audio_buffer.clear'], - Field(description='The event type, must be `input_audio_buffer.clear`.'), - ] - - -class RealtimeClientEventInputAudioBufferCommit(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['input_audio_buffer.commit'], - Field(description='The event type, must be `input_audio_buffer.commit`.'), - ] - - -class RealtimeClientEventOutputAudioBufferClear(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='The unique ID of the client event used for error handling.'), - ] = None - type: Annotated[ - Literal['output_audio_buffer.clear'], - Field(description='The event type, must be `output_audio_buffer.clear`.'), - ] - - -class RealtimeClientEventResponseCancel(BaseModel): - event_id: Annotated[ - Optional[str], - Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, - ), - ] = None - type: Annotated[ - Literal['response.cancel'], - Field(description='The event type, must be `response.cancel`.'), - ] - response_id: Annotated[ - Optional[str], - Field( - description='A specific response ID to cancel - if not provided, will cancel an \nin-progress response in the default conversation.\n' - ), - ] = None - - -class RealtimeConversationItemFunctionCall(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemFunctionCall'], - Field(description='The type of the item. Always `function_call`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - call_id: Annotated[ - Optional[str], Field(description='The ID of the function call.') - ] = None - name: Annotated[str, Field(description='The name of the function being called.')] - arguments: Annotated[ - str, - Field( - description='The arguments of the function call. This is a JSON-encoded string representing the arguments passed to the function, for example `{"arg1": "value1", "arg2": 42}`.' - ), - ] - - -class RealtimeConversationItemFunctionCallOutput(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemFunctionCallOutput'], - Field(description='The type of the item. Always `function_call_output`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - call_id: Annotated[ - str, Field(description='The ID of the function call this output is for.') - ] - output: Annotated[ - str, - Field( - description='The output of the function call, this is free text and can contain any information or simply be empty.' - ), - ] - - -class ContentItem1(BaseModel): - type: Annotated[ - Optional[Literal['output_text', 'output_audio']], - Field( - description='The content type, `output_text` or `output_audio` depending on the session `output_modalities` configuration.' - ), - ] = None - text: Annotated[Optional[str], Field(description='The text content.')] = None - audio: Annotated[ - Optional[str], - Field( - description='Base64-encoded audio bytes, these will be parsed as the format specified in the session output audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified.' - ), - ] = None - transcript: Annotated[ - Optional[str], - Field( - description='The transcript of the audio content, this will always be present if the output type is `audio`.' - ), - ] = None - - -class RealtimeConversationItemMessageAssistant(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemMessageAssistant'], - Field(description='The type of the item. Always `message`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - role: Annotated[ - Literal['assistant'], - Field(description='The role of the message sender. Always `assistant`.'), - ] - content: Annotated[ - List[ContentItem1], Field(description='The content of the message.') - ] - - -class ContentItem2(BaseModel): - type: Annotated[ - Optional[Literal['input_text']], - Field(description='The content type. Always `input_text` for system messages.'), - ] = None - text: Annotated[Optional[str], Field(description='The text content.')] = None - - -class RealtimeConversationItemMessageSystem(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemMessageSystem'], - Field(description='The type of the item. Always `message`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - role: Annotated[ - Literal['system'], - Field(description='The role of the message sender. Always `system`.'), - ] - content: Annotated[ - List[ContentItem2], Field(description='The content of the message.') - ] - - -class ContentItem3(BaseModel): - type: Annotated[ - Optional[Literal['input_text', 'input_audio', 'input_image']], - Field( - description='The content type (`input_text`, `input_audio`, or `input_image`).' - ), - ] = None - text: Annotated[ - Optional[str], Field(description='The text content (for `input_text`).') - ] = None - audio: Annotated[ - Optional[str], - Field( - description='Base64-encoded audio bytes (for `input_audio`), these will be parsed as the format specified in the session input audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified.' - ), - ] = None - image_url: Annotated[ - Optional[str], - Field( - description='Base64-encoded image bytes (for `input_image`) as a data URI. For example `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...`. Supported formats are PNG and JPEG.' - ), - ] = None - detail: Annotated[ - Literal['auto', 'low', 'high'], - Field( - description='The detail level of the image (for `input_image`). `auto` will default to `high`.' - ), - ] = 'auto' - transcript: Annotated[ - Optional[str], - Field( - description='Transcript of the audio (for `input_audio`). This is not sent to the model, but will be attached to the message item for reference.' - ), - ] = None - - -class RealtimeConversationItemMessageUser(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='The unique ID of the item. This may be provided by the client or generated by the server.' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item.' - ), - ] = None - type: Annotated[ - Literal['RealtimeConversationItemMessageUser'], - Field(description='The type of the item. Always `message`.'), - ] - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field(description='The status of the item. Has no effect on the conversation.'), - ] = None - role: Annotated[ - Literal['user'], - Field(description='The role of the message sender. Always `user`.'), - ] - content: Annotated[ - List[ContentItem3], Field(description='The content of the message.') - ] - - -class ContentItem4(BaseModel): - type: Annotated[ - Optional[Literal['input_text', 'input_audio', 'item_reference', 'text']], - Field( - description='The content type (`input_text`, `input_audio`, `item_reference`, `text`).\n' - ), - ] = None - text: Annotated[ - Optional[str], - Field( - description='The text content, used for `input_text` and `text` content types.\n' - ), - ] = None - id: Annotated[ - Optional[str], - Field( - description='ID of a previous conversation item to reference (for `item_reference`\ncontent types in `response.create` events). These can reference both\nclient and server created items.\n' - ), - ] = None - audio: Annotated[ - Optional[str], - Field( - description='Base64-encoded audio bytes, used for `input_audio` content type.\n' - ), - ] = None - transcript: Annotated[ - Optional[str], - Field( - description='The transcript of the audio, used for `input_audio` content type.\n' - ), - ] = None - - -class RealtimeConversationItemWithReference(BaseModel): - id: Annotated[ - Optional[str], - Field( - description='For an item of type (`message` | `function_call` | `function_call_output`)\nthis field allows the client to assign the unique ID of the item. It is\nnot required because the server will generate one if not provided.\n\nFor an item of type `item_reference`, this field is required and is a\nreference to any item that has previously existed in the conversation.\n' - ), - ] = None - type: Annotated[ - Optional[ - Literal[ - 'message', 'function_call', 'function_call_output', 'item_reference' - ] - ], - Field( - description='The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`).\n' - ), - ] = None - object: Annotated[ - Optional[Literal['realtime.item']], - Field( - description='Identifier for the API object being returned - always `realtime.item`.\n' - ), - ] = None - status: Annotated[ - Optional[Literal['completed', 'incomplete', 'in_progress']], - Field( - description='The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect \non the conversation, but are accepted for consistency with the \n`conversation.item.created` event.\n' - ), - ] = None - role: Annotated[ - Optional[Literal['user', 'assistant', 'system']], - Field( - description='The role of the message sender (`user`, `assistant`, `system`), only \napplicable for `message` items.\n' - ), - ] = None - content: Annotated[ - Optional[List[ContentItem4]], - Field( - description='The content of the message, applicable for `message` items. \n- Message items of role `system` support only `input_text` content\n- Message items of role `user` support `input_text` and `input_audio` \n content\n- Message items of role `assistant` support `text` content.\n' - ), - ] = None - call_id: Annotated[ - Optional[str], - Field( - description='The ID of the function call (for `function_call` and \n`function_call_output` items). If passed on a `function_call_output` \nitem, the server will check that a `function_call` item with the same \nID exists in the conversation history.\n' - ), - ] = None - name: Annotated[ - Optional[str], - Field( - description='The name of the function being called (for `function_call` items).\n' - ), - ] = None - arguments: Annotated[ - Optional[str], - Field( - description='The arguments of the function call (for `function_call` items).\n' - ), - ] = None - output: Annotated[ - Optional[str], - Field( - description='The output of the function call (for `function_call_output` items).\n' - ), - ] = None - - -class ExpiresAfter2(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='The anchor point for the client secret expiration, meaning that `seconds` will be added to the `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` is currently supported.\n' - ), - ] = 'created_at' - seconds: Annotated[ - int, - Field( - description='The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200` (2 hours). This default to 600 seconds (10 minutes) if not specified.\n', - ge=10, - le=7200, - ), - ] = 600 - - -class RealtimeFunctionTool(BaseModel): - type: Annotated[ - Literal['RealtimeFunctionTool'], - Field(description='The type of the tool, i.e. `function`.'), - ] - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - description: Annotated[ - Optional[str], - Field( - description='The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n' - ), - ] = None - parameters: Annotated[ - Optional[Dict[str, Any]], - Field(description='Parameters of the function in JSON Schema.'), - ] = None - - -class RealtimeMCPApprovalRequest(BaseModel): - type: Annotated[ - Literal['RealtimeMCPApprovalRequest'], - Field(description='The type of the item. Always `mcp_approval_request`.'), - ] - id: Annotated[str, Field(description='The unique ID of the approval request.')] - server_label: Annotated[ - str, Field(description='The label of the MCP server making the request.') - ] - name: Annotated[str, Field(description='The name of the tool to run.')] - arguments: Annotated[ - str, Field(description='A JSON string of arguments for the tool.') - ] - - -class RealtimeMCPApprovalResponse(BaseModel): - type: Annotated[ - Literal['RealtimeMCPApprovalResponse'], - Field(description='The type of the item. Always `mcp_approval_response`.'), - ] - id: Annotated[str, Field(description='The unique ID of the approval response.')] - approval_request_id: Annotated[ - str, Field(description='The ID of the approval request being answered.') - ] - approve: Annotated[bool, Field(description='Whether the request was approved.')] - reason: Optional[str] = None - - -class RealtimeMCPHTTPError(BaseModel): - type: Literal['http_error'] - code: int - message: str - - -class RealtimeMCPListTools(BaseModel): - type: Annotated[ - Literal['RealtimeMCPListTools'], - Field(description='The type of the item. Always `mcp_list_tools`.'), - ] - id: Annotated[Optional[str], Field(description='The unique ID of the list.')] = None - server_label: Annotated[str, Field(description='The label of the MCP server.')] - tools: Annotated[ - List[MCPListToolsTool], Field(description='The tools available on the server.') - ] - - -class RealtimeMCPProtocolError(BaseModel): - type: Literal['protocol_error'] - code: int - message: str - - -class RealtimeMCPToolExecutionError(BaseModel): - type: Literal['tool_execution_error'] - message: str - - -class Error6(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - - -class StatusDetails1(BaseModel): - type: Annotated[ - Optional[Literal['completed', 'cancelled', 'incomplete', 'failed']], - Field( - description='The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n' - ), - ] = None - reason: Annotated[ - Optional[ - Literal[ - 'turn_detected', - 'client_cancelled', - 'max_output_tokens', - 'content_filter', - ] - ], - Field( - description='The reason the Response did not complete. For a `cancelled` Response, one of `turn_detected` (the server VAD detected a new start of speech) or `client_cancelled` (the client sent a cancel event). For an `incomplete` Response, one of `max_output_tokens` or `content_filter` (the server-side safety filter activated and cut off the response).\n' - ), - ] = None - error: Annotated[ - Optional[Error6], - Field( - description='A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n' - ), - ] = None - - -class InputTokenDetails1(BaseModel): - cached_tokens: Annotated[ - Optional[int], - Field( - description='The number of cached tokens used as input for the Response.' - ), - ] = None - text_tokens: Annotated[ - Optional[int], - Field(description='The number of text tokens used as input for the Response.'), - ] = None - image_tokens: Annotated[ - Optional[int], - Field(description='The number of image tokens used as input for the Response.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='The number of audio tokens used as input for the Response.'), - ] = None - cached_tokens_details: Annotated[ - Optional[CachedTokensDetails], - Field( - description='Details about the cached tokens used as input for the Response.' - ), - ] = None - - -class Usage4(BaseModel): - total_tokens: Annotated[ - Optional[int], - Field( - description='The total number of tokens in the Response including input and output \ntext and audio tokens.\n' - ), - ] = None - input_tokens: Annotated[ - Optional[int], - Field( - description='The number of input tokens used in the Response, including text and \naudio tokens.\n' - ), - ] = None - output_tokens: Annotated[ - Optional[int], - Field( - description='The number of output tokens sent in the Response, including text and \naudio tokens.\n' - ), - ] = None - input_token_details: Annotated[ - Optional[InputTokenDetails1], - Field( - description='Details about the input tokens used in the Response. Cached tokens are tokens from previous turns in the conversation that are included as context for the current response. Cached tokens here are counted as a subset of input tokens, meaning input tokens will include cached and uncached tokens.' - ), - ] = None - output_token_details: Annotated[ - Optional[OutputTokenDetails], - Field(description='Details about the output tokens used in the Response.'), - ] = None - - -class Conversation1(BaseModel): - id: Annotated[ - Optional[str], Field(description='The unique ID of the conversation.') - ] = None - object: Annotated[ - Literal['realtime.conversation'], - Field(description='The object type, must be `realtime.conversation`.'), - ] = 'realtime.conversation' - - -class RealtimeServerEventConversationCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.created'], - Field(description='The event type, must be `conversation.created`.'), - ] - conversation: Annotated[ - Conversation1, Field(description='The conversation resource.') - ] - - -class RealtimeServerEventConversationItemDeleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.deleted'], - Field(description='The event type, must be `conversation.item.deleted`.'), - ] - item_id: Annotated[str, Field(description='The ID of the item that was deleted.')] - - -class RealtimeServerEventConversationItemInputAudioTranscriptionDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.delta'], - Field( - description='The event type, must be `conversation.item.input_audio_transcription.delta`.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item containing the audio that is being transcribed.' - ), - ] - content_index: Annotated[ - Optional[int], - Field(description="The index of the content part in the item's content array."), - ] = None - delta: Annotated[Optional[str], Field(description='The text delta.')] = None - logprobs: Optional[List[LogProbProperties]] = None - - -class Error7(BaseModel): - type: Annotated[Optional[str], Field(description='The type of error.')] = None - code: Annotated[Optional[str], Field(description='Error code, if any.')] = None - message: Annotated[ - Optional[str], Field(description='A human-readable error message.') - ] = None - param: Annotated[ - Optional[str], Field(description='Parameter related to the error, if any.') - ] = None - - -class RealtimeServerEventConversationItemInputAudioTranscriptionFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['RealtimeServerEventConversationItemInputAudioTranscriptionFailed'], - Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.failed`.\n' - ), - ] - item_id: Annotated[str, Field(description='The ID of the user message item.')] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - error: Annotated[Error7, Field(description='Details of the transcription error.')] - - -class RealtimeServerEventConversationItemInputAudioTranscriptionSegment(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.segment'], - Field( - description='The event type, must be `conversation.item.input_audio_transcription.segment`.' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the item containing the input audio content.') - ] - content_index: Annotated[ - int, - Field(description='The index of the input audio content part within the item.'), - ] - text: Annotated[str, Field(description='The text for this segment.')] - id: Annotated[str, Field(description='The segment identifier.')] - speaker: Annotated[ - str, Field(description='The detected speaker label for this segment.') - ] - start: Annotated[float, Field(description='Start time of the segment in seconds.')] - end: Annotated[float, Field(description='End time of the segment in seconds.')] - - -class RealtimeServerEventConversationItemTruncated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.truncated'], - Field(description='The event type, must be `conversation.item.truncated`.'), - ] - item_id: Annotated[ - str, - Field(description='The ID of the assistant message item that was truncated.'), - ] - content_index: Annotated[ - int, Field(description='The index of the content part that was truncated.') - ] - audio_end_ms: Annotated[ - int, - Field( - description='The duration up to which the audio was truncated, in milliseconds.\n' - ), - ] - - -class Error8(BaseModel): - type: Annotated[ - str, - Field( - description='The type of error (e.g., "invalid_request_error", "server_error").\n' - ), - ] - code: Optional[str] = None - message: Annotated[str, Field(description='A human-readable error message.')] - param: Optional[str] = None - event_id: Optional[str] = None - - -class RealtimeServerEventError(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['error'], Field(description='The event type, must be `error`.') - ] - error: Annotated[Error8, Field(description='Details of the error.')] - - -class RealtimeServerEventInputAudioBufferCleared(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.cleared'], - Field(description='The event type, must be `input_audio_buffer.cleared`.'), - ] - - -class RealtimeServerEventInputAudioBufferCommitted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.committed'], - Field(description='The event type, must be `input_audio_buffer.committed`.'), - ] - previous_item_id: Optional[str] = None - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeServerEventInputAudioBufferSpeechStarted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.speech_started'], - Field( - description='The event type, must be `input_audio_buffer.speech_started`.' - ), - ] - audio_start_ms: Annotated[ - int, - Field( - description='Milliseconds from the start of all audio written to the buffer during the \nsession when speech was first detected. This will correspond to the \nbeginning of audio sent to the model, and thus includes the \n`prefix_padding_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the user message item that will be created when speech stops.\n' - ), - ] - - -class RealtimeServerEventInputAudioBufferSpeechStopped(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.speech_stopped'], - Field( - description='The event type, must be `input_audio_buffer.speech_stopped`.' - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Milliseconds since the session started when speech stopped. This will \ncorrespond to the end of audio sent to the model, and thus includes the \n`min_silence_duration_ms` configured in the Session.\n' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the user message item that will be created.') - ] - - -class RealtimeServerEventInputAudioBufferTimeoutTriggered(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['input_audio_buffer.timeout_triggered'], - Field( - description='The event type, must be `input_audio_buffer.timeout_triggered`.' - ), - ] - audio_start_ms: Annotated[ - int, - Field( - description='Millisecond offset of audio written to the input audio buffer that was after the playback time of the last model response.' - ), - ] - audio_end_ms: Annotated[ - int, - Field( - description='Millisecond offset of audio written to the input audio buffer at the time the timeout was triggered.' - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the item associated with this segment.') - ] - - -class RealtimeServerEventMCPListToolsCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.completed'], - Field(description='The event type, must be `mcp_list_tools.completed`.'), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeServerEventMCPListToolsFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.failed'], - Field(description='The event type, must be `mcp_list_tools.failed`.'), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeServerEventMCPListToolsInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['mcp_list_tools.in_progress'], - Field(description='The event type, must be `mcp_list_tools.in_progress`.'), - ] - item_id: Annotated[str, Field(description='The ID of the MCP list tools item.')] - - -class RealtimeServerEventOutputAudioBufferCleared(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['output_audio_buffer.cleared'], - Field(description='The event type, must be `output_audio_buffer.cleared`.'), - ] - response_id: Annotated[ - str, Field(description='The unique ID of the response that produced the audio.') - ] - - -class RealtimeServerEventOutputAudioBufferStarted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['output_audio_buffer.started'], - Field(description='The event type, must be `output_audio_buffer.started`.'), - ] - response_id: Annotated[ - str, Field(description='The unique ID of the response that produced the audio.') - ] - - -class RealtimeServerEventOutputAudioBufferStopped(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['output_audio_buffer.stopped'], - Field(description='The event type, must be `output_audio_buffer.stopped`.'), - ] - response_id: Annotated[ - str, Field(description='The unique ID of the response that produced the audio.') - ] - - -class RealtimeServerEventRateLimitsUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['rate_limits.updated'], - Field(description='The event type, must be `rate_limits.updated`.'), - ] - rate_limits: Annotated[ - List[RateLimit], Field(description='List of rate limit information.') - ] - - -class RealtimeServerEventResponseAudioDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio.delta'], - Field(description='The event type, must be `response.output_audio.delta`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='Base64-encoded audio data delta.')] - - -class RealtimeServerEventResponseAudioDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio.done'], - Field(description='The event type, must be `response.output_audio.done`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - - -class RealtimeServerEventResponseAudioTranscriptDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio_transcript.delta'], - Field( - description='The event type, must be `response.output_audio_transcript.delta`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The transcript delta.')] - - -class RealtimeServerEventResponseAudioTranscriptDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_audio_transcript.done'], - Field( - description='The event type, must be `response.output_audio_transcript.done`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - transcript: Annotated[str, Field(description='The final transcript of the audio.')] - - -class RealtimeServerEventResponseContentPartAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.content_part.added'], - Field(description='The event type, must be `response.content_part.added`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[ - str, - Field(description='The ID of the item to which the content part was added.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that was added.')] - - -class RealtimeServerEventResponseContentPartDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.content_part.done'], - Field(description='The event type, must be `response.content_part.done`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - part: Annotated[Part, Field(description='The content part that is done.')] - - -class RealtimeServerEventResponseFunctionCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.function_call_arguments.delta'], - Field( - description='The event type, must be `response.function_call_arguments.delta`.\n' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - delta: Annotated[str, Field(description='The arguments delta as a JSON string.')] - - -class RealtimeServerEventResponseFunctionCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.function_call_arguments.done'], - Field( - description='The event type, must be `response.function_call_arguments.done`.\n' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the function call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - call_id: Annotated[str, Field(description='The ID of the function call.')] - arguments: Annotated[ - str, Field(description='The final arguments as a JSON string.') - ] - - -class RealtimeServerEventResponseMCPCallArgumentsDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call_arguments.delta'], - Field( - description='The event type, must be `response.mcp_call_arguments.delta`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - delta: Annotated[str, Field(description='The JSON-encoded arguments delta.')] - obfuscation: Optional[str] = None - - -class RealtimeServerEventResponseMCPCallArgumentsDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call_arguments.done'], - Field( - description='The event type, must be `response.mcp_call_arguments.done`.' - ), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - arguments: Annotated[ - str, Field(description='The final JSON-encoded arguments string.') - ] - - -class RealtimeServerEventResponseMCPCallCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.completed'], - Field(description='The event type, must be `response.mcp_call.completed`.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeServerEventResponseMCPCallFailed(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.failed'], - Field(description='The event type, must be `response.mcp_call.failed`.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeServerEventResponseMCPCallInProgress(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.mcp_call.in_progress'], - Field(description='The event type, must be `response.mcp_call.in_progress`.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - item_id: Annotated[str, Field(description='The ID of the MCP tool call item.')] - - -class RealtimeServerEventResponseTextDelta(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_text.delta'], - Field(description='The event type, must be `response.output_text.delta`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - delta: Annotated[str, Field(description='The text delta.')] - - -class RealtimeServerEventResponseTextDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_text.done'], - Field(description='The event type, must be `response.output_text.done`.'), - ] - response_id: Annotated[str, Field(description='The ID of the response.')] - item_id: Annotated[str, Field(description='The ID of the item.')] - output_index: Annotated[ - int, Field(description='The index of the output item in the response.') - ] - content_index: Annotated[ - int, - Field(description="The index of the content part in the item's content array."), - ] - text: Annotated[str, Field(description='The final text content.')] - - -class InputAudioNoiseReduction(BaseModel): - type: Optional[NoiseReductionType] = None - - -class Tracing(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n' - ), - ] = None - - -class ClientSecret(BaseModel): - value: Annotated[ - str, - Field( - description='Ephemeral key usable in client environments to authenticate connections\nto the Realtime API. Use this in client-side environments rather than\na standard API token, which should only be used server-side.\n' - ), - ] - expires_at: Annotated[ - int, - Field( - description='Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n' - ), - ] - - -class InputAudioTranscription(BaseModel): - model: Annotated[ - Optional[str], Field(description='The model to use for transcription.\n') - ] = None - - -class TurnDetection(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class Tool2(BaseModel): - type: Annotated[ - Optional[Literal['function']], - Field(description='The type of the tool, i.e. `function`.'), - ] = None - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - description: Annotated[ - Optional[str], - Field( - description='The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n' - ), - ] = None - parameters: Annotated[ - Optional[Dict[str, Any]], - Field(description='Parameters of the function in JSON Schema.'), - ] = None - - -class NoiseReduction(BaseModel): - type: Optional[NoiseReductionType] = None - - -class Tracing2(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n' - ), - ] = None - - -class TurnDetection1(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Optional[float] = None - prefix_padding_ms: Optional[int] = None - silence_duration_ms: Optional[int] = None - - -class Input6(BaseModel): - format: Optional[RealtimeAudioFormats] = None - transcription: Annotated[ - Optional[AudioTranscription], - Field(description='Configuration for input audio transcription.\n'), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], - Field(description='Configuration for input audio noise reduction.\n'), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection1], - Field(description='Configuration for turn detection.\n'), - ] = None - - -class Tracing3(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n' - ), - ] = None - - -class TurnDetection2(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class ClientSecret1(BaseModel): - value: Annotated[ - str, - Field( - description='Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side.\n' - ), - ] - expires_at: Annotated[ - int, - Field( - description='Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n' - ), - ] - - -class Tracing4(BaseModel): - workflow_name: Annotated[ - Optional[str], - Field( - description='The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n' - ), - ] = None - group_id: Annotated[ - Optional[str], - Field( - description='The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n' - ), - ] = None - metadata: Annotated[ - Optional[Dict[str, Any]], - Field( - description='The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n' - ), - ] = None - - -class TurnDetection3(BaseModel): - type: Annotated[ - Optional[Literal['server_vad']], - Field( - description='Type of turn detection. Only `server_vad` is currently supported for transcription sessions.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class RealtimeTranscriptionSessionCreateRequest(BaseModel): - turn_detection: Annotated[ - Optional[TurnDetection3], - Field( - description='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.\n' - ), - ] = None - input_audio_noise_reduction: Annotated[ - Optional[InputAudioNoiseReduction], - Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' - ), - ] = None - input_audio_format: Annotated[ - Literal['pcm16', 'g711_ulaw', 'g711_alaw'], - Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n' - ), - ] = 'pcm16' - input_audio_transcription: Annotated[ - Optional[AudioTranscription], - Field( - description='Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n' - ), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='The set of items to include in the transcription. Current available items are:\n`item.input_audio_transcription.logprobs`\n' - ), - ] = None - - -class ClientSecret2(BaseModel): - value: Annotated[ - str, - Field( - description='Ephemeral key usable in client environments to authenticate connections\nto the Realtime API. Use this in client-side environments rather than\na standard API token, which should only be used server-side.\n' - ), - ] - expires_at: Annotated[ - int, - Field( - description='Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n' - ), - ] - - -class TurnDetection4(BaseModel): - type: Annotated[ - Optional[str], - Field( - description='Type of turn detection, only `server_vad` is currently supported.\n' - ), - ] = None - threshold: Annotated[ - Optional[float], - Field( - description='Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - - -class RealtimeTranscriptionSessionCreateResponse(BaseModel): - client_secret: Annotated[ - ClientSecret2, - Field( - description='Ephemeral key returned by the API. Only present when the session is\ncreated on the server via REST API.\n' - ), - ] - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' - ), - ] = None - input_audio_format: Annotated[ - Optional[str], - Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' - ), - ] = None - input_audio_transcription: Annotated[ - Optional[AudioTranscription], - Field(description='Configuration of the transcription model.\n'), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection4], - Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' - ), - ] = None - - -class Input9(BaseModel): - format: Optional[RealtimeAudioFormats] = None - transcription: Annotated[ - Optional[AudioTranscription], - Field(description='Configuration of the transcription model.\n'), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], - Field(description='Configuration for input audio noise reduction.\n'), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection4], - Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' - ), - ] = None - - -class Audio9(BaseModel): - input: Optional[Input9] = None - - -class RealtimeTranscriptionSessionCreateResponseGA(BaseModel): - type: Annotated[ - Literal['RealtimeTranscriptionSessionCreateResponseGA'], - Field( - description='The type of session. Always `transcription` for transcription sessions.\n' - ), - ] - id: Annotated[ - str, - Field( - description='Unique identifier for the session that looks like `sess_1234567890abcdef`.\n' - ), - ] - object: Annotated[ - str, - Field(description='The object type. Always `realtime.transcription_session`.'), - ] - expires_at: Annotated[ - Optional[int], - Field( - description='Expiration timestamp for the session, in seconds since epoch.' - ), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' - ), - ] = None - audio: Annotated[ - Optional[Audio9], - Field(description='Configuration for input audio for the session.\n'), - ] = None - - -class TokenLimits(BaseModel): - post_instructions: Annotated[ - Optional[int], - Field( - description="Maximum tokens allowed in the conversation after instructions (which including tool definitions). For example, setting this to 5,000 would mean that truncation would occur when the conversation exceeds 5,000 tokens after instructions. This cannot be higher than the model's context window size minus the maximum output tokens.", - ge=0, - ), - ] = None - - -class RealtimeTruncation1(BaseModel): - type: Annotated[ - Literal['retention_ratio'], Field(description='Use retention ratio truncation.') - ] - retention_ratio: Annotated[ - float, - Field( - description='Fraction of post-instruction conversation tokens to retain (`0.0` - `1.0`) when the conversation exceeds the input token limit. Setting this to `0.8` means that messages will be dropped until 80% of the maximum allowed tokens are used. This helps reduce the frequency of truncations and improve cache rates.\n', - ge=0.0, - le=1.0, - ), - ] - token_limits: Annotated[ - Optional[TokenLimits], - Field( - description="Optional custom token limits for this truncation strategy. If not provided, the model's default token limits will be used." - ), - ] = None - - -class RealtimeTruncation( - RootModel[Union[Literal['auto', 'disabled'], RealtimeTruncation1]] -): - root: Annotated[ - Union[Literal['auto', 'disabled'], RealtimeTruncation1], - Field( - description="When the number of tokens in a conversation exceeds the model's input token limit, the conversation be truncated, meaning messages (starting from the oldest) will not be included in the model's context. A 32k context model with 4,096 max output tokens can only include 28,224 tokens in the context before truncation occurs.\nClients can configure truncation behavior to truncate with a lower max token limit, which is an effective way to control token usage and cost.\nTruncation will reduce the number of cached tokens on the next turn (busting the cache), since messages are dropped from the beginning of the context. However, clients can also configure truncation to retain messages up to a fraction of the maximum context size, which will reduce the need for future truncations and thus improve the cache rate.\nTruncation can be disabled entirely, which means the server will never truncate but would instead return an error if the conversation exceeds the model's input token limit.\n", - title='Realtime Truncation Controls', - ), - ] - - -class IdleTimeoutMs(RootModel[int]): - root: Annotated[ - int, - Field( - description="Optional timeout after which a model response will be triggered automatically. This is\nuseful for situations in which a long pause from the user is unexpected, such as a phone\ncall. The model will effectively prompt the user to continue the conversation based\non the current context.\n\nThe timeout value will be applied after the last model response's audio has finished playing,\ni.e. it's set to the `response.done` time plus audio playback duration.\n\nAn `input_audio_buffer.timeout_triggered` event (plus events\nassociated with the Response) will be emitted when the timeout is reached.\nIdle timeout is currently only supported for `server_vad` mode.\n", - ge=5000, - le=30000, - ), - ] - - -class RealtimeTurnDetection1(BaseModel): - type: Annotated[ - Literal['server_vad'], - Field( - description='Type of turn detection, `server_vad` to turn on simple Server VAD.\n' - ), - ] - threshold: Annotated[ - Optional[float], - Field( - description='Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n' - ), - ] = None - prefix_padding_ms: Annotated[ - Optional[int], - Field( - description='Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n' - ), - ] = None - silence_duration_ms: Annotated[ - Optional[int], - Field( - description='Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n' - ), - ] = None - create_response: Annotated[ - bool, - Field( - description='Whether or not to automatically generate a response when a VAD stop event occurs.\n' - ), - ] = True - interrupt_response: Annotated[ - bool, - Field( - description='Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n' - ), - ] = True - idle_timeout_ms: Optional[IdleTimeoutMs] = None - - -class RealtimeTurnDetection2(BaseModel): - type: Annotated[ - Literal['semantic_vad'], - Field( - description='Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n' - ), - ] - eagerness: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field( - description='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`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n' - ), - ] = 'auto' - create_response: Annotated[ - bool, - Field( - description='Whether or not to automatically generate a response when a VAD stop event occurs.\n' - ), - ] = True - interrupt_response: Annotated[ - bool, - Field( - description='Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n' - ), - ] = True - - -class RealtimeTurnDetection( - RootModel[Optional[Union[RealtimeTurnDetection1, RealtimeTurnDetection2]]] -): - root: Optional[Union[RealtimeTurnDetection1, RealtimeTurnDetection2]] - - -class ReasoningEffort( - RootModel[Optional[Literal['none', 'minimal', 'low', 'medium', 'high']]] -): - root: Optional[Literal['none', 'minimal', 'low', 'medium', 'high']] - - -class IncompleteDetails1(BaseModel): - reason: Annotated[ - Optional[Literal['max_output_tokens', 'content_filter']], - Field(description='The reason why the response is incomplete.'), - ] = None - - -class ResponseAudioDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioDeltaEvent'], - Field(description='The type of the event. Always `response.audio.delta`.\n'), - ] - sequence_number: Annotated[ - int, - Field(description='A sequence number for this chunk of the stream response.\n'), - ] - delta: Annotated[ - str, Field(description='A chunk of Base64 encoded response audio bytes.\n') - ] - - -class ResponseAudioDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioDoneEvent'], - Field(description='The type of the event. Always `response.audio.done`.\n'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of the delta.\n') - ] - - -class ResponseAudioTranscriptDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioTranscriptDeltaEvent'], - Field( - description='The type of the event. Always `response.audio.transcript.delta`.\n' - ), - ] - delta: Annotated[ - str, Field(description='The partial transcript of the audio response.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseAudioTranscriptDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseAudioTranscriptDoneEvent'], - Field( - description='The type of the event. Always `response.audio.transcript.done`.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseCodeInterpreterCallCodeDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallCodeDeltaEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call_code.delta`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code is being streamed.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - delta: Annotated[ - str, - Field( - description='The partial code snippet being streamed by the code interpreter.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallCodeDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallCodeDoneEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call_code.done`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code is finalized.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - code: Annotated[ - str, Field(description='The final code snippet output by the code interpreter.') - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallCompletedEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call.completed`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code interpreter call is completed.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallInProgressEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call.in_progress`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code interpreter call is in progress.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCodeInterpreterCallInterpretingEvent(BaseModel): - type: Annotated[ - Literal['ResponseCodeInterpreterCallInterpretingEvent'], - Field( - description='The type of the event. Always `response.code_interpreter_call.interpreting`.' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item in the response for which the code interpreter is interpreting code.' - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the code interpreter tool call item.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of this event, used to order streaming events.' - ), - ] - - -class ResponseCustomToolCallInputDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseCustomToolCallInputDeltaEvent'], - Field(description='The event type identifier.'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - output_index: Annotated[ - int, Field(description='The index of the output this delta applies to.') - ] - item_id: Annotated[ - str, - Field( - description='Unique identifier for the API item associated with this event.' - ), - ] - delta: Annotated[ - str, - Field( - description='The incremental input data (delta) for the custom tool call.' - ), - ] - - -class ResponseCustomToolCallInputDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseCustomToolCallInputDoneEvent'], - Field(description='The event type identifier.'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - output_index: Annotated[ - int, Field(description='The index of the output this event applies to.') - ] - item_id: Annotated[ - str, - Field( - description='Unique identifier for the API item associated with this event.' - ), - ] - input: Annotated[ - str, Field(description='The complete input data for the custom tool call.') - ] - - -class ResponseErrorCode( - RootModel[ - Literal[ - 'server_error', - 'rate_limit_exceeded', - 'invalid_prompt', - 'vector_store_timeout', - 'invalid_image', - 'invalid_image_format', - 'invalid_base64_image', - 'invalid_image_url', - 'image_too_large', - 'image_too_small', - 'image_parse_error', - 'image_content_policy_violation', - 'invalid_image_mode', - 'image_file_too_large', - 'unsupported_image_media_type', - 'empty_image_file', - 'failed_to_download_image', - 'image_file_not_found', - ] - ] -): - root: Annotated[ - Literal[ - 'server_error', - 'rate_limit_exceeded', - 'invalid_prompt', - 'vector_store_timeout', - 'invalid_image', - 'invalid_image_format', - 'invalid_base64_image', - 'invalid_image_url', - 'image_too_large', - 'image_too_small', - 'image_parse_error', - 'image_content_policy_violation', - 'invalid_image_mode', - 'image_file_too_large', - 'unsupported_image_media_type', - 'empty_image_file', - 'failed_to_download_image', - 'image_file_not_found', - ], - Field(description='The error code for the response.\n'), - ] - - -class ResponseErrorEvent(BaseModel): - type: Annotated[ - Literal['ResponseErrorEvent'], - Field(description='The type of the event. Always `error`.\n'), - ] - code: Optional[str] = None - message: Annotated[str, Field(description='The error message.\n')] - param: Optional[str] = None - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFileSearchCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseFileSearchCallCompletedEvent'], - Field( - description='The type of the event. Always `response.file_search_call.completed`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the file search call is initiated.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the file search call is initiated.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFileSearchCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseFileSearchCallInProgressEvent'], - Field( - description='The type of the event. Always `response.file_search_call.in_progress`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the file search call is initiated.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the file search call is initiated.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFileSearchCallSearchingEvent(BaseModel): - type: Annotated[ - Literal['ResponseFileSearchCallSearchingEvent'], - Field( - description='The type of the event. Always `response.file_search_call.searching`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the file search call is searching.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the file search call is initiated.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseFormatJsonObject(BaseModel): - type: Annotated[ - Literal['ResponseFormatJsonObject'], - Field( - description='The type of response format being defined. Always `json_object`.' - ), - ] - - -class ResponseFormatJsonSchemaSchema(BaseModel): - pass - model_config = ConfigDict( - extra='allow', - ) - - -class ResponseFormatText(BaseModel): - type: Annotated[ - Literal['ResponseFormatText'], - Field(description='The type of response format being defined. Always `text`.'), - ] - - -class ResponseFormatTextGrammar(BaseModel): - type: Annotated[ - Literal['grammar'], - Field( - description='The type of response format being defined. Always `grammar`.' - ), - ] - grammar: Annotated[ - str, Field(description='The custom grammar for the model to follow.') - ] - - -class ResponseFormatTextPython(BaseModel): - type: Annotated[ - Literal['python'], - Field( - description='The type of response format being defined. Always `python`.' - ), - ] - - -class ResponseFunctionCallArgumentsDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseFunctionCallArgumentsDeltaEvent'], - Field( - description='The type of the event. Always `response.function_call_arguments.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the function-call arguments delta is added to.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the function-call arguments delta is added to.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - delta: Annotated[ - str, Field(description='The function-call arguments delta that is added.\n') - ] - - -class ResponseFunctionCallArgumentsDoneEvent(BaseModel): - type: Literal['ResponseFunctionCallArgumentsDoneEvent'] - item_id: Annotated[str, Field(description='The ID of the item.')] - name: Annotated[str, Field(description='The name of the function that was called.')] - output_index: Annotated[int, Field(description='The index of the output item.')] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - arguments: Annotated[str, Field(description='The function-call arguments.')] - - -class ResponseImageGenCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallCompletedEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.completed'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - - -class ResponseImageGenCallGeneratingEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallGeneratingEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.generating'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the image generation item being processed.' - ), - ] - - -class ResponseImageGenCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallInProgressEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.in_progress'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the image generation item being processed.' - ), - ] - - -class ResponseImageGenCallPartialImageEvent(BaseModel): - type: Annotated[ - Literal['ResponseImageGenCallPartialImageEvent'], - Field( - description="The type of the event. Always 'response.image_generation_call.partial_image'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the image generation item being processed.' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the image generation item being processed.' - ), - ] - partial_image_index: Annotated[ - int, - Field( - description='0-based index for the partial image (backend is 1-based, but this is 0-based for the user).' - ), - ] - partial_image_b64: Annotated[ - str, - Field( - description='Base64-encoded partial image data, suitable for rendering as an image.' - ), - ] - - -class TopLogprob1(BaseModel): - token: Annotated[Optional[str], Field(description='A possible text token.')] = None - logprob: Annotated[ - Optional[float], Field(description='The log probability of this token.') - ] = None - - -class ResponseLogProb(BaseModel): - token: Annotated[str, Field(description='A possible text token.')] - logprob: Annotated[float, Field(description='The log probability of this token.\n')] - top_logprobs: Annotated[ - Optional[List[TopLogprob1]], - Field(description='The log probability of the top 20 most likely tokens.\n'), - ] = None - - -class ResponseMCPCallArgumentsDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallArgumentsDeltaEvent'], - Field( - description="The type of the event. Always 'response.mcp_call_arguments.delta'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the MCP tool call item being processed.' - ), - ] - delta: Annotated[ - str, - Field( - description='A JSON string containing the partial update to the arguments for the MCP tool call.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallArgumentsDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallArgumentsDoneEvent'], - Field( - description="The type of the event. Always 'response.mcp_call_arguments.done'." - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the MCP tool call item being processed.' - ), - ] - arguments: Annotated[ - str, - Field( - description='A JSON string containing the finalized arguments for the MCP tool call.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallCompletedEvent'], - Field( - description="The type of the event. Always 'response.mcp_call.completed'." - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the MCP tool call item that completed.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item that completed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallFailedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallFailedEvent'], - Field(description="The type of the event. Always 'response.mcp_call.failed'."), - ] - item_id: Annotated[ - str, Field(description='The ID of the MCP tool call item that failed.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item that failed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPCallInProgressEvent'], - Field( - description="The type of the event. Always 'response.mcp_call.in_progress'." - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the MCP tool call item being processed.' - ), - ] - - -class ResponseMCPListToolsCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPListToolsCompletedEvent'], - Field( - description="The type of the event. Always 'response.mcp_list_tools.completed'." - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the MCP tool call item that produced this output.' - ), - ] - output_index: Annotated[ - int, Field(description='The index of the output item that was processed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPListToolsFailedEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPListToolsFailedEvent'], - Field( - description="The type of the event. Always 'response.mcp_list_tools.failed'." - ), - ] - item_id: Annotated[ - str, Field(description='The ID of the MCP tool call item that failed.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item that failed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseMCPListToolsInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseMCPListToolsInProgressEvent'], - Field( - description="The type of the event. Always 'response.mcp_list_tools.in_progress'." - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the MCP tool call item that is being processed.'), - ] - output_index: Annotated[ - int, Field(description='The index of the output item that is being processed.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseModalities(RootModel[Optional[List[Literal['text', 'audio']]]]): - root: Optional[List[Literal['text', 'audio']]] - - -class ResponseOutputTextAnnotationAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseOutputTextAnnotationAddedEvent'], - Field( - description="The type of the event. Always 'response.output_text.annotation.added'." - ), - ] - item_id: Annotated[ - str, - Field( - description='The unique identifier of the item to which the annotation is being added.' - ), - ] - output_index: Annotated[ - int, - Field( - description="The index of the output item in the response's output array." - ), - ] - content_index: Annotated[ - int, Field(description='The index of the content part within the output item.') - ] - annotation_index: Annotated[ - int, Field(description='The index of the annotation within the content part.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - annotation: Annotated[ - Dict[str, Any], - Field( - description='The annotation object being added. (See annotation schema for details.)' - ), - ] - - -class Part4(BaseModel): - type: Annotated[ - Literal['summary_text'], - Field(description='The type of the summary part. Always `summary_text`.'), - ] - text: Annotated[str, Field(description='The text of the summary part.')] - - -class ResponseReasoningSummaryPartAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryPartAddedEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_part.added`.\n' - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the item this summary part is associated with.\n'), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary part is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - part: Annotated[Part4, Field(description='The summary part that was added.\n')] - - -class ResponseReasoningSummaryPartDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryPartDoneEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_part.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the item this summary part is associated with.\n'), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary part is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - part: Annotated[Part4, Field(description='The completed summary part.\n')] - - -class ResponseReasoningSummaryTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryTextDeltaEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_text.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item this summary text delta is associated with.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary text delta is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - delta: Annotated[ - str, Field(description='The text delta that was added to the summary.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseReasoningSummaryTextDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningSummaryTextDoneEvent'], - Field( - description='The type of the event. Always `response.reasoning_summary_text.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field(description='The ID of the item this summary text is associated with.\n'), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this summary text is associated with.\n' - ), - ] - summary_index: Annotated[ - int, - Field( - description='The index of the summary part within the reasoning summary.\n' - ), - ] - text: Annotated[ - str, Field(description='The full text of the completed reasoning summary.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseReasoningTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningTextDeltaEvent'], - Field( - description='The type of the event. Always `response.reasoning_text.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item this reasoning text delta is associated with.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this reasoning text delta is associated with.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the reasoning content part this delta is associated with.\n' - ), - ] - delta: Annotated[ - str, - Field(description='The text delta that was added to the reasoning content.\n'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseReasoningTextDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseReasoningTextDoneEvent'], - Field( - description='The type of the event. Always `response.reasoning_text.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the item this reasoning text is associated with.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item this reasoning text is associated with.\n' - ), - ] - content_index: Annotated[ - int, Field(description='The index of the reasoning content part.\n') - ] - text: Annotated[ - str, Field(description='The full text of the completed reasoning content.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseRefusalDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseRefusalDeltaEvent'], - Field(description='The type of the event. Always `response.refusal.delta`.\n'), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the refusal text is added to.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the refusal text is added to.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the refusal text is added to.\n' - ), - ] - delta: Annotated[str, Field(description='The refusal text that is added.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseRefusalDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseRefusalDoneEvent'], - Field(description='The type of the event. Always `response.refusal.done`.\n'), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the refusal text is finalized.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the refusal text is finalized.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the refusal text is finalized.\n' - ), - ] - refusal: Annotated[str, Field(description='The refusal text that is finalized.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - - -class ResponseStreamOptions1(BaseModel): - include_obfuscation: Annotated[ - Optional[bool], - Field( - description='When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n' - ), - ] = None - - -class ResponseStreamOptions(RootModel[Optional[ResponseStreamOptions1]]): - root: Optional[ResponseStreamOptions1] - - -class ResponseTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['ResponseTextDeltaEvent'], - Field( - description='The type of the event. Always `response.output_text.delta`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the text delta was added to.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the text delta was added to.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the text delta was added to.\n' - ), - ] - delta: Annotated[str, Field(description='The text delta that was added.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] - logprobs: Annotated[ - List[ResponseLogProb], - Field(description='The log probabilities of the tokens in the delta.\n'), - ] - - -class ResponseTextDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseTextDoneEvent'], - Field( - description='The type of the event. Always `response.output_text.done`.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='The ID of the output item that the text content is finalized.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the text content is finalized.\n' - ), - ] - content_index: Annotated[ - int, - Field( - description='The index of the content part that the text content is finalized.\n' - ), - ] - text: Annotated[str, Field(description='The text content that is finalized.\n')] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] - logprobs: Annotated[ - List[ResponseLogProb], - Field(description='The log probabilities of the tokens in the delta.\n'), - ] - - -class InputTokensDetails2(BaseModel): - cached_tokens: Annotated[ - int, - Field( - description='The number of tokens that were retrieved from the cache. \n[More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n' - ), - ] - - -class ResponseUsage(BaseModel): - input_tokens: Annotated[int, Field(description='The number of input tokens.')] - input_tokens_details: Annotated[ - InputTokensDetails2, - Field(description='A detailed breakdown of the input tokens.'), - ] - output_tokens: Annotated[int, Field(description='The number of output tokens.')] - output_tokens_details: Annotated[ - OutputTokensDetails, - Field(description='A detailed breakdown of the output tokens.'), - ] - total_tokens: Annotated[int, Field(description='The total number of tokens used.')] - - -class ResponseWebSearchCallCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseWebSearchCallCompletedEvent'], - Field( - description='The type of the event. Always `response.web_search_call.completed`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the web search call is associated with.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='Unique ID for the output item associated with the web search call.\n' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the web search call being processed.' - ), - ] - - -class ResponseWebSearchCallInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseWebSearchCallInProgressEvent'], - Field( - description='The type of the event. Always `response.web_search_call.in_progress`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the web search call is associated with.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='Unique ID for the output item associated with the web search call.\n' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the web search call being processed.' - ), - ] - - -class ResponseWebSearchCallSearchingEvent(BaseModel): - type: Annotated[ - Literal['ResponseWebSearchCallSearchingEvent'], - Field( - description='The type of the event. Always `response.web_search_call.searching`.\n' - ), - ] - output_index: Annotated[ - int, - Field( - description='The index of the output item that the web search call is associated with.\n' - ), - ] - item_id: Annotated[ - str, - Field( - description='Unique ID for the output item associated with the web search call.\n' - ), - ] - sequence_number: Annotated[ - int, - Field( - description='The sequence number of the web search call being processed.' - ), - ] - - -class Role(BaseModel): - object: Annotated[Literal['role'], Field(description='Always `role`.')] - id: Annotated[str, Field(description='Identifier for the role.')] - name: Annotated[str, Field(description='Unique name for the role.')] - description: Annotated[ - Optional[str], Field(description='Optional description of the role.') - ] = None - permissions: Annotated[ - List[str], Field(description='Permissions granted by the role.') - ] - resource_type: Annotated[ - str, - Field( - description='Resource type the role is bound to (for example `api.organization` or `api.project`).' - ), - ] - predefined_role: Annotated[ - bool, Field(description='Whether the role is predefined and managed by OpenAI.') - ] - - -class RoleDeletedResource(BaseModel): - object: Annotated[ - Literal['role.deleted'], Field(description='Always `role.deleted`.') - ] - id: Annotated[str, Field(description='Identifier of the deleted role.')] - deleted: Annotated[bool, Field(description='Whether the role was deleted.')] - - -class RoleListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[AssignedRoleDetails], - Field(description='Role assignments returned in the current page.'), - ] - has_more: Annotated[ - bool, - Field( - description='Whether additional assignments are available when paginating.' - ), - ] - next: Annotated[ - Optional[str], - Field( - description='Cursor to fetch the next page of results, or `null` when there are no more assignments.' - ), - ] = None - - -class RunCompletionUsage1(BaseModel): - completion_tokens: Annotated[ - int, - Field( - description='Number of completion tokens used over the course of the run.' - ), - ] - prompt_tokens: Annotated[ - int, - Field(description='Number of prompt tokens used over the course of the run.'), - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (prompt + completion).') - ] - - -class RunCompletionUsage(RootModel[Optional[RunCompletionUsage1]]): - root: Optional[RunCompletionUsage1] - - -class Errors1(BaseModel): - formula_parse_error: bool - sample_parse_error: bool - truncated_observation_error: bool - unresponsive_reward_error: bool - invalid_variable_error: bool - other_error: bool - python_grader_server_error: bool - python_grader_server_error_type: Optional[str] = None - python_grader_runtime_error: bool - python_grader_runtime_error_details: Optional[str] = None - model_grader_server_error: bool - model_grader_refusal_error: bool - model_grader_parse_error: bool - model_grader_server_error_details: Optional[str] = None - - -class Metadata1(BaseModel): - name: str - type: str - errors: Errors1 - execution_time: float - scores: Dict[str, Any] - token_usage: Optional[int] = None - sampled_model_name: Optional[str] = None - - -class RunGraderResponse(BaseModel): - reward: float - metadata: Metadata1 - sub_rewards: Dict[str, Any] - model_grader_token_usage_per_model: Dict[str, Any] - - -class LastError(BaseModel): - code: Annotated[ - Literal['server_error', 'rate_limit_exceeded', 'invalid_prompt'], - Field( - description='One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.' - ), - ] - message: Annotated[ - str, Field(description='A human-readable description of the error.') - ] - - -class IncompleteDetails2(BaseModel): - reason: Annotated[ - Optional[Literal['max_completion_tokens', 'max_prompt_tokens']], - Field( - description='The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run.' - ), - ] = None - - -class RunStepCompletionUsage1(BaseModel): - completion_tokens: Annotated[ - int, - Field( - description='Number of completion tokens used over the course of the run step.' - ), - ] - prompt_tokens: Annotated[ - int, - Field( - description='Number of prompt tokens used over the course of the run step.' - ), - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (prompt + completion).') - ] - - -class RunStepCompletionUsage(RootModel[Optional[RunStepCompletionUsage1]]): - root: Optional[RunStepCompletionUsage1] - - -class MessageCreation(BaseModel): - message_id: Annotated[ - Optional[str], - Field(description='The ID of the message that was created by this run step.'), - ] = None - - -class RunStepDeltaStepDetailsMessageCreationObject(BaseModel): - type: Annotated[ - Literal['RunStepDeltaStepDetailsMessageCreationObject'], - Field(description='Always `message_creation`.'), - ] - message_creation: Optional[MessageCreation] = None - - -class Image2(BaseModel): - file_id: Annotated[ - Optional[str], - Field( - description='The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.' - ), - ] = None - - -class RunStepDeltaStepDetailsToolCallsCodeOutputImageObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the output in the outputs array.') - ] - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsCodeOutputImageObject'], - Field(description='Always `image`.'), - ] - image: Optional[Image2] = None - - -class RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the output in the outputs array.') - ] - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject'], - Field(description='Always `logs`.'), - ] - logs: Annotated[ - Optional[str], - Field(description='The text output from the Code Interpreter tool call.'), - ] = None - - -class RunStepDeltaStepDetailsToolCallsFileSearchObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the tool call in the tool calls array.') - ] - id: Annotated[ - Optional[str], Field(description='The ID of the tool call object.') - ] = None - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsFileSearchObject'], - Field( - description='The type of tool call. This is always going to be `file_search` for this type of tool call.' - ), - ] - file_search: Annotated[ - Dict[str, Any], - Field(description='For now, this is always going to be an empty object.'), - ] - - -class Function4(BaseModel): - name: Annotated[Optional[str], Field(description='The name of the function.')] = ( - None - ) - arguments: Annotated[ - Optional[str], Field(description='The arguments passed to the function.') - ] = None - output: Optional[str] = None - - -class RunStepDeltaStepDetailsToolCallsFunctionObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the tool call in the tool calls array.') - ] - id: Annotated[ - Optional[str], Field(description='The ID of the tool call object.') - ] = None - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsFunctionObject'], - Field( - description='The type of tool call. This is always going to be `function` for this type of tool call.' - ), - ] - function: Annotated[ - Optional[Function4], - Field(description='The definition of the function that was called.'), - ] = None - - -class MessageCreation1(BaseModel): - message_id: Annotated[ - str, - Field(description='The ID of the message that was created by this run step.'), - ] - - -class RunStepDetailsMessageCreationObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsMessageCreationObject'], - Field(description='Always `message_creation`.'), - ] - message_creation: MessageCreation1 - - -class Image3(BaseModel): - file_id: Annotated[ - str, - Field( - description='The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.' - ), - ] - - -class RunStepDetailsToolCallsCodeOutputImageObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsToolCallsCodeOutputImageObject'], - Field(description='Always `image`.'), - ] - image: Image3 - - -class RunStepDetailsToolCallsCodeOutputLogsObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsToolCallsCodeOutputLogsObject'], - Field(description='Always `logs`.'), - ] - logs: Annotated[ - str, Field(description='The text output from the Code Interpreter tool call.') - ] - - -class RunStepDetailsToolCallsFileSearchRankingOptionsObject(BaseModel): - ranker: FileSearchRanker - score_threshold: Annotated[ - float, - Field( - description='The score threshold for the file search. All values must be a floating point number between 0 and 1.', - ge=0.0, - le=1.0, - ), - ] - - -class ContentItem5(BaseModel): - type: Annotated[ - Optional[Literal['text']], Field(description='The type of the content.') - ] = None - text: Annotated[ - Optional[str], Field(description='The text content of the file.') - ] = None - - -class RunStepDetailsToolCallsFileSearchResultObject(BaseModel): - file_id: Annotated[ - str, Field(description='The ID of the file that result was found in.') - ] - file_name: Annotated[ - str, Field(description='The name of the file that result was found in.') - ] - score: Annotated[ - float, - Field( - description='The score of the result. All values must be a floating point number between 0 and 1.', - ge=0.0, - le=1.0, - ), - ] - content: Annotated[ - Optional[List[ContentItem5]], - Field( - description='The content of the result that was found. The content is only included if requested via the include query parameter.' - ), - ] = None - - -class Function5(BaseModel): - name: Annotated[str, Field(description='The name of the function.')] - arguments: Annotated[ - str, Field(description='The arguments passed to the function.') - ] - output: Optional[str] = None - - -class RunStepDetailsToolCallsFunctionObject(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call object.')] - type: Annotated[ - Literal['RunStepDetailsToolCallsFunctionObject'], - Field( - description='The type of tool call. This is always going to be `function` for this type of tool call.' - ), - ] - function: Annotated[ - Function5, Field(description='The definition of the function that was called.') - ] - - -class LastError1(BaseModel): - code: Annotated[ - Literal['server_error', 'rate_limit_exceeded'], - Field(description='One of `server_error` or `rate_limit_exceeded`.'), - ] - message: Annotated[ - str, Field(description='A human-readable description of the error.') - ] - - -class Function6(BaseModel): - name: Annotated[str, Field(description='The name of the function.')] - arguments: Annotated[ - str, - Field( - description='The arguments that the model expects you to pass to the function.' - ), - ] - - -class RunToolCallObject(BaseModel): - id: Annotated[ - str, - Field( - description='The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint.' - ), - ] - type: Annotated[ - Literal['function'], - Field( - description='The type of tool call the output is required for. For now, this is always `function`.' - ), - ] - function: Annotated[Function6, Field(description='The function definition.')] - - -class Screenshot(BaseModel): - type: Annotated[ - Literal['Screenshot'], - Field( - description='Specifies the event type. For a screenshot action, this property is \nalways set to `screenshot`.\n' - ), - ] - - -class Scroll(BaseModel): - type: Annotated[ - Literal['Scroll'], - Field( - description='Specifies the event type. For a scroll action, this property is \nalways set to `scroll`.\n' - ), - ] - x: Annotated[ - int, Field(description='The x-coordinate where the scroll occurred.\n') - ] - y: Annotated[ - int, Field(description='The y-coordinate where the scroll occurred.\n') - ] - scroll_x: Annotated[int, Field(description='The horizontal scroll distance.\n')] - scroll_y: Annotated[int, Field(description='The vertical scroll distance.\n')] - - -class ServiceTier( - RootModel[Optional[Literal['auto', 'default', 'flex', 'scale', 'priority']]] -): - root: Optional[Literal['auto', 'default', 'flex', 'scale', 'priority']] - - -class SpeechAudioDeltaEvent(BaseModel): - type: Annotated[ - Literal['SpeechAudioDeltaEvent'], - Field(description='The type of the event. Always `speech.audio.delta`.\n'), - ] - audio: Annotated[str, Field(description='A chunk of Base64-encoded audio data.\n')] - - -class Usage5(BaseModel): - input_tokens: Annotated[ - int, Field(description='Number of input tokens in the prompt.') - ] - output_tokens: Annotated[ - int, Field(description='Number of output tokens generated.') - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (input + output).') - ] - - -class SpeechAudioDoneEvent(BaseModel): - type: Annotated[ - Literal['SpeechAudioDoneEvent'], - Field(description='The type of the event. Always `speech.audio.done`.\n'), - ] - usage: Annotated[ - Usage5, Field(description='Token usage statistics for the request.\n') - ] - - -class StaticChunkingStrategy(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - max_chunk_size_tokens: Annotated[ - int, - Field( - description='The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.', - ge=100, - le=4096, - ), - ] - chunk_overlap_tokens: Annotated[ - int, - Field( - description='The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n' - ), - ] - - -class StaticChunkingStrategyRequestParam(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['StaticChunkingStrategyRequestParam'], - Field(description='Always `static`.'), - ] - static: StaticChunkingStrategy - - -class StaticChunkingStrategyResponseParam(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['StaticChunkingStrategyResponseParam'], - Field(description='Always `static`.'), - ] - static: StaticChunkingStrategy - - -class StopConfiguration1(RootModel[Optional[List[str]]]): - root: Annotated[ - Optional[List[str]], - Field( - description='Not supported with latest reasoning models `o3` and `o4-mini`.\n\nUp to 4 sequences where the API will stop generating further tokens. The\nreturned text will not contain the stop sequence.\n', - max_length=4, - min_length=1, - ), - ] = None - - -class StopConfiguration(RootModel[Optional[Union[Optional[str], StopConfiguration1]]]): - root: Annotated[ - Optional[Union[Optional[str], StopConfiguration1]], - Field( - description='Not supported with latest reasoning models `o3` and `o4-mini`.\n\nUp to 4 sequences where the API will stop generating further tokens. The\nreturned text will not contain the stop sequence.\n' - ), - ] = None - - -class ToolOutput(BaseModel): - tool_call_id: Annotated[ - Optional[str], - Field( - description='The ID of the tool call in the `required_action` object within the run object the output is being submitted for.' - ), - ] = None - output: Annotated[ - Optional[str], - Field( - description='The output of the tool call to be submitted to continue the run.' - ), - ] = None - - -class SubmitToolOutputsRunRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - tool_outputs: Annotated[ - List[ToolOutput], - Field(description='A list of tools for which the outputs are being submitted.'), - ] - stream: Optional[bool] = None - - -class TextResponseFormatJsonSchema(BaseModel): - type: Annotated[ - Literal['TextResponseFormatJsonSchema'], - Field( - description='The type of response format being defined. Always `json_schema`.' - ), - ] - description: Annotated[ - Optional[str], - Field( - description='A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n' - ), - ] = None - name: Annotated[ - str, - Field( - description='The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n' - ), - ] - schema_: Annotated[ResponseFormatJsonSchemaSchema, Field(alias='schema')] - strict: Optional[bool] = None - - -class ToolResources6(BaseModel): - code_interpreter: Optional[CodeInterpreter5] = None - file_search: Optional[FileSearch8] = None - - -class ThreadObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['thread'], - Field(description='The object type, which is always `thread`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the thread was created.' - ), - ] - tool_resources: Optional[ToolResources6] = None - metadata: Metadata - - -class ThreadStreamEvent1(BaseModel): - enabled: Annotated[ - Optional[bool], - Field(description='Whether to enable input audio transcription.'), - ] = None - event: Literal['thread.created'] - data: ThreadObject - - -class ThreadStreamEvent(RootModel[ThreadStreamEvent1]): - root: Annotated[ThreadStreamEvent1, Field(discriminator='event')] - - -class ToggleCertificatesRequest(BaseModel): - certificate_ids: Annotated[List[str], Field(max_length=10, min_length=1)] - - -class ToolChoiceAllowed(BaseModel): - type: Annotated[ - Literal['ToolChoiceAllowed'], - Field(description='Allowed tool configuration type. Always `allowed_tools`.'), - ] - mode: Annotated[ - Literal['auto', 'required'], - Field( - description='Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n' - ), - ] - tools: Annotated[ - List[Dict[str, Any]], - Field( - description='A list of tool definitions that the model should be allowed to call.\n\nFor the Responses API, the list of tool definitions might look like:\n```json\n[\n { "type": "function", "name": "get_weather" },\n { "type": "mcp", "server_label": "deepwiki" },\n { "type": "image_generation" }\n]\n```\n' - ), - ] - - -class ToolChoiceCustom(BaseModel): - type: Annotated[ - Literal['ToolChoiceCustom'], - Field(description='For custom tool calling, the type is always `custom`.'), - ] - name: Annotated[str, Field(description='The name of the custom tool to call.')] - - -class ToolChoiceFunction(BaseModel): - type: Annotated[ - Literal['ToolChoiceFunction'], - Field(description='For function calling, the type is always `function`.'), - ] - name: Annotated[str, Field(description='The name of the function to call.')] - - -class ToolChoiceMCP(BaseModel): - type: Annotated[ - Literal['ToolChoiceMCP'], - Field(description='For MCP tools, the type is always `mcp`.'), - ] - server_label: Annotated[ - str, Field(description='The label of the MCP server to use.\n') - ] - name: Optional[str] = None - - -class ToolChoiceOptions(RootModel[Literal['none', 'auto', 'required']]): - root: Annotated[ - Literal['none', 'auto', 'required'], - Field( - description='Controls which (if any) tool is called by the model.\n\n`none` means the model will not call any tool and instead generates a message.\n\n`auto` means the model can pick between generating a message or calling one or\nmore tools.\n\n`required` means the model must call one or more tools.\n', - title='Tool choice mode', - ), - ] - - -class ToolChoiceTypes(BaseModel): - type: Annotated[ - Literal['ToolChoiceTypes'], - Field( - description='The type of hosted tool the model should to use. Learn more about\n[built-in tools](https://platform.openai.com/docs/guides/tools).\n\nAllowed values are:\n- `file_search`\n- `web_search_preview`\n- `computer_use_preview`\n- `code_interpreter`\n- `image_generation`\n' - ), - ] - - -class Logprob1(BaseModel): - token: Annotated[ - Optional[str], - Field(description='The token that was used to generate the log probability.\n'), - ] = None - logprob: Annotated[ - Optional[float], Field(description='The log probability of the token.\n') - ] = None - bytes: Annotated[ - Optional[List[int]], - Field( - description='The bytes that were used to generate the log probability.\n' - ), - ] = None - - -class TranscriptTextDeltaEvent(BaseModel): - type: Annotated[ - Literal['TranscriptTextDeltaEvent'], - Field(description='The type of the event. Always `transcript.text.delta`.\n'), - ] - delta: Annotated[ - str, Field(description='The text delta that was additionally transcribed.\n') - ] - logprobs: Annotated[ - Optional[List[Logprob1]], - Field( - description='The log probabilities of the delta. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n' - ), - ] = None - segment_id: Annotated[ - Optional[str], - Field( - description='Identifier of the diarized segment that this delta belongs to. Only present when using `gpt-4o-transcribe-diarize`.\n' - ), - ] = None - - -class TranscriptTextSegmentEvent(BaseModel): - type: Annotated[ - Literal['TranscriptTextSegmentEvent'], - Field(description='The type of the event. Always `transcript.text.segment`.'), - ] - id: Annotated[str, Field(description='Unique identifier for the segment.')] - start: Annotated[ - float, Field(description='Start timestamp of the segment in seconds.') - ] - end: Annotated[float, Field(description='End timestamp of the segment in seconds.')] - text: Annotated[str, Field(description='Transcript text for this segment.')] - speaker: Annotated[str, Field(description='Speaker label for this segment.')] - - -class TranscriptTextUsageDuration(BaseModel): - type: Annotated[ - Literal['TranscriptTextUsageDuration'], - Field( - description='The type of the usage object. Always `duration` for this variant.' - ), - ] - seconds: Annotated[ - float, Field(description='Duration of the input audio in seconds.') - ] - - -class InputTokenDetails2(BaseModel): - text_tokens: Annotated[ - Optional[int], - Field(description='Number of text tokens billed for this request.'), - ] = None - audio_tokens: Annotated[ - Optional[int], - Field(description='Number of audio tokens billed for this request.'), - ] = None - - -class TranscriptTextUsageTokens(BaseModel): - type: Annotated[ - Literal['TranscriptTextUsageTokens'], - Field( - description='The type of the usage object. Always `tokens` for this variant.' - ), - ] - input_tokens: Annotated[ - int, Field(description='Number of input tokens billed for this request.') - ] - input_token_details: Annotated[ - Optional[InputTokenDetails2], - Field(description='Details about the input tokens billed for this request.'), - ] = None - output_tokens: Annotated[ - int, Field(description='Number of output tokens generated.') - ] - total_tokens: Annotated[ - int, Field(description='Total number of tokens used (input + output).') - ] - - -class TranscriptionDiarizedSegment(BaseModel): - type: Annotated[ - Literal['transcript.text.segment'], - Field( - description='The type of the segment. Always `transcript.text.segment`.\n' - ), - ] - id: Annotated[str, Field(description='Unique identifier for the segment.')] - start: Annotated[ - float, Field(description='Start timestamp of the segment in seconds.') - ] - end: Annotated[float, Field(description='End timestamp of the segment in seconds.')] - text: Annotated[str, Field(description='Transcript text for this segment.')] - speaker: Annotated[ - str, - Field( - description='Speaker label for this segment. When known speakers are provided, the label matches `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, `B`, ...).\n' - ), - ] - - -class TranscriptionInclude(RootModel[Literal['logprobs']]): - root: Literal['logprobs'] - - -class TranscriptionSegment(BaseModel): - id: Annotated[int, Field(description='Unique identifier of the segment.')] - seek: Annotated[int, Field(description='Seek offset of the segment.')] - start: Annotated[float, Field(description='Start time of the segment in seconds.')] - end: Annotated[float, Field(description='End time of the segment in seconds.')] - text: Annotated[str, Field(description='Text content of the segment.')] - tokens: Annotated[ - List[int], Field(description='Array of token IDs for the text content.') - ] - temperature: Annotated[ - float, - Field(description='Temperature parameter used for generating the segment.'), - ] - avg_logprob: Annotated[ - float, - Field( - description='Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.' - ), - ] - compression_ratio: Annotated[ - float, - Field( - description='Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.' - ), - ] - no_speech_prob: Annotated[ - float, - Field( - description='Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent.' - ), - ] - - -class TranscriptionWord(BaseModel): - word: Annotated[str, Field(description='The text content of the word.')] - start: Annotated[float, Field(description='Start time of the word in seconds.')] - end: Annotated[float, Field(description='End time of the word in seconds.')] - - -class LastMessages(RootModel[int]): - root: Annotated[ - int, - Field( - description='The number of most recent messages from the thread when constructing the context for the run.', - ge=1, - ), - ] - - -class TruncationObject(BaseModel): - type: Annotated[ - Literal['auto', 'last_messages'], - Field( - description='The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.' - ), - ] - last_messages: Optional[LastMessages] = None - - -class Type(BaseModel): - type: Annotated[ - Literal['Type'], - Field( - description='Specifies the event type. For a type action, this property is \nalways set to `type`.\n' - ), - ] - text: Annotated[str, Field(description='The text to type.\n')] - - -class UpdateGroupBody(BaseModel): - name: Annotated[ - str, - Field( - description='New display name for the group.', max_length=255, min_length=1 - ), - ] - - -class Upload(BaseModel): - id: Annotated[ - str, - Field( - description='The Upload unique identifier, which can be referenced in API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the Upload was created.' - ), - ] - filename: Annotated[str, Field(description='The name of the file to be uploaded.')] - bytes: Annotated[ - int, Field(description='The intended number of bytes to be uploaded.') - ] - purpose: Annotated[ - str, - Field( - description='The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values.' - ), - ] - status: Annotated[ - Literal['pending', 'completed', 'cancelled', 'expired'], - Field(description='The status of the Upload.'), - ] - expires_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the Upload will expire.' - ), - ] - object: Annotated[ - Literal['upload'], - Field(description='The object type, which is always "upload".'), - ] - file: Optional[OpenAIFile] = None - - -class UploadCertificateRequest(BaseModel): - name: Annotated[ - Optional[str], Field(description='An optional name for the certificate') - ] = None - content: Annotated[str, Field(description='The certificate content in PEM format')] - - -class UploadPart(BaseModel): - id: Annotated[ - str, - Field( - description='The upload Part unique identifier, which can be referenced in API endpoints.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the Part was created.' - ), - ] - upload_id: Annotated[ - str, - Field(description='The ID of the Upload object that this Part was added to.'), - ] - object: Annotated[ - Literal['upload.part'], - Field(description='The object type, which is always `upload.part`.'), - ] - - -class UsageAudioSpeechesResult(BaseModel): - object: Literal['UsageAudioSpeechesResult'] - characters: Annotated[int, Field(description='The number of characters processed.')] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageAudioTranscriptionsResult(BaseModel): - object: Literal['UsageAudioTranscriptionsResult'] - seconds: Annotated[int, Field(description='The number of seconds processed.')] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageCodeInterpreterSessionsResult(BaseModel): - object: Literal['UsageCodeInterpreterSessionsResult'] - num_sessions: Annotated[ - Optional[int], Field(description='The number of code interpreter sessions.') - ] = None - project_id: Optional[str] = None - - -class UsageCompletionsResult(BaseModel): - object: Literal['UsageCompletionsResult'] - input_tokens: Annotated[ - int, - Field( - description='The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens.' - ), - ] - input_cached_tokens: Annotated[ - Optional[int], - Field( - description='The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens.' - ), - ] = None - output_tokens: Annotated[ - int, - Field( - description='The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens.' - ), - ] - input_audio_tokens: Annotated[ - Optional[int], - Field( - description='The aggregated number of audio input tokens used, including cached tokens.' - ), - ] = None - output_audio_tokens: Annotated[ - Optional[int], - Field(description='The aggregated number of audio output tokens used.'), - ] = None - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - batch: Optional[bool] = None - service_tier: Optional[str] = None - - -class UsageEmbeddingsResult(BaseModel): - object: Literal['UsageEmbeddingsResult'] - input_tokens: Annotated[ - int, Field(description='The aggregated number of input tokens used.') - ] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageImagesResult(BaseModel): - object: Literal['UsageImagesResult'] - images: Annotated[int, Field(description='The number of images processed.')] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - source: Optional[str] = None - size: Optional[str] = None - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageModerationsResult(BaseModel): - object: Literal['UsageModerationsResult'] - input_tokens: Annotated[ - int, Field(description='The aggregated number of input tokens used.') - ] - num_model_requests: Annotated[ - int, Field(description='The count of requests made to the model.') - ] - project_id: Optional[str] = None - user_id: Optional[str] = None - api_key_id: Optional[str] = None - model: Optional[str] = None - - -class UsageVectorStoresResult(BaseModel): - object: Literal['UsageVectorStoresResult'] - usage_bytes: Annotated[int, Field(description='The vector stores usage in bytes.')] - project_id: Optional[str] = None - - -class User(BaseModel): - object: Annotated[ - Literal['organization.user'], - Field(description='The object type, which is always `organization.user`'), - ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - name: Annotated[str, Field(description='The name of the user')] - email: Annotated[str, Field(description='The email address of the user')] - role: Annotated[ - Literal['owner', 'reader'], Field(description='`owner` or `reader`') - ] - added_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the user was added.' - ), - ] - - -class UserDeleteResponse(BaseModel): - object: Literal['organization.user.deleted'] - id: str - deleted: bool - - -class UserListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[List[User], Field(description='Users in the current page.')] - has_more: Annotated[ - bool, Field(description='Whether more users are available when paginating.') - ] - next: Annotated[ - Optional[str], - Field( - description='Cursor to fetch the next page of results, or `null` when no further users are available.' - ), - ] = None - - -class UserListResponse(BaseModel): - object: Literal['list'] - data: List[User] - first_id: str - last_id: str - has_more: bool - - -class UserRoleAssignment(BaseModel): - object: Annotated[Literal['user.role'], Field(description='Always `user.role`.')] - user: User - role: Role - - -class UserRoleUpdateRequest(BaseModel): - role: Annotated[ - Literal['owner', 'reader'], Field(description='`owner` or `reader`') - ] - - -class VadConfig(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['server_vad'], - Field( - description='Must be set to `server_vad` to enable manual chunking using server side VAD.' - ), - ] - prefix_padding_ms: Annotated[ - int, - Field( - description='Amount of audio to include before the VAD detected speech (in \nmilliseconds).\n' - ), - ] = 300 - silence_duration_ms: Annotated[ - int, - Field( - description='Duration of silence to detect speech stop (in milliseconds).\nWith shorter values the model will respond more quickly, \nbut may jump in on short pauses from the user.\n' - ), - ] = 200 - threshold: Annotated[ - float, - Field( - description='Sensitivity threshold (0.0 to 1.0) for voice activity detection. A \nhigher threshold will require louder audio to activate the model, and \nthus might perform better in noisy environments.\n' - ), - ] = 0.5 - - -class VectorStoreExpirationAfter(BaseModel): - anchor: Annotated[ - Literal['last_active_at'], - Field( - description='Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.' - ), - ] - days: Annotated[ - int, - Field( - description='The number of days after the anchor time that the vector store will expire.', - ge=1, - le=365, - ), - ] - - -class VectorStoreFileAttributes1(RootModel[str]): - root: Annotated[str, Field(max_length=512)] - - -class VectorStoreFileAttributes( - RootModel[Optional[Dict[str, Union[VectorStoreFileAttributes1, float, bool]]]] -): - root: Optional[Dict[str, Union[VectorStoreFileAttributes1, float, bool]]] - - -class FileCounts(BaseModel): - in_progress: Annotated[ - int, - Field(description='The number of files that are currently being processed.'), - ] - completed: Annotated[ - int, Field(description='The number of files that have been processed.') - ] - failed: Annotated[ - int, Field(description='The number of files that have failed to process.') - ] - cancelled: Annotated[ - int, Field(description='The number of files that where cancelled.') - ] - total: Annotated[int, Field(description='The total number of files.')] - - -class VectorStoreFileBatchObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['vector_store.files_batch'], - Field( - description='The object type, which is always `vector_store.file_batch`.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the vector store files batch was created.' - ), - ] - vector_store_id: Annotated[ - str, - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.' - ), - ] - status: Annotated[ - Literal['in_progress', 'completed', 'cancelled', 'failed'], - Field( - description='The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`.' - ), - ] - file_counts: FileCounts - - -class Datum1(BaseModel): - type: Annotated[ - Optional[str], Field(description='The content type (currently only `"text"`)') - ] = None - text: Annotated[Optional[str], Field(description='The text content')] = None - - -class VectorStoreFileContentResponse(BaseModel): - object: Annotated[ - Literal['vector_store.file_content.page'], - Field( - description='The object type, which is always `vector_store.file_content.page`' - ), - ] - data: Annotated[List[Datum1], Field(description='Parsed content of the file.')] - has_more: Annotated[ - bool, Field(description='Indicates if there are more content pages to fetch.') - ] - next_page: Optional[str] = None - - -class LastError2(BaseModel): - code: Annotated[ - Literal['server_error', 'unsupported_file', 'invalid_file'], - Field( - description='One of `server_error`, `unsupported_file`, or `invalid_file`.' - ), - ] - message: Annotated[ - str, Field(description='A human-readable description of the error.') - ] - - -class FileCounts1(BaseModel): - in_progress: Annotated[ - int, - Field(description='The number of files that are currently being processed.'), - ] - completed: Annotated[ - int, - Field(description='The number of files that have been successfully processed.'), - ] - failed: Annotated[ - int, Field(description='The number of files that have failed to process.') - ] - cancelled: Annotated[ - int, Field(description='The number of files that were cancelled.') - ] - total: Annotated[int, Field(description='The total number of files.')] - - -class VectorStoreObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['vector_store'], - Field(description='The object type, which is always `vector_store`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the vector store was created.' - ), - ] - name: Annotated[str, Field(description='The name of the vector store.')] - usage_bytes: Annotated[ - int, - Field( - description='The total number of bytes used by the files in the vector store.' - ), - ] - file_counts: FileCounts1 - status: Annotated[ - Literal['expired', 'in_progress', 'completed'], - Field( - description='The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use.' - ), - ] - expires_after: Optional[VectorStoreExpirationAfter] = None - expires_at: Optional[int] = None - last_active_at: Optional[int] = None - metadata: Metadata - - -class QueryItem(RootModel[str]): - root: Annotated[ - str, Field(description='A list of queries to search for.', min_length=1) - ] - - -class RankingOptions(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - ranker: Annotated[ - Literal['none', 'auto', 'default-2024-11-15'], - Field( - description='Enable re-ranking; set to `none` to disable, which can help reduce latency.' - ), - ] = 'auto' - score_threshold: Annotated[float, Field(ge=0.0, le=1.0)] = 0 - - -class VectorStoreSearchResultContentObject(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[Literal['text'], Field(description='The type of content.')] - text: Annotated[str, Field(description='The text content returned from search.')] - - -class VectorStoreSearchResultItem(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - file_id: Annotated[str, Field(description='The ID of the vector store file.')] - filename: Annotated[str, Field(description='The name of the vector store file.')] - score: Annotated[ - float, Field(description='The similarity score for the result.', ge=0.0, le=1.0) - ] - attributes: VectorStoreFileAttributes - content: Annotated[ - List[VectorStoreSearchResultContentObject], - Field(description='Content chunks from the file.'), - ] - - -class SearchQueryItem(RootModel[str]): - root: Annotated[ - str, Field(description='The query used for this search.', min_length=1) - ] - - -class VectorStoreSearchResultsPage(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - object: Annotated[ - Literal['vector_store.search_results.page'], - Field( - description='The object type, which is always `vector_store.search_results.page`' - ), - ] - search_query: List[SearchQueryItem] - data: Annotated[ - List[VectorStoreSearchResultItem], - Field(description='The list of search result items.'), - ] - has_more: Annotated[ - bool, Field(description='Indicates if there are more results to fetch.') - ] - next_page: Optional[str] = None - - -class Verbosity(RootModel[Optional[Literal['low', 'medium', 'high']]]): - root: Optional[Literal['low', 'medium', 'high']] - - -class VoiceIdsShared( - RootModel[ - Union[ - str, - Literal[ - 'alloy', - 'ash', - 'ballad', - 'coral', - 'echo', - 'sage', - 'shimmer', - 'verse', - 'marin', - 'cedar', - ], - ] - ] -): - root: Annotated[ - Union[ - str, - Literal[ - 'alloy', - 'ash', - 'ballad', - 'coral', - 'echo', - 'sage', - 'shimmer', - 'verse', - 'marin', - 'cedar', - ], - ], - Field(examples=['ash']), - ] - - -class Wait(BaseModel): - type: Annotated[ - Literal['Wait'], - Field( - description='Specifies the event type. For a wait action, this property is \nalways set to `wait`.\n' - ), - ] - - -class WebSearchActionFind(BaseModel): - type: Annotated[ - Literal['WebSearchActionFind'], Field(description='The action type.\n') - ] - url: Annotated[ - AnyUrl, Field(description='The URL of the page searched for the pattern.\n') - ] - pattern: Annotated[ - str, Field(description='The pattern or text to search for within the page.\n') - ] - - -class WebSearchActionOpenPage(BaseModel): - type: Annotated[ - Literal['WebSearchActionOpenPage'], Field(description='The action type.\n') - ] - url: Annotated[AnyUrl, Field(description='The URL opened by the model.\n')] - - -class Source(BaseModel): - type: Annotated[ - Literal['url'], Field(description='The type of source. Always `url`.\n') - ] - url: Annotated[str, Field(description='The URL of the source.\n')] - - -class WebSearchActionSearch(BaseModel): - type: Annotated[ - Literal['WebSearchActionSearch'], Field(description='The action type.\n') - ] - query: Annotated[str, Field(description='The search query.\n')] - sources: Annotated[ - Optional[List[Source]], - Field( - description='The sources used in the search.\n', title='Web search sources' - ), - ] = None - - -class WebSearchApproximateLocation1(BaseModel): - type: Annotated[ - Literal['approximate'], - Field(description='The type of location approximation. Always `approximate`.'), - ] = 'approximate' - country: Optional[str] = None - region: Optional[str] = None - city: Optional[str] = None - timezone: Optional[str] = None - - -class WebSearchApproximateLocation(RootModel[Optional[WebSearchApproximateLocation1]]): - root: Optional[WebSearchApproximateLocation1] - - -class WebSearchContextSize(RootModel[Literal['low', 'medium', 'high']]): - root: Annotated[ - Literal['low', 'medium', 'high'], - Field( - description='High level guidance for the amount of context window space to use for the \nsearch. One of `low`, `medium`, or `high`. `medium` is the default.\n' - ), - ] - - -class WebSearchLocation(BaseModel): - country: Annotated[ - Optional[str], - Field( - description='The two-letter \n[ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user,\ne.g. `US`.\n' - ), - ] = None - region: Annotated[ - Optional[str], - Field( - description='Free text input for the region of the user, e.g. `California`.\n' - ), - ] = None - city: Annotated[ - Optional[str], - Field( - description='Free text input for the city of the user, e.g. `San Francisco`.\n' - ), - ] = None - timezone: Annotated[ - Optional[str], - Field( - description='The [IANA timezone](https://timeapi.io/documentation/iana-timezones) \nof the user, e.g. `America/Los_Angeles`.\n' - ), - ] = None - - -class Filters1(BaseModel): - allowed_domains: Optional[List[str]] = None - - -class WebSearchTool(BaseModel): - type: Annotated[ - Literal['WebSearchTool'], - Field( - description='The type of the web search tool. One of `web_search` or `web_search_2025_08_26`.' - ), - ] - filters: Optional[Filters1] = None - user_location: Optional[WebSearchApproximateLocation] = None - search_context_size: Annotated[ - Literal['low', 'medium', 'high'], - Field( - description='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.' - ), - ] = 'medium' - - -class WebSearchToolCall(BaseModel): - id: Annotated[ - str, Field(description='The unique ID of the web search tool call.\n') - ] - type: Annotated[ - Literal['WebSearchToolCall'], - Field( - description='The type of the web search tool call. Always `web_search_call`.\n' - ), - ] - status: Annotated[ - Literal['in_progress', 'searching', 'completed', 'failed'], - Field(description='The status of the web search tool call.\n'), - ] - action: Annotated[ - Union[WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind], - Field( - description='An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find).\n', - discriminator='type', - ), - ] - - -class Data7(BaseModel): - id: Annotated[str, Field(description='The unique ID of the batch API request.\n')] - - -class WebhookBatchCancelled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request was cancelled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.cancelled'], - Field(description='The type of the event. Always `batch.cancelled`.\n'), - ] - - -class WebhookBatchCompleted(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request was completed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.completed'], - Field(description='The type of the event. Always `batch.completed`.\n'), - ] - - -class WebhookBatchExpired(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request expired.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.expired'], - Field(description='The type of the event. Always `batch.expired`.\n'), - ] - - -class WebhookBatchFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the batch API request failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data7, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['batch.failed'], - Field(description='The type of the event. Always `batch.failed`.\n'), - ] - - -class Data11(BaseModel): - id: Annotated[str, Field(description='The unique ID of the eval run.\n')] - - -class WebhookEvalRunCanceled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the eval run was canceled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data11, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['eval.run.canceled'], - Field(description='The type of the event. Always `eval.run.canceled`.\n'), - ] - - -class WebhookEvalRunFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the eval run failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data11, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['eval.run.failed'], - Field(description='The type of the event. Always `eval.run.failed`.\n'), - ] - - -class WebhookEvalRunSucceeded(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the eval run succeeded.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data11, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['eval.run.succeeded'], - Field(description='The type of the event. Always `eval.run.succeeded`.\n'), - ] - - -class Data14(BaseModel): - id: Annotated[str, Field(description='The unique ID of the fine-tuning job.\n')] - - -class WebhookFineTuningJobCancelled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the fine-tuning job was cancelled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data14, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['fine_tuning.job.cancelled'], - Field( - description='The type of the event. Always `fine_tuning.job.cancelled`.\n' - ), - ] - - -class WebhookFineTuningJobFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the fine-tuning job failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data14, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['fine_tuning.job.failed'], - Field(description='The type of the event. Always `fine_tuning.job.failed`.\n'), - ] - - -class WebhookFineTuningJobSucceeded(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the fine-tuning job succeeded.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data14, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['fine_tuning.job.succeeded'], - Field( - description='The type of the event. Always `fine_tuning.job.succeeded`.\n' - ), - ] - - -class SipHeader(BaseModel): - name: Annotated[str, Field(description='Name of the SIP Header.\n')] - value: Annotated[str, Field(description='Value of the SIP Header.\n')] - - -class Data17(BaseModel): - call_id: Annotated[str, Field(description='The unique ID of this call.\n')] - sip_headers: Annotated[ - List[SipHeader], Field(description='Headers from the SIP Invite.\n') - ] - - -class WebhookRealtimeCallIncoming(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was completed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data17, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['realtime.call.incoming'], - Field(description='The type of the event. Always `realtime.call.incoming`.\n'), - ] - - -class Data18(BaseModel): - id: Annotated[str, Field(description='The unique ID of the model response.\n')] - - -class WebhookResponseCancelled(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was cancelled.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.cancelled'], - Field(description='The type of the event. Always `response.cancelled`.\n'), - ] - - -class WebhookResponseCompleted(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was completed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.completed'], - Field(description='The type of the event. Always `response.completed`.\n'), - ] - - -class WebhookResponseFailed(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response failed.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.failed'], - Field(description='The type of the event. Always `response.failed`.\n'), - ] - - -class WebhookResponseIncomplete(BaseModel): - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the model response was interrupted.\n' - ), - ] - id: Annotated[str, Field(description='The unique ID of the event.\n')] - data: Annotated[Data18, Field(description='Event data payload.\n')] - object: Annotated[ - Optional[Literal['event']], - Field(description='The object of the event. Always `event`.\n'), - ] = None - type: Annotated[ - Literal['response.incomplete'], - Field(description='The type of the event. Always `response.incomplete`.\n'), - ] - - -class IncludeEnum( - RootModel[ - Literal[ - 'file_search_call.results', - 'web_search_call.results', - 'web_search_call.action.sources', - 'message.input_image.image_url', - 'computer_call_output.output.image_url', - 'code_interpreter_call.outputs', - 'reasoning.encrypted_content', - 'message.output_text.logprobs', - ] - ] -): - root: Annotated[ - Literal[ - 'file_search_call.results', - 'web_search_call.results', - 'web_search_call.action.sources', - 'message.input_image.image_url', - 'computer_call_output.output.image_url', - 'code_interpreter_call.outputs', - 'reasoning.encrypted_content', - 'message.output_text.logprobs', - ], - Field( - description='Specify additional output data to include in the model response. Currently supported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `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).' - ), - ] - - -class MessageStatus(RootModel[Literal['in_progress', 'completed', 'incomplete']]): - root: Literal['in_progress', 'completed', 'incomplete'] - - -class MessageRole( - RootModel[ - Literal[ - 'unknown', - 'user', - 'assistant', - 'system', - 'critic', - 'discriminator', - 'developer', - 'tool', - ] - ] -): - root: Literal[ - 'unknown', - 'user', - 'assistant', - 'system', - 'critic', - 'discriminator', - 'developer', - 'tool', - ] - - -class InputTextContent(BaseModel): - type: Annotated[ - Literal['InputTextContent'], - Field(description='The type of the input item. Always `input_text`.'), - ] - text: Annotated[str, Field(description='The text input to the model.')] - - -class FileCitationBody(BaseModel): - type: Annotated[ - Literal['FileCitationBody'], - Field(description='The type of the file citation. Always `file_citation`.'), - ] - file_id: Annotated[str, Field(description='The ID of the file.')] - index: Annotated[ - int, Field(description='The index of the file in the list of files.') - ] - filename: Annotated[str, Field(description='The filename of the file cited.')] - - -class UrlCitationBody(BaseModel): - type: Annotated[ - Literal['UrlCitationBody'], - Field(description='The type of the URL citation. Always `url_citation`.'), - ] - url: Annotated[str, Field(description='The URL of the web resource.')] - start_index: Annotated[ - int, - Field( - description='The index of the first character of the URL citation in the message.' - ), - ] - end_index: Annotated[ - int, - Field( - description='The index of the last character of the URL citation in the message.' - ), - ] - title: Annotated[str, Field(description='The title of the web resource.')] - - -class ContainerFileCitationBody(BaseModel): - type: Annotated[ - Literal['ContainerFileCitationBody'], - Field( - description='The type of the container file citation. Always `container_file_citation`.' - ), - ] - container_id: Annotated[str, Field(description='The ID of the container file.')] - file_id: Annotated[str, Field(description='The ID of the file.')] - start_index: Annotated[ - int, - Field( - description='The index of the first character of the container file citation in the message.' - ), - ] - end_index: Annotated[ - int, - Field( - description='The index of the last character of the container file citation in the message.' - ), - ] - filename: Annotated[ - str, Field(description='The filename of the container file cited.') - ] - - -class Annotation1( - RootModel[ - Union[FileCitationBody, UrlCitationBody, ContainerFileCitationBody, FilePath] - ] -): - root: Annotated[ - Union[FileCitationBody, UrlCitationBody, ContainerFileCitationBody, FilePath], - Field(discriminator='type'), - ] - - -class TopLogProb(BaseModel): - token: str - logprob: float - bytes: List[int] - - -class LogProb(BaseModel): - token: str - logprob: float - bytes: List[int] - top_logprobs: List[TopLogProb] - - -class OutputTextContent(BaseModel): - type: Annotated[ - Literal['OutputTextContent'], - Field(description='The type of the output text. Always `output_text`.'), - ] - text: Annotated[str, Field(description='The text output from the model.')] - annotations: Annotated[ - List[Annotation1], Field(description='The annotations of the text output.') - ] - logprobs: Optional[List[LogProb]] = None - - -class TextContent(BaseModel): - type: Literal['TextContent'] - text: str - - -class SummaryTextContent(BaseModel): - type: Annotated[ - Literal['SummaryTextContent'], - Field(description='The type of the object. Always `summary_text`.'), - ] - text: Annotated[ - str, - Field(description='A summary of the reasoning output from the model so far.'), - ] - - -class ReasoningTextContent(BaseModel): - type: Annotated[ - Literal['ReasoningTextContent'], - Field(description='The type of the reasoning text. Always `reasoning_text`.'), - ] - text: Annotated[str, Field(description='The reasoning text from the model.')] - - -class RefusalContent(BaseModel): - type: Annotated[ - Literal['RefusalContent'], - Field(description='The type of the refusal. Always `refusal`.'), - ] - refusal: Annotated[ - str, Field(description='The refusal explanation from the model.') - ] - - -class ImageDetail(RootModel[Literal['low', 'high', 'auto']]): - root: Literal['low', 'high', 'auto'] - - -class InputImageContent(BaseModel): - type: Annotated[ - Literal['InputImageContent'], - Field(description='The type of the input item. Always `input_image`.'), - ] - image_url: Optional[str] = None - file_id: Optional[str] = None - detail: Annotated[ - ImageDetail, - Field( - description='The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.' - ), - ] - - -class ComputerScreenshotContent(BaseModel): - type: Annotated[ - Literal['ComputerScreenshotContent'], - Field( - description='Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`.' - ), - ] - image_url: Optional[str] = None - file_id: Optional[str] = None - - -class InputFileContent(BaseModel): - type: Annotated[ - Literal['InputFileContent'], - Field(description='The type of the input item. Always `input_file`.'), - ] - file_id: Optional[str] = None - filename: Annotated[ - Optional[str], - Field(description='The name of the file to be sent to the model.'), - ] = None - file_url: Annotated[ - Optional[str], Field(description='The URL of the file to be sent to the model.') - ] = None - file_data: Annotated[ - Optional[str], - Field(description='The content of the file to be sent to the model.\n'), - ] = None - - -class Content10( - RootModel[ - Union[ - InputTextContent, - OutputTextContent, - TextContent, - SummaryTextContent, - ReasoningTextContent, - RefusalContent, - InputImageContent, - ComputerScreenshotContent, - InputFileContent, - ] - ] -): - root: Annotated[ - Union[ - InputTextContent, - OutputTextContent, - TextContent, - SummaryTextContent, - ReasoningTextContent, - RefusalContent, - InputImageContent, - ComputerScreenshotContent, - InputFileContent, - ], - Field(discriminator='type'), - ] - - -class Message(BaseModel): - type: Annotated[ - Literal['Message'], - Field(description='The type of the message. Always set to `message`.'), - ] - id: Annotated[str, Field(description='The unique ID of the message.')] - status: Annotated[ - MessageStatus, - Field( - description='The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API.' - ), - ] - role: Annotated[ - MessageRole, - Field( - description='The role of the message. One of `unknown`, `user`, `assistant`, `system`, `critic`, `discriminator`, `developer`, or `tool`.' - ), - ] - content: Annotated[List[Content10], Field(description='The content of the message')] - - -class ClickButtonType(RootModel[Literal['left', 'right', 'wheel', 'back', 'forward']]): - root: Literal['left', 'right', 'wheel', 'back', 'forward'] - - -class ClickParam(BaseModel): - type: Annotated[ - Literal['ClickParam'], - Field( - description='Specifies the event type. For a click action, this property is always `click`.' - ), - ] - button: Annotated[ - ClickButtonType, - Field( - description='Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`.' - ), - ] - x: Annotated[int, Field(description='The x-coordinate where the click occurred.')] - y: Annotated[int, Field(description='The y-coordinate where the click occurred.')] - - -class DoubleClickAction(BaseModel): - type: Annotated[ - Literal['DoubleClickAction'], - Field( - description='Specifies the event type. For a double click action, this property is always set to `double_click`.' - ), - ] - x: Annotated[ - int, Field(description='The x-coordinate where the double click occurred.') - ] - y: Annotated[ - int, Field(description='The y-coordinate where the double click occurred.') - ] - - -class DragPoint(BaseModel): - x: Annotated[int, Field(description='The x-coordinate.')] - y: Annotated[int, Field(description='The y-coordinate.')] - - -class KeyPressAction(BaseModel): - type: Annotated[ - Literal['KeyPressAction'], - Field( - description='Specifies the event type. For a keypress action, this property is always set to `keypress`.' - ), - ] - keys: Annotated[ - List[str], - Field( - description='The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key.' - ), - ] - - -class ComputerCallSafetyCheckParam(BaseModel): - id: Annotated[str, Field(description='The ID of the pending safety check.')] - code: Optional[str] = None - message: Optional[str] = None - - -class CodeInterpreterOutputLogs(BaseModel): - type: Annotated[ - Literal['CodeInterpreterOutputLogs'], - Field(description='The type of the output. Always `logs`.'), - ] - logs: Annotated[ - str, Field(description='The logs output from the code interpreter.') - ] - - -class CodeInterpreterOutputImage(BaseModel): - type: Annotated[ - Literal['CodeInterpreterOutputImage'], - Field(description='The type of the output. Always `image`.'), - ] - url: Annotated[ - str, Field(description='The URL of the image output from the code interpreter.') - ] - - -class LocalShellExecAction(BaseModel): - type: Annotated[ - Literal['exec'], - Field(description='The type of the local shell action. Always `exec`.'), - ] - command: Annotated[List[str], Field(description='The command to run.')] - timeout_ms: Optional[int] = None - working_directory: Optional[str] = None - env: Annotated[ - Dict[str, str], - Field(description='Environment variables to set for the command.'), - ] - user: Optional[str] = None - - -class FunctionShellAction(BaseModel): - commands: List[str] - timeout_ms: Optional[int] = None - max_output_length: Optional[int] = None - - -class LocalShellCallStatus( - RootModel[Literal['in_progress', 'completed', 'incomplete']] -): - root: Literal['in_progress', 'completed', 'incomplete'] - - -class FunctionShellCall(BaseModel): - type: Annotated[ - Literal['FunctionShellCall'], - Field(description='The type of the item. Always `shell_call`.'), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call generated by the model.' - ), - ] - action: Annotated[ - FunctionShellAction, - Field( - description='The shell commands and limits that describe how to run the tool call.' - ), - ] - status: Annotated[ - LocalShellCallStatus, - Field( - description='The status of the shell call. One of `in_progress`, `completed`, or `incomplete`.' - ), - ] - created_by: Annotated[ - Optional[str], - Field(description='The ID of the entity that created this tool call.'), - ] = None - - -class FunctionShellCallOutputTimeoutOutcome(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputTimeoutOutcome'], - Field(description='The outcome type. Always `timeout`.'), - ] - - -class FunctionShellCallOutputExitOutcome(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputExitOutcome'], - Field(description='The outcome type. Always `exit`.'), - ] - exit_code: Annotated[int, Field(description='Exit code from the shell process.')] - - -class FunctionShellCallOutputContent(BaseModel): - stdout: str - stderr: str - outcome: Annotated[ - Union[ - FunctionShellCallOutputTimeoutOutcome, FunctionShellCallOutputExitOutcome - ], - Field( - description='Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk.', - discriminator='type', - title='Function shell call outcome', - ), - ] - created_by: Optional[str] = None - - -class FunctionShellCallOutput(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutput'], - Field( - description='The type of the shell call output. Always `shell_call_output`.' - ), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the shell call output. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the shell tool call generated by the model.' - ), - ] - output: Annotated[ - List[FunctionShellCallOutputContent], - Field(description='An array of shell call output contents'), - ] - max_output_length: Optional[int] = None - created_by: Optional[str] = None - - -class ApplyPatchCallStatus(RootModel[Literal['in_progress', 'completed']]): - root: Literal['in_progress', 'completed'] - - -class ApplyPatchCreateFileOperation(BaseModel): - type: Annotated[ - Literal['ApplyPatchCreateFileOperation'], - Field(description='Create a new file with the provided diff.'), - ] - path: Annotated[str, Field(description='Path of the file to create.')] - diff: Annotated[str, Field(description='Diff to apply.')] - - -class ApplyPatchDeleteFileOperation(BaseModel): - type: Annotated[ - Literal['ApplyPatchDeleteFileOperation'], - Field(description='Delete the specified file.'), - ] - path: Annotated[str, Field(description='Path of the file to delete.')] - - -class ApplyPatchUpdateFileOperation(BaseModel): - type: Annotated[ - Literal['ApplyPatchUpdateFileOperation'], - Field(description='Update an existing file with the provided diff.'), - ] - path: Annotated[str, Field(description='Path of the file to update.')] - diff: Annotated[str, Field(description='Diff to apply.')] - - -class ApplyPatchToolCall(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCall'], - Field(description='The type of the item. Always `apply_patch_call`.'), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.' - ), - ] - status: Annotated[ - ApplyPatchCallStatus, - Field( - description='The status of the apply patch tool call. One of `in_progress` or `completed`.' - ), - ] - operation: Annotated[ - Union[ - ApplyPatchCreateFileOperation, - ApplyPatchDeleteFileOperation, - ApplyPatchUpdateFileOperation, - ], - Field( - description='One of the create_file, delete_file, or update_file operations applied via apply_patch.', - discriminator='type', - title='Apply patch operation', - ), - ] - created_by: Annotated[ - Optional[str], - Field(description='The ID of the entity that created this tool call.'), - ] = None - - -class ApplyPatchCallOutputStatus(RootModel[Literal['completed', 'failed']]): - root: Literal['completed', 'failed'] - - -class ApplyPatchToolCallOutput(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCallOutput'], - Field(description='The type of the item. Always `apply_patch_call_output`.'), - ] - id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call output. Populated when this item is returned via API.' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.' - ), - ] - status: Annotated[ - ApplyPatchCallOutputStatus, - Field( - description='The status of the apply patch tool call output. One of `completed` or `failed`.' - ), - ] - output: Optional[str] = None - created_by: Annotated[ - Optional[str], - Field(description='The ID of the entity that created this tool call output.'), - ] = None - - -class MCPToolCallStatus( - RootModel[Literal['in_progress', 'completed', 'incomplete', 'calling', 'failed']] -): - root: Literal['in_progress', 'completed', 'incomplete', 'calling', 'failed'] - - -class DetailEnum(RootModel[Literal['low', 'high', 'auto']]): - root: Literal['low', 'high', 'auto'] - - -class FunctionCallItemStatus( - RootModel[Literal['in_progress', 'completed', 'incomplete']] -): - root: Literal['in_progress', 'completed', 'incomplete'] - - -class ComputerCallOutputItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The ID of the computer tool call that produced the output.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['ComputerCallOutputItemParam'], - Field( - description='The type of the computer tool call output. Always `computer_call_output`.' - ), - ] - output: ComputerScreenshotImage - acknowledged_safety_checks: Optional[List[ComputerCallSafetyCheckParam]] = None - status: Optional[FunctionCallItemStatus] = None - - -class InputTextContentParam(BaseModel): - type: Annotated[ - Literal['InputTextContentParam'], - Field(description='The type of the input item. Always `input_text`.'), - ] - text: Annotated[ - str, Field(description='The text input to the model.', max_length=10485760) - ] - - -class ImageUrl3(RootModel[str]): - root: Annotated[ - str, - Field( - description='The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL.', - max_length=20971520, - ), - ] - - -class InputImageContentParamAutoParam(BaseModel): - type: Annotated[ - Literal['InputImageContentParamAutoParam'], - Field(description='The type of the input item. Always `input_image`.'), - ] - image_url: Optional[ImageUrl3] = None - file_id: Optional[str] = None - detail: Optional[DetailEnum] = None - - -class FileData(RootModel[str]): - root: Annotated[ - str, - Field( - description='The base64-encoded data of the file to be sent to the model.', - max_length=33554432, - ), - ] - - -class InputFileContentParam(BaseModel): - type: Annotated[ - Literal['InputFileContentParam'], - Field(description='The type of the input item. Always `input_file`.'), - ] - file_id: Optional[str] = None - filename: Optional[str] = None - file_data: Optional[FileData] = None - file_url: Optional[str] = None - - -class Output5(RootModel[str]): - root: Annotated[ - str, - Field( - description='A JSON string of the output of the function tool call.', - max_length=10485760, - ), - ] - - -class Output6( - RootModel[ - Union[ - InputTextContentParam, - InputImageContentParamAutoParam, - InputFileContentParam, - ] - ] -): - root: Annotated[ - Union[ - InputTextContentParam, - InputImageContentParamAutoParam, - InputFileContentParam, - ], - Field(discriminator='type'), - ] - - -class FunctionCallOutputItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the function tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['FunctionCallOutputItemParam'], - Field( - description='The type of the function tool call output. Always `function_call_output`.' - ), - ] - output: Annotated[ - Union[Output5, List[Output6]], - Field(description='Text, image, or file output of the function tool call.'), - ] - status: Optional[FunctionCallItemStatus] = None - - -class FunctionShellActionParam(BaseModel): - commands: Annotated[ - List[str], - Field( - description='Ordered shell commands for the execution environment to run.' - ), - ] - timeout_ms: Optional[int] = None - max_output_length: Optional[int] = None - - -class FunctionShellCallItemStatus( - RootModel[Literal['in_progress', 'completed', 'incomplete']] -): - root: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], - Field( - description='Status values reported for function shell tool calls.', - title='Function shell call status', - ), - ] - - -class FunctionShellCallItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['FunctionShellCallItemParam'], - Field(description='The type of the item. Always `function_shell_call`.'), - ] - action: Annotated[ - FunctionShellActionParam, - Field( - description='The shell commands and limits that describe how to run the tool call.' - ), - ] - status: Optional[FunctionShellCallItemStatus] = None - - -class FunctionShellCallOutputTimeoutOutcomeParam(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputTimeoutOutcomeParam'], - Field(description='The outcome type. Always `timeout`.'), - ] - - -class FunctionShellCallOutputExitOutcomeParam(BaseModel): - type: Annotated[ - Literal['FunctionShellCallOutputExitOutcomeParam'], - Field(description='The outcome type. Always `exit`.'), - ] - exit_code: Annotated[ - int, Field(description='The exit code returned by the shell process.') - ] - - -class FunctionShellCallOutputOutcomeParam( - RootModel[ - Union[ - FunctionShellCallOutputTimeoutOutcomeParam, - FunctionShellCallOutputExitOutcomeParam, - ] - ] -): - root: Annotated[ - Union[ - FunctionShellCallOutputTimeoutOutcomeParam, - FunctionShellCallOutputExitOutcomeParam, - ], - Field( - description='The exit or timeout outcome associated with this chunk.', - discriminator='type', - title='Function shell call outcome', - ), - ] - - -class FunctionShellCallOutputContentParam(BaseModel): - stdout: Annotated[ - str, - Field( - description='Captured stdout output for this chunk of the shell call.', - max_length=10485760, - ), - ] - stderr: Annotated[ - str, - Field( - description='Captured stderr output for this chunk of the shell call.', - max_length=10485760, - ), - ] - outcome: Annotated[ - FunctionShellCallOutputOutcomeParam, - Field(description='The exit or timeout outcome associated with this chunk.'), - ] - - -class FunctionShellCallOutputItemParam(BaseModel): - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the function shell tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - type: Annotated[ - Literal['FunctionShellCallOutputItemParam'], - Field(description='The type of the item. Always `function_shell_call_output`.'), - ] - output: Annotated[ - List[FunctionShellCallOutputContentParam], - Field( - description='Captured chunks of stdout and stderr output, along with their associated outcomes.' - ), - ] - max_output_length: Optional[int] = None - - -class ApplyPatchCallStatusParam(RootModel[Literal['in_progress', 'completed']]): - root: Annotated[ - Literal['in_progress', 'completed'], - Field( - description='Status values reported for apply_patch tool calls.', - title='Apply patch call status', - ), - ] - - -class ApplyPatchCreateFileOperationParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchCreateFileOperationParam'], - Field(description='The operation type. Always `create_file`.'), - ] - path: Annotated[ - str, - Field( - description='Path of the file to create relative to the workspace root.', - min_length=1, - ), - ] - diff: Annotated[ - str, - Field( - description='Unified diff content to apply when creating the file.', - max_length=10485760, - ), - ] - - -class ApplyPatchDeleteFileOperationParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchDeleteFileOperationParam'], - Field(description='The operation type. Always `delete_file`.'), - ] - path: Annotated[ - str, - Field( - description='Path of the file to delete relative to the workspace root.', - min_length=1, - ), - ] - - -class ApplyPatchUpdateFileOperationParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchUpdateFileOperationParam'], - Field(description='The operation type. Always `update_file`.'), - ] - path: Annotated[ - str, - Field( - description='Path of the file to update relative to the workspace root.', - min_length=1, - ), - ] - diff: Annotated[ - str, - Field( - description='Unified diff content to apply to the existing file.', - max_length=10485760, - ), - ] - - -class ApplyPatchOperationParam( - RootModel[ - Union[ - ApplyPatchCreateFileOperationParam, - ApplyPatchDeleteFileOperationParam, - ApplyPatchUpdateFileOperationParam, - ] - ] -): - root: Annotated[ - Union[ - ApplyPatchCreateFileOperationParam, - ApplyPatchDeleteFileOperationParam, - ApplyPatchUpdateFileOperationParam, - ], - Field( - description='One of the create_file, delete_file, or update_file operations supplied to the apply_patch tool.', - discriminator='type', - title='Apply patch operation', - ), - ] - - -class ApplyPatchToolCallItemParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCallItemParam'], - Field(description='The type of the item. Always `apply_patch_call`.'), - ] - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - status: Annotated[ - ApplyPatchCallStatusParam, - Field( - description='The status of the apply patch tool call. One of `in_progress` or `completed`.' - ), - ] - operation: Annotated[ - ApplyPatchOperationParam, - Field( - description='The specific create, delete, or update instruction for the apply_patch tool call.' - ), - ] - - -class ApplyPatchCallOutputStatusParam(RootModel[Literal['completed', 'failed']]): - root: Annotated[ - Literal['completed', 'failed'], - Field( - description='Outcome values reported for apply_patch tool call outputs.', - title='Apply patch call output status', - ), - ] - - -class Output7(RootModel[str]): - root: Annotated[ - str, - Field( - description='Optional human-readable log text from the apply patch tool (e.g., patch results or errors).', - max_length=10485760, - ), - ] - - -class ApplyPatchToolCallOutputItemParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolCallOutputItemParam'], - Field(description='The type of the item. Always `apply_patch_call_output`.'), - ] - id: Optional[str] = None - call_id: Annotated[ - str, - Field( - description='The unique ID of the apply patch tool call generated by the model.', - max_length=64, - min_length=1, - ), - ] - status: Annotated[ - ApplyPatchCallOutputStatusParam, - Field( - description='The status of the apply patch tool call output. One of `completed` or `failed`.' - ), - ] - output: Optional[Output7] = None - - -class ItemReferenceParam(BaseModel): - type: Literal['ItemReferenceParam'] - id: Annotated[str, Field(description='The ID of the item to reference.')] - - -class ConversationResource(BaseModel): - id: Annotated[str, Field(description='The unique ID of the conversation.')] - object: Annotated[ - Literal['conversation'], - Field(description='The object type, which is always `conversation`.'), - ] - metadata: Annotated[ - Any, - Field( - description='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.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.' - ), - ] - created_at: Annotated[ - int, - Field( - description='The time at which the conversation was created, measured in seconds since the Unix epoch.' - ), - ] - - -class FunctionTool(BaseModel): - type: Annotated[ - Literal['FunctionTool'], - Field(description='The type of the function tool. Always `function`.'), - ] - name: Annotated[str, Field(description='The name of the function to call.')] - description: Optional[str] = None - parameters: Optional[Dict[str, Any]] = None - strict: Optional[bool] = None - - -class RankerVersionType(RootModel[Literal['auto', 'default-2024-11-15']]): - root: Literal['auto', 'default-2024-11-15'] - - -class HybridSearchOptions(BaseModel): - embedding_weight: Annotated[ - float, - Field( - description='The weight of the embedding in the reciprocal ranking fusion.' - ), - ] - text_weight: Annotated[ - float, - Field(description='The weight of the text in the reciprocal ranking fusion.'), - ] - - -class RankingOptions1(BaseModel): - ranker: Annotated[ - Optional[RankerVersionType], - Field(description='The ranker to use for the file search.'), - ] = None - score_threshold: Annotated[ - Optional[float], - Field( - description='The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results.' - ), - ] = None - hybrid_search: Annotated[ - Optional[HybridSearchOptions], - Field( - description='Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse keyword matches when hybrid search is enabled.' - ), - ] = None - - -class ComputerEnvironment( - RootModel[Literal['windows', 'mac', 'linux', 'ubuntu', 'browser']] -): - root: Literal['windows', 'mac', 'linux', 'ubuntu', 'browser'] - - -class ComputerUsePreviewTool(BaseModel): - type: Annotated[ - Literal['ComputerUsePreviewTool'], - Field( - description='The type of the computer use tool. Always `computer_use_preview`.' - ), - ] - environment: Annotated[ - ComputerEnvironment, - Field(description='The type of computer environment to control.'), - ] - display_width: Annotated[ - int, Field(description='The width of the computer display.') - ] - display_height: Annotated[ - int, Field(description='The height of the computer display.') - ] - - -class ContainerMemoryLimit(RootModel[Literal['1g', '4g', '16g', '64g']]): - root: Literal['1g', '4g', '16g', '64g'] - - -class InputFidelity(RootModel[Literal['high', 'low']]): - root: Annotated[ - Literal['high', 'low'], - Field( - description='Control how much effort the model will exert to match the style and features, especially facial features, of input images. This parameter is only supported for `gpt-image-1`. Unsupported for `gpt-image-1-mini`. Supports `high` and `low`. Defaults to `low`.' - ), - ] - - -class LocalShellToolParam(BaseModel): - type: Annotated[ - Literal['LocalShellToolParam'], - Field(description='The type of the local shell tool. Always `local_shell`.'), - ] - - -class FunctionShellToolParam(BaseModel): - type: Annotated[ - Literal['FunctionShellToolParam'], - Field(description='The type of the shell tool. Always `shell`.'), - ] - - -class CustomTextFormatParam(BaseModel): - type: Annotated[ - Literal['CustomTextFormatParam'], - Field(description='Unconstrained text format. Always `text`.'), - ] - - -class GrammarSyntax1(RootModel[Literal['lark', 'regex']]): - root: Literal['lark', 'regex'] - - -class CustomGrammarFormatParam(BaseModel): - type: Annotated[ - Literal['CustomGrammarFormatParam'], - Field(description='Grammar format. Always `grammar`.'), - ] - syntax: Annotated[ - GrammarSyntax1, - Field( - description='The syntax of the grammar definition. One of `lark` or `regex`.' - ), - ] - definition: Annotated[str, Field(description='The grammar definition.')] - - -class CustomToolParam(BaseModel): - type: Annotated[ - Literal['CustomToolParam'], - Field(description='The type of the custom tool. Always `custom`.'), - ] - name: Annotated[ - str, - Field( - description='The name of the custom tool, used to identify it in tool calls.' - ), - ] - description: Annotated[ - Optional[str], - Field( - description='Optional description of the custom tool, used to provide more context.' - ), - ] = None - format: Annotated[ - Optional[Union[CustomTextFormatParam, CustomGrammarFormatParam]], - Field( - description='The input format for the custom tool. Default is unconstrained text.', - discriminator='type', - ), - ] = None - - -class ApproximateLocation(BaseModel): - type: Annotated[ - Literal['approximate'], - Field(description='The type of location approximation. Always `approximate`.'), - ] - country: Optional[str] = None - region: Optional[str] = None - city: Optional[str] = None - timezone: Optional[str] = None - - -class SearchContextSize(RootModel[Literal['low', 'medium', 'high']]): - root: Literal['low', 'medium', 'high'] - - -class WebSearchPreviewTool(BaseModel): - type: Annotated[ - Literal['WebSearchPreviewTool'], - Field( - description='The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`.' - ), - ] - user_location: Optional[ApproximateLocation] = None - search_context_size: Annotated[ - Optional[SearchContextSize], - Field( - description='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.' - ), - ] = None - - -class ApplyPatchToolParam(BaseModel): - type: Annotated[ - Literal['ApplyPatchToolParam'], - Field(description='The type of the tool. Always `apply_patch`.'), - ] - - -class ImageGenInputUsageDetails(BaseModel): - text_tokens: Annotated[ - int, Field(description='The number of text tokens in the input prompt.') - ] - image_tokens: Annotated[ - int, Field(description='The number of image tokens in the input prompt.') - ] - - -class ImageGenUsage(BaseModel): - input_tokens: Annotated[ - int, - Field( - description='The number of tokens (images and text) in the input prompt.' - ), - ] - total_tokens: Annotated[ - int, - Field( - description='The total number of tokens (images and text) used for the image generation.' - ), - ] - output_tokens: Annotated[ - int, Field(description='The number of output tokens generated by the model.') - ] - input_tokens_details: ImageGenInputUsageDetails - - -class SpecificApplyPatchParam(BaseModel): - type: Annotated[ - Literal['SpecificApplyPatchParam'], - Field(description='The tool to call. Always `apply_patch`.'), - ] - - -class SpecificFunctionShellParam(BaseModel): - type: Annotated[ - Literal['SpecificFunctionShellParam'], - Field(description='The tool to call. Always `shell`.'), - ] - - -class ConversationParam2(BaseModel): - id: Annotated[ - str, - Field(description='The unique ID of the conversation.', examples=['conv_123']), - ] - - -class Conversation2(BaseModel): - id: Annotated[str, Field(description='The unique ID of the conversation.')] - - -class UpdateConversationBody(BaseModel): - metadata: Annotated[ - Metadata, - Field( - description='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.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.' - ), - ] - - -class DeletedConversationResource(BaseModel): - object: Literal['conversation.deleted'] - deleted: bool - id: str - - -class OrderEnum(RootModel[Literal['asc', 'desc']]): - root: Literal['asc', 'desc'] - - -class VideoModel(RootModel[Literal['sora-2', 'sora-2-pro']]): - root: Literal['sora-2', 'sora-2-pro'] - - -class VideoStatus(RootModel[Literal['queued', 'in_progress', 'completed', 'failed']]): - root: Literal['queued', 'in_progress', 'completed', 'failed'] - - -class VideoSize(RootModel[Literal['720x1280', '1280x720', '1024x1792', '1792x1024']]): - root: Literal['720x1280', '1280x720', '1024x1792', '1792x1024'] - - -class VideoSeconds(RootModel[Literal['4', '8', '12']]): - root: Literal['4', '8', '12'] - - -class Error21(BaseModel): - code: str - message: str - - -class VideoResource(BaseModel): - id: Annotated[str, Field(description='Unique identifier for the video job.')] - object: Annotated[ - Literal['video'], Field(description='The object type, which is always `video`.') - ] - model: Annotated[ - VideoModel, - Field(description='The video generation model that produced the job.'), - ] - status: Annotated[ - VideoStatus, Field(description='Current lifecycle status of the video job.') - ] - progress: Annotated[ - int, - Field(description='Approximate completion percentage for the generation task.'), - ] - created_at: Annotated[ - int, Field(description='Unix timestamp (seconds) for when the job was created.') - ] - completed_at: Optional[int] = None - expires_at: Optional[int] = None - prompt: Optional[str] = None - size: Annotated[ - VideoSize, Field(description='The resolution of the generated video.') - ] - seconds: Annotated[ - VideoSeconds, Field(description='Duration of the generated clip in seconds.') - ] - remixed_from_video_id: Optional[str] = None - error: Optional[Error21] = None - - -class VideoListResource(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of object returned, must be `list`.'), - ] - data: Annotated[List[VideoResource], Field(description='A list of items')] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - - -class CreateVideoBody(BaseModel): - model: Annotated[ - Optional[VideoModel], - Field(description='The video generation model to use. Defaults to `sora-2`.'), - ] = None - prompt: Annotated[ - str, - Field( - description='Text prompt that describes the video to generate.', - max_length=32000, - min_length=1, - ), - ] - input_reference: Annotated[ - Optional[bytes], - Field(description='Optional image reference that guides generation.'), - ] = None - seconds: Annotated[ - Optional[VideoSeconds], - Field(description='Clip duration in seconds. Defaults to 4 seconds.'), - ] = None - size: Annotated[ - Optional[VideoSize], - Field( - description='Output resolution formatted as width x height. Defaults to 720x1280.' - ), - ] = None - - -class DeletedVideoResource(BaseModel): - object: Annotated[ - Literal['video.deleted'], - Field(description='The object type that signals the deletion response.'), - ] - deleted: Annotated[ - bool, Field(description='Indicates that the video resource was deleted.') - ] - id: Annotated[str, Field(description='Identifier of the deleted video.')] - - -class VideoContentVariant(RootModel[Literal['video', 'thumbnail', 'spritesheet']]): - root: Literal['video', 'thumbnail', 'spritesheet'] - - -class CreateVideoRemixBody(BaseModel): - prompt: Annotated[ - str, - Field( - description='Updated text prompt that directs the remix generation.', - max_length=32000, - min_length=1, - ), - ] - - -class TruncationEnum(RootModel[Literal['auto', 'disabled']]): - root: Literal['auto', 'disabled'] - - -class Input10(RootModel[str]): - root: Annotated[ - str, - Field( - description='A text input to the model, equivalent to a text input with the `user` role.', - max_length=10485760, - ), - ] - - -class TokenCountsResource(BaseModel): - object: Literal['response.input_tokens'] - input_tokens: int - - -class ChatkitWorkflowTracing(BaseModel): - enabled: Annotated[bool, Field(description='Indicates whether tracing is enabled.')] - - -class ChatkitWorkflow(BaseModel): - id: Annotated[ - str, Field(description='Identifier of the workflow backing the session.') - ] - version: Optional[str] = None - state_variables: Optional[Dict[str, Union[str, int, bool, float]]] = None - tracing: Annotated[ - ChatkitWorkflowTracing, - Field(description='Tracing settings applied to the workflow.'), - ] - - -class ChatSessionRateLimits(BaseModel): - max_requests_per_1_minute: Annotated[ - int, Field(description='Maximum allowed requests per one-minute window.') - ] - - -class ChatSessionStatus(RootModel[Literal['active', 'expired', 'cancelled']]): - root: Literal['active', 'expired', 'cancelled'] - - -class ChatSessionAutomaticThreadTitling(BaseModel): - enabled: Annotated[ - bool, Field(description='Whether automatic thread titling is enabled.') - ] - - -class ChatSessionFileUpload(BaseModel): - enabled: Annotated[ - bool, Field(description='Indicates if uploads are enabled for the session.') - ] - max_file_size: Optional[int] = None - max_files: Optional[int] = None - - -class ChatSessionHistory(BaseModel): - enabled: Annotated[ - bool, - Field(description='Indicates if chat history is persisted for the session.'), - ] - recent_threads: Optional[int] = None - - -class ChatSessionChatkitConfiguration(BaseModel): - automatic_thread_titling: Annotated[ - ChatSessionAutomaticThreadTitling, - Field(description='Automatic thread titling preferences.'), - ] - file_upload: Annotated[ - ChatSessionFileUpload, Field(description='Upload settings for the session.') - ] - history: Annotated[ - ChatSessionHistory, Field(description='History retention configuration.') - ] - - -class ChatSessionResource(BaseModel): - id: Annotated[str, Field(description='Identifier for the ChatKit session.')] - object: Annotated[ - Literal['chatkit.session'], - Field(description='Type discriminator that is always `chatkit.session`.'), - ] - expires_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the session expires.'), - ] - client_secret: Annotated[ - str, - Field( - description='Ephemeral client secret that authenticates session requests.' - ), - ] - workflow: Annotated[ - ChatkitWorkflow, Field(description='Workflow metadata for the session.') - ] - user: Annotated[ - str, Field(description='User identifier associated with the session.') - ] - rate_limits: Annotated[ - ChatSessionRateLimits, Field(description='Resolved rate limit values.') - ] - max_requests_per_1_minute: Annotated[ - int, Field(description='Convenience copy of the per-minute request limit.') - ] - status: Annotated[ - ChatSessionStatus, Field(description='Current lifecycle state of the session.') - ] - chatkit_configuration: Annotated[ - ChatSessionChatkitConfiguration, - Field(description='Resolved ChatKit feature configuration for the session.'), - ] - - -class WorkflowTracingParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field( - description='Whether tracing is enabled during the session. Defaults to true.' - ), - ] = None - - -class StateVariables(RootModel[str]): - root: Annotated[str, Field(max_length=10485760)] - - -class WorkflowParam(BaseModel): - id: Annotated[ - str, Field(description='Identifier for the workflow invoked by the session.') - ] - version: Annotated[ - Optional[str], - Field( - description='Specific workflow version to run. Defaults to the latest deployed version.' - ), - ] = None - state_variables: Annotated[ - Optional[Dict[str, Union[StateVariables, int, bool, float]]], - Field( - description='State variables forwarded to the workflow. Keys may be up to 64 characters, values must be primitive types, and the map defaults to an empty object.' - ), - ] = None - tracing: Annotated[ - Optional[WorkflowTracingParam], - Field( - description='Optional tracing overrides for the workflow invocation. When omitted, tracing is enabled by default.' - ), - ] = None - - -class ExpiresAfterParam(BaseModel): - anchor: Annotated[ - Literal['created_at'], - Field( - description='Base timestamp used to calculate expiration. Currently fixed to `created_at`.' - ), - ] - seconds: Annotated[ - int, - Field( - description='Number of seconds after the anchor when the session expires.', - ge=1, - le=600, - ), - ] - - -class RateLimitsParam(BaseModel): - max_requests_per_1_minute: Annotated[ - Optional[int], - Field( - description='Maximum number of requests allowed per minute for the session. Defaults to 10.', - ge=1, - ), - ] = None - - -class AutomaticThreadTitlingParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field( - description='Enable automatic thread title generation. Defaults to true.' - ), - ] = None - - -class FileUploadParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field(description='Enable uploads for this session. Defaults to false.'), - ] = None - max_file_size: Annotated[ - Optional[int], - Field( - description='Maximum size in megabytes for each uploaded file. Defaults to 512 MB, which is the maximum allowable size.', - ge=1, - le=512, - ), - ] = None - max_files: Annotated[ - Optional[int], - Field( - description='Maximum number of files that can be uploaded to the session. Defaults to 10.', - ge=1, - ), - ] = None - - -class HistoryParam(BaseModel): - enabled: Annotated[ - Optional[bool], - Field( - description='Enables chat users to access previous ChatKit threads. Defaults to true.' - ), - ] = None - recent_threads: Annotated[ - Optional[int], - Field( - description='Number of recent ChatKit threads users have access to. Defaults to unlimited when unset.', - ge=1, - ), - ] = None - - -class ChatkitConfigurationParam(BaseModel): - automatic_thread_titling: Annotated[ - Optional[AutomaticThreadTitlingParam], - Field( - description='Configuration for automatic thread titling. When omitted, automatic thread titling is enabled by default.' - ), - ] = None - file_upload: Annotated[ - Optional[FileUploadParam], - Field( - description='Configuration for upload enablement and limits. When omitted, uploads are disabled by default (max_files 10, max_file_size 512 MB).' - ), - ] = None - history: Annotated[ - Optional[HistoryParam], - Field( - description='Configuration for chat history retention. When omitted, history is enabled by default with no limit on recent_threads (null).' - ), - ] = None - - -class CreateChatSessionBody(BaseModel): - workflow: Annotated[ - WorkflowParam, Field(description='Workflow that powers the session.') - ] - user: Annotated[ - str, - Field( - description='A free-form string that identifies your end user; ensures this Session can access other objects that have the same `user` scope.', - min_length=1, - ), - ] - expires_after: Annotated[ - Optional[ExpiresAfterParam], - Field( - description='Optional override for session expiration timing in seconds from creation. Defaults to 10 minutes.' - ), - ] = None - rate_limits: Annotated[ - Optional[RateLimitsParam], - Field( - description='Optional override for per-minute request limits. When omitted, defaults to 10.' - ), - ] = None - chatkit_configuration: Annotated[ - Optional[ChatkitConfigurationParam], - Field( - description='Optional overrides for ChatKit runtime configuration features' - ), - ] = None - - -class UserMessageInputText(BaseModel): - type: Annotated[ - Literal['UserMessageInputText'], - Field(description='Type discriminator that is always `input_text`.'), - ] - text: Annotated[str, Field(description='Plain-text content supplied by the user.')] - - -class UserMessageQuotedText(BaseModel): - type: Annotated[ - Literal['UserMessageQuotedText'], - Field(description='Type discriminator that is always `quoted_text`.'), - ] - text: Annotated[str, Field(description='Quoted text content.')] - - -class AttachmentType(RootModel[Literal['image', 'file']]): - root: Literal['image', 'file'] - - -class Attachment2(BaseModel): - type: Annotated[AttachmentType, Field(description='Attachment discriminator.')] - id: Annotated[str, Field(description='Identifier for the attachment.')] - name: Annotated[str, Field(description='Original display name for the attachment.')] - mime_type: Annotated[str, Field(description='MIME type of the attachment.')] - preview_url: Optional[str] = None - - -class ToolChoice(BaseModel): - id: Annotated[str, Field(description='Identifier of the requested tool.')] - - -class InferenceOptions(BaseModel): - tool_choice: Optional[ToolChoice] = None - model: Optional[str] = None - - -class Content11(RootModel[Union[UserMessageInputText, UserMessageQuotedText]]): - root: Annotated[ - Union[UserMessageInputText, UserMessageQuotedText], - Field( - description='Content blocks that comprise a user message.', - discriminator='type', - ), - ] - - -class UserMessageItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Literal['UserMessageItem'] - content: Annotated[ - List[Content11], - Field(description='Ordered content elements supplied by the user.'), - ] - attachments: Annotated[ - List[Attachment2], - Field( - description='Attachments associated with the user message. Defaults to an empty list.' - ), - ] - inference_options: Optional[InferenceOptions] = None - - -class FileAnnotationSource(BaseModel): - type: Annotated[ - Literal['file'], Field(description='Type discriminator that is always `file`.') - ] - filename: Annotated[ - str, Field(description='Filename referenced by the annotation.') - ] - - -class FileAnnotation(BaseModel): - type: Annotated[ - Literal['FileAnnotation'], - Field( - description='Type discriminator that is always `file` for this annotation.' - ), - ] - source: Annotated[ - FileAnnotationSource, - Field(description='File attachment referenced by the annotation.'), - ] - - -class UrlAnnotationSource(BaseModel): - type: Annotated[ - Literal['url'], Field(description='Type discriminator that is always `url`.') - ] - url: Annotated[str, Field(description='URL referenced by the annotation.')] - - -class UrlAnnotation(BaseModel): - type: Annotated[ - Literal['UrlAnnotation'], - Field( - description='Type discriminator that is always `url` for this annotation.' - ), - ] - source: Annotated[ - UrlAnnotationSource, Field(description='URL referenced by the annotation.') - ] - - -class Annotations(RootModel[Union[FileAnnotation, UrlAnnotation]]): - root: Annotated[ - Union[FileAnnotation, UrlAnnotation], - Field( - description='Annotation object describing a cited source.', - discriminator='type', - ), - ] - - -class ResponseOutputText(BaseModel): - type: Annotated[ - Literal['output_text'], - Field(description='Type discriminator that is always `output_text`.'), - ] - text: Annotated[str, Field(description='Assistant generated text.')] - annotations: Annotated[ - List[Annotations], - Field(description='Ordered list of annotations attached to the response text.'), - ] - - -class AssistantMessageItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['AssistantMessageItem'], - Field( - description='Type discriminator that is always `chatkit.assistant_message`.' - ), - ] - content: Annotated[ - List[ResponseOutputText], - Field(description='Ordered assistant response segments.'), - ] - - -class WidgetMessageItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['WidgetMessageItem'], - Field(description='Type discriminator that is always `chatkit.widget`.'), - ] - widget: Annotated[ - str, Field(description='Serialized widget payload rendered in the UI.') - ] - - -class ClientToolCallStatus(RootModel[Literal['in_progress', 'completed']]): - root: Literal['in_progress', 'completed'] - - -class ClientToolCallItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['ClientToolCallItem'], - Field( - description='Type discriminator that is always `chatkit.client_tool_call`.' - ), - ] - status: Annotated[ - ClientToolCallStatus, Field(description='Execution status for the tool call.') - ] - call_id: Annotated[str, Field(description='Identifier for the client tool call.')] - name: Annotated[str, Field(description='Tool name that was invoked.')] - arguments: Annotated[ - str, Field(description='JSON-encoded arguments that were sent to the tool.') - ] - output: Optional[str] = None - - -class TaskType(RootModel[Literal['custom', 'thought']]): - root: Literal['custom', 'thought'] - - -class TaskItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['TaskItem'], - Field(description='Type discriminator that is always `chatkit.task`.'), - ] - task_type: Annotated[TaskType, Field(description='Subtype for the task.')] - heading: Optional[str] = None - summary: Optional[str] = None - - -class TaskGroupTask(BaseModel): - type: Annotated[TaskType, Field(description='Subtype for the grouped task.')] - heading: Optional[str] = None - summary: Optional[str] = None - - -class TaskGroupItem(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread item.')] - object: Annotated[ - Literal['chatkit.thread_item'], - Field(description='Type discriminator that is always `chatkit.thread_item`.'), - ] - created_at: Annotated[ - int, - Field(description='Unix timestamp (in seconds) for when the item was created.'), - ] - thread_id: Annotated[str, Field(description='Identifier of the parent thread.')] - type: Annotated[ - Literal['TaskGroupItem'], - Field(description='Type discriminator that is always `chatkit.task_group`.'), - ] - tasks: Annotated[ - List[TaskGroupTask], Field(description='Tasks included in the group.') - ] - - -class ThreadItem( - RootModel[ - Union[ - UserMessageItem, - AssistantMessageItem, - WidgetMessageItem, - ClientToolCallItem, - TaskItem, - TaskGroupItem, - ] - ] -): - root: Annotated[ - Union[ - UserMessageItem, - AssistantMessageItem, - WidgetMessageItem, - ClientToolCallItem, - TaskItem, - TaskGroupItem, - ], - Field(discriminator='type', title='The thread item'), - ] - - -class ThreadItemListResource(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of object returned, must be `list`.'), - ] - data: Annotated[List[ThreadItem], Field(description='A list of items')] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - - -class ActiveStatus(BaseModel): - type: Annotated[ - Literal['ActiveStatus'], - Field(description='Status discriminator that is always `active`.'), - ] - - -class LockedStatus(BaseModel): - type: Annotated[ - Literal['LockedStatus'], - Field(description='Status discriminator that is always `locked`.'), - ] - reason: Optional[str] = None - - -class ClosedStatus(BaseModel): - type: Annotated[ - Literal['ClosedStatus'], - Field(description='Status discriminator that is always `closed`.'), - ] - reason: Optional[str] = None - - -class ThreadResource(BaseModel): - id: Annotated[str, Field(description='Identifier of the thread.')] - object: Annotated[ - Literal['chatkit.thread'], - Field(description='Type discriminator that is always `chatkit.thread`.'), - ] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) for when the thread was created.' - ), - ] - title: Optional[str] = None - status: Annotated[ - Union[ActiveStatus, LockedStatus, ClosedStatus], - Field( - description='Current status for the thread. Defaults to `active` for newly created threads.', - discriminator='type', - ), - ] - user: Annotated[ - str, - Field( - description='Free-form string that identifies your end user who owns the thread.' - ), - ] - - -class DeletedThreadResource(BaseModel): - id: Annotated[str, Field(description='Identifier of the deleted thread.')] - object: Annotated[ - Literal['chatkit.thread.deleted'], - Field( - description='Type discriminator that is always `chatkit.thread.deleted`.' - ), - ] - deleted: Annotated[ - bool, Field(description='Indicates that the thread has been deleted.') - ] - - -class ThreadListResource(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of object returned, must be `list`.'), - ] - data: Annotated[List[ThreadResource], Field(description='A list of items')] - first_id: Optional[str] = None - last_id: Optional[str] = None - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - - -class RealtimeConnectParams(BaseModel): - model: Optional[str] = None - call_id: Optional[str] = None - - -class ImageUrl4(BaseModel): - url: Annotated[ - AnyUrl, - Field( - description='Either a URL of the image or the base64 encoded image data.', - examples=['https://example.com/image.jpg'], - ), - ] - - -class ModerationImageURLInput(BaseModel): - type: Annotated[ - Literal['ModerationImageURLInput'], Field(description='Always `image_url`.') - ] - image_url: Annotated[ - ImageUrl4, - Field( - description='Contains either an image URL or a data URL for a base64 encoded image.' - ), - ] - - -class ModerationTextInput(BaseModel): - type: Annotated[Literal['ModerationTextInput'], Field(description='Always `text`.')] - text: Annotated[ - str, - Field( - description='A string of text to classify.', - examples=['I want to kill them'], - ), - ] - - -class ComparisonFilterValueItems(RootModel[Union[str, float]]): - root: Union[str, float] - - -class ChunkingStrategyResponse( - RootModel[ - Union[StaticChunkingStrategyResponseParam, OtherChunkingStrategyResponseParam] - ] -): - root: Annotated[ - Union[StaticChunkingStrategyResponseParam, OtherChunkingStrategyResponseParam], - Field(description='The strategy used to chunk the file.', discriminator='type'), - ] - - -class FilePurpose( - RootModel[ - Literal['assistants', 'batch', 'fine-tune', 'vision', 'user_data', 'evals'] - ] -): - root: Annotated[ - Literal['assistants', 'batch', 'fine-tune', 'vision', 'user_data', 'evals'], - Field( - description='The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets\n' - ), - ] - - -class BatchError(BaseModel): - code: Annotated[ - Optional[str], Field(description='An error code identifying the error type.') - ] = None - message: Annotated[ - Optional[str], - Field( - description='A human-readable message providing more details about the error.' - ), - ] = None - param: Optional[str] = None - line: Optional[int] = None - - -class BatchRequestCounts(BaseModel): - total: Annotated[int, Field(description='Total number of requests in the batch.')] - completed: Annotated[ - int, - Field(description='Number of requests that have been completed successfully.'), - ] - failed: Annotated[int, Field(description='Number of requests that have failed.')] - - -class TextAnnotationDelta( - RootModel[ - Union[ - MessageDeltaContentTextAnnotationsFileCitationObject, - MessageDeltaContentTextAnnotationsFilePathObject, - ] - ] -): - root: Annotated[ - Union[ - MessageDeltaContentTextAnnotationsFileCitationObject, - MessageDeltaContentTextAnnotationsFilePathObject, - ], - Field(discriminator='type'), - ] - - -class TextAnnotation( - RootModel[ - Union[ - MessageContentTextAnnotationsFileCitationObject, - MessageContentTextAnnotationsFilePathObject, - ] - ] -): - root: Annotated[ - Union[ - MessageContentTextAnnotationsFileCitationObject, - MessageContentTextAnnotationsFilePathObject, - ], - Field(discriminator='type'), - ] - - -class ChatModel( - RootModel[ - Literal[ - 'gpt-5.1', - 'gpt-5.1-2025-11-13', - 'gpt-5.1-codex', - 'gpt-5.1-mini', - 'gpt-5.1-chat-latest', - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-5-chat-latest', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'o4-mini', - 'o4-mini-2025-04-16', - 'o3', - 'o3-2025-04-16', - 'o3-mini', - 'o3-mini-2025-01-31', - 'o1', - 'o1-2024-12-17', - 'o1-preview', - 'o1-preview-2024-09-12', - 'o1-mini', - 'o1-mini-2024-09-12', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-audio-preview', - 'gpt-4o-audio-preview-2024-10-01', - 'gpt-4o-audio-preview-2024-12-17', - 'gpt-4o-audio-preview-2025-06-03', - 'gpt-4o-mini-audio-preview', - 'gpt-4o-mini-audio-preview-2024-12-17', - 'gpt-4o-search-preview', - 'gpt-4o-mini-search-preview', - 'gpt-4o-search-preview-2025-03-11', - 'gpt-4o-mini-search-preview-2025-03-11', - 'chatgpt-4o-latest', - 'codex-mini-latest', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0301', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ] - ] -): - root: Literal[ - 'gpt-5.1', - 'gpt-5.1-2025-11-13', - 'gpt-5.1-codex', - 'gpt-5.1-mini', - 'gpt-5.1-chat-latest', - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-5-chat-latest', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'o4-mini', - 'o4-mini-2025-04-16', - 'o3', - 'o3-2025-04-16', - 'o3-mini', - 'o3-mini-2025-01-31', - 'o1', - 'o1-2024-12-17', - 'o1-preview', - 'o1-preview-2024-09-12', - 'o1-mini', - 'o1-mini-2024-09-12', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-audio-preview', - 'gpt-4o-audio-preview-2024-10-01', - 'gpt-4o-audio-preview-2024-12-17', - 'gpt-4o-audio-preview-2025-06-03', - 'gpt-4o-mini-audio-preview', - 'gpt-4o-mini-audio-preview-2024-12-17', - 'gpt-4o-search-preview', - 'gpt-4o-mini-search-preview', - 'gpt-4o-search-preview-2025-03-11', - 'gpt-4o-mini-search-preview-2025-03-11', - 'chatgpt-4o-latest', - 'codex-mini-latest', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0301', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ] - - -class Summary(BaseModel): - type: Annotated[ - Literal['summary_text'], - Field(description='The type of the object. Always `summary_text`.'), - ] - text: Annotated[ - str, - Field(description='A summary of the reasoning output from the model so far.'), - ] - - -class FileSearch11(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), - ] = None - - -class ToolResources7(BaseModel): - code_interpreter: Optional[CodeInterpreter5] = None - file_search: Optional[FileSearch11] = None - - -class SubmitToolOutputsRunRequestWithoutStream(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - tool_outputs: Annotated[ - List[ToolOutput], - Field(description='A list of tools for which the outputs are being submitted.'), - ] - - -class RunStatus( - RootModel[ - Literal[ - 'queued', - 'in_progress', - 'requires_action', - 'cancelling', - 'cancelled', - 'failed', - 'completed', - 'incomplete', - 'expired', - ] - ] -): - root: Annotated[ - Literal[ - 'queued', - 'in_progress', - 'requires_action', - 'cancelling', - 'cancelled', - 'failed', - 'completed', - 'incomplete', - 'expired', - ], - Field( - description='The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`.' - ), - ] - - -class CodeInterpreterContainerAuto(BaseModel): - type: Annotated[Literal['auto'], Field(description='Always `auto`.')] - file_ids: Annotated[ - Optional[List[str]], - Field( - description='An optional list of uploaded files to make available to your code.', - max_length=50, - ), - ] = None - memory_limit: Optional[ContainerMemoryLimit] = None - - -class FileSearch1(BaseModel): - max_num_results: Annotated[ - Optional[int], - Field( - description='The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n\nNote that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n', - ge=1, - le=50, - ), - ] = None - ranking_options: Optional[FileSearchRankingOptions] = None - - -class AssistantToolsFileSearch(BaseModel): - type: Annotated[ - Literal['AssistantToolsFileSearch'], - Field(description='The type of tool being defined: `file_search`'), - ] - file_search: Annotated[ - Optional[FileSearch1], Field(description='Overrides for the file search tool.') - ] = None - - -class AssistantsApiToolChoiceOption( - RootModel[Union[Literal['none', 'auto', 'required'], AssistantsNamedToolChoice]] -): - root: Annotated[ - Union[Literal['none', 'auto', 'required'], AssistantsNamedToolChoice], - Field( - description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n' - ), - ] - - -class AuditLogActorApiKey(BaseModel): - id: Annotated[ - Optional[str], Field(description='The tracking id of the API key.') - ] = None - type: Annotated[ - Optional[Literal['user', 'service_account']], - Field( - description='The type of API key. Can be either `user` or `service_account`.' - ), - ] = None - user: Optional[AuditLogActorUser] = None - service_account: Optional[AuditLogActorServiceAccount] = None - - -class AuditLogActorSession(BaseModel): - user: Optional[AuditLogActorUser] = None - ip_address: Annotated[ - Optional[str], - Field(description='The IP address from which the action was performed.'), - ] = None - - -class Errors(BaseModel): - object: Annotated[ - Optional[str], Field(description='The object type, which is always `list`.') - ] = None - data: Optional[List[BatchError]] = None - - -class Batch(BaseModel): - id: str - object: Annotated[ - Literal['batch'], Field(description='The object type, which is always `batch`.') - ] - endpoint: Annotated[ - str, Field(description='The OpenAI API endpoint used by the batch.') - ] - model: Annotated[ - Optional[str], - Field( - description='Model ID used to process the batch, like `gpt-5-2025-08-07`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model\nguide](https://platform.openai.com/docs/models) to browse and compare available models.\n' - ), - ] = None - errors: Optional[Errors] = None - input_file_id: Annotated[ - str, Field(description='The ID of the input file for the batch.') - ] - completion_window: Annotated[ - str, - Field(description='The time frame within which the batch should be processed.'), - ] - status: Annotated[ - Literal[ - 'validating', - 'failed', - 'in_progress', - 'finalizing', - 'completed', - 'expired', - 'cancelling', - 'cancelled', - ], - Field(description='The current status of the batch.'), - ] - output_file_id: Annotated[ - Optional[str], - Field( - description='The ID of the file containing the outputs of successfully executed requests.' - ), - ] = None - error_file_id: Annotated[ - Optional[str], - Field( - description='The ID of the file containing the outputs of requests with errors.' - ), - ] = None - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the batch was created.' - ), - ] - in_progress_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch started processing.' - ), - ] = None - expires_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch will expire.' - ), - ] = None - finalizing_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch started finalizing.' - ), - ] = None - completed_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch was completed.' - ), - ] = None - failed_at: Annotated[ - Optional[int], - Field(description='The Unix timestamp (in seconds) for when the batch failed.'), - ] = None - expired_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch expired.' - ), - ] = None - cancelling_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch started cancelling.' - ), - ] = None - cancelled_at: Annotated[ - Optional[int], - Field( - description='The Unix timestamp (in seconds) for when the batch was cancelled.' - ), - ] = None - request_counts: Optional[BatchRequestCounts] = None - usage: Annotated[ - Optional[Usage], - Field( - description='Represents token usage details including input tokens, output tokens, a\nbreakdown of output tokens, and the total tokens used. Only populated on\nbatches created after September 7, 2025.\n' - ), - ] = None - metadata: Optional[Metadata] = None - - -class ChatCompletionFunctions(BaseModel): - description: Annotated[ - Optional[str], - Field( - description='A description of what the function does, used by the model to choose when and how to call the function.' - ), - ] = None - name: Annotated[ - str, - Field( - description='The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.' - ), - ] - parameters: Optional[FunctionParameters] = None - - -class Datum(ChatCompletionResponseMessage): - id: Annotated[str, Field(description='The identifier of the chat message.')] - content_parts: Optional[ - List[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartImage, - ] - ] - ] = None - - -class ChatCompletionMessageList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[ - List[Datum], Field(description='An array of chat completion message objects.\n') - ] - first_id: Annotated[ - str, - Field( - description='The identifier of the first chat message in the data array.' - ), - ] - last_id: Annotated[ - str, - Field(description='The identifier of the last chat message in the data array.'), - ] - has_more: Annotated[ - bool, - Field(description='Indicates whether there are more chat messages available.'), - ] - - -class ChatCompletionRequestAssistantMessageContentPart( - RootModel[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartRefusal, - ] - ] -): - root: Annotated[ - Union[ - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartRefusal, - ], - Field(discriminator='type'), - ] - - -class Content1(RootModel[List[ChatCompletionRequestMessageContentPartText]]): - root: Annotated[ - List[ChatCompletionRequestMessageContentPartText], - Field( - description='An array of content parts with a defined type. For developer messages, only type `text` is supported.', - min_length=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestDeveloperMessage(BaseModel): - content: Annotated[ - Union[str, Content1], - Field(description='The contents of the developer message.'), - ] - role: Annotated[ - Literal['ChatCompletionRequestDeveloperMessage'], - Field(description='The role of the messages author, in this case `developer`.'), - ] - name: Annotated[ - Optional[str], - Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' - ), - ] = None - - -class Content2(RootModel[List[ChatCompletionRequestSystemMessageContentPart]]): - root: Annotated[ - List[ChatCompletionRequestSystemMessageContentPart], - Field( - description='An array of content parts with a defined type. For system messages, only type `text` is supported.', - min_length=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestSystemMessage(BaseModel): - content: Annotated[ - Union[str, Content2], Field(description='The contents of the system message.') - ] - role: Annotated[ - Literal['ChatCompletionRequestSystemMessage'], - Field(description='The role of the messages author, in this case `system`.'), - ] - name: Annotated[ - Optional[str], - Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' - ), - ] = None - - -class Content3(RootModel[List[ChatCompletionRequestToolMessageContentPart]]): - root: Annotated[ - List[ChatCompletionRequestToolMessageContentPart], - Field( - description='An array of content parts with a defined type. For tool messages, only type `text` is supported.', - min_length=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestToolMessage(BaseModel): - role: Annotated[ - Literal['ChatCompletionRequestToolMessage'], - Field(description='The role of the messages author, in this case `tool`.'), - ] - content: Annotated[ - Union[str, Content3], Field(description='The contents of the tool message.') - ] - tool_call_id: Annotated[ - str, Field(description='Tool call that this message is responding to.') - ] - - -class Content4(RootModel[List[ChatCompletionRequestUserMessageContentPart]]): - root: Annotated[ - List[ChatCompletionRequestUserMessageContentPart], - Field( - description='An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text, image, or audio inputs.', - min_length=1, - title='Array of content parts', - ), - ] - - -class ChatCompletionRequestUserMessage(BaseModel): - content: Annotated[ - Union[str, Content4], Field(description='The contents of the user message.\n') - ] - role: Annotated[ - Literal['ChatCompletionRequestUserMessage'], - Field(description='The role of the messages author, in this case `user`.'), - ] - name: Annotated[ - Optional[str], - Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' - ), - ] = None - - -class ChunkingStrategyRequestParam( - RootModel[ - Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam] - ] -): - root: Annotated[ - Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty.', - discriminator='type', - ), - ] - - -class CodeInterpreterTool(BaseModel): - type: Annotated[ - Literal['CodeInterpreterTool'], - Field( - description='The type of the code interpreter tool. Always `code_interpreter`.\n' - ), - ] - container: Annotated[ - Union[str, CodeInterpreterContainerAuto], - Field( - description='The code interpreter container. Can be a container ID or an object that\nspecifies uploaded file IDs to make available to your code.\n' - ), - ] - - -class Outputs(RootModel[Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage]]): - root: Annotated[ - Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage], - Field(discriminator='type'), - ] - - -class CodeInterpreterToolCall(BaseModel): - type: Annotated[ - Literal['CodeInterpreterToolCall'], - Field( - description='The type of the code interpreter tool call. Always `code_interpreter_call`.\n' - ), - ] - id: Annotated[ - str, Field(description='The unique ID of the code interpreter tool call.\n') - ] - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete', 'interpreting', 'failed'], - Field( - description='The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n' - ), - ] - container_id: Annotated[ - str, Field(description='The ID of the container used to run the code.\n') - ] - code: Optional[str] = None - outputs: Optional[List[Outputs]] = None - - -class ComparisonFilter(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - type: Annotated[ - Literal['ComparisonFilter'], - Field( - description='Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`.\n- `eq`: equals\n- `ne`: not equal\n- `gt`: greater than\n- `gte`: greater than or equal\n- `lt`: less than\n- `lte`: less than or equal\n- `in`: in\n- `nin`: not in\n' - ), - ] - key: Annotated[str, Field(description='The key to compare against the value.')] - value: Annotated[ - Union[str, float, bool, List[ComparisonFilterValueItems]], - Field( - description='The value to compare against the attribute key; supports string, number, or boolean types.' - ), - ] - - -class ComputerToolCallOutput(BaseModel): - type: Annotated[ - Literal['computer_call_output'], - Field( - description='The type of the computer tool call output. Always `computer_call_output`.\n' - ), - ] - id: Annotated[ - Optional[str], Field(description='The ID of the computer tool call output.\n') - ] = None - call_id: Annotated[ - str, - Field( - description='The ID of the computer tool call that produced the output.\n' - ), - ] - acknowledged_safety_checks: Annotated[ - Optional[List[ComputerCallSafetyCheckParam]], - Field( - description='The safety checks reported by the API that have been acknowledged by the\ndeveloper.\n' - ), - ] = None - output: ComputerScreenshotImage - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n' - ), - ] = None - - -class ComputerToolCallOutputResource(ComputerToolCallOutput): - id: Annotated[ - str, Field(description='The unique ID of the computer call tool output.\n') - ] - type: Literal['ComputerToolCallOutputResource'] - - -class ContainerFileListResource(BaseModel): - object: Annotated[ - Literal['list'], - Field(description="The type of object returned, must be 'list'."), - ] - data: Annotated[ - List[ContainerFileResource], Field(description='A list of container files.') - ] - first_id: Annotated[str, Field(description='The ID of the first file in the list.')] - last_id: Annotated[str, Field(description='The ID of the last file in the list.')] - has_more: Annotated[ - bool, Field(description='Whether there are more files available.') - ] - - -class ContainerListResource(BaseModel): - object: Annotated[ - Literal['list'], - Field(description="The type of object returned, must be 'list'."), - ] - data: Annotated[List[ContainerResource], Field(description='A list of containers.')] - first_id: Annotated[ - str, Field(description='The ID of the first container in the list.') - ] - last_id: Annotated[ - str, Field(description='The ID of the last container in the list.') - ] - has_more: Annotated[ - bool, Field(description='Whether there are more containers available.') - ] - - -Conversation = ConversationResource - - -class ConversationParam(RootModel[Union[str, ConversationParam2]]): - root: Annotated[ - Union[str, ConversationParam2], - Field( - description='The conversation that this response belongs to. Items from this conversation are prepended to `input_items` for this response request.\nInput items and output items from this response are automatically added to this conversation after this response completes.\n' - ), - ] - - -class VectorStore(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_length=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy, ChunkingStrategy1]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch2(BaseModel): - vector_store_ids: Annotated[ - List[str], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), - ] - vector_stores: Annotated[ - Optional[List[VectorStore]], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), - ] = None - - -class VectorStore1(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_length=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy2, ChunkingStrategy3]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch3(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), - ] = None - vector_stores: Annotated[ - List[VectorStore1], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n', - max_length=1, - ), - ] - - -class ToolResources1(BaseModel): - code_interpreter: Optional[CodeInterpreter1] = None - file_search: Optional[Union[FileSearch2, FileSearch3]] = None - - -class UserLocation(BaseModel): - type: Annotated[ - Literal['approximate'], - Field( - description='The type of location approximation. Always `approximate`.\n' - ), - ] - approximate: WebSearchLocation - - -class WebSearchOptions(BaseModel): - user_location: Annotated[ - Optional[UserLocation], - Field(description='Approximate location parameters for the search.\n'), - ] = None - search_context_size: Annotated[Optional[WebSearchContextSize], Field()] = 'medium' - - -class Audio2(BaseModel): - voice: Annotated[ - VoiceIdsShared, - Field( - description='The voice the model uses to respond. Supported voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`.\n' - ), - ] - format: Annotated[ - Literal['wav', 'aac', 'mp3', 'flac', 'opus', 'pcm16'], - Field( - description='Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`,\n`opus`, or `pcm16`.\n' - ), - ] - - -class CreateChatCompletionResponse(BaseModel): - id: Annotated[ - str, Field(description='A unique identifier for the chat completion.') - ] - choices: Annotated[ - List[Choice], - Field( - description='A list of chat completion choices. Can be more than one if `n` is greater than 1.' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the chat completion was created.' - ), - ] - model: Annotated[str, Field(description='The model used for the chat completion.')] - service_tier: Optional[ServiceTier] = None - system_fingerprint: Annotated[ - Optional[str], - Field( - description='This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n' - ), - ] = None - object: Annotated[ - Literal['chat.completion'], - Field(description='The object type, which is always `chat.completion`.'), - ] - usage: Optional[CompletionUsage] = None - - -class CreateChatCompletionStreamResponse(BaseModel): - id: Annotated[ - str, - Field( - description='A unique identifier for the chat completion. Each chunk has the same ID.' - ), - ] - choices: Annotated[ - List[Choice1], - Field( - description='A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the\nlast chunk if you set `stream_options: {"include_usage": true}`.\n' - ), - ] - created: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.' - ), - ] - model: Annotated[str, Field(description='The model to generate the completion.')] - service_tier: Optional[ServiceTier] = None - system_fingerprint: Annotated[ - Optional[str], - Field( - description='This fingerprint represents the backend configuration that the model runs with.\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n' - ), - ] = None - object: Annotated[ - Literal['chat.completion.chunk'], - Field(description='The object type, which is always `chat.completion.chunk`.'), - ] - usage: Annotated[ - Optional[CompletionUsage], - Field( - description='An optional field that will only be present when you set\n`stream_options: {"include_usage": true}` in your request. When present, it\ncontains a null value **except for the last chunk** which contains the\ntoken usage statistics for the entire request.\n\n**NOTE:** If the stream is interrupted or cancelled, you may not\nreceive the final usage chunk which contains the total token usage for\nthe request.\n' - ), - ] = None - - -class CreateCompletionRequest(BaseModel): - model: Annotated[ - Union[str, Literal['gpt-3.5-turbo-instruct', 'davinci-002', 'babbage-002']], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n' - ), - ] - prompt: Annotated[ - Optional[Union[Optional[str], List[str], Prompt, Prompt1]], - Field( - description='The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n' - ), - ] - best_of: Annotated[ - Optional[int], - Field( - description='Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed.\n\nWhen used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n', - ge=0, - le=20, - ), - ] = 1 - echo: Annotated[ - Optional[bool], - Field(description='Echo back the prompt in addition to the completion\n'), - ] = False - frequency_penalty: Annotated[ - Optional[float], - Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n", - ge=-2.0, - le=2.0, - ), - ] = 0 - logit_bias: Annotated[ - Optional[Dict[str, int]], - Field( - description='Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n\nAs an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated.\n' - ), - ] = None - logprobs: Annotated[ - Optional[int], - Field( - description='Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n\nThe maximum value for `logprobs` is 5.\n', - ge=0, - le=5, - ), - ] = None - max_tokens: Annotated[ - Optional[int], - Field( - description="The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n\nThe token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n", - examples=[16], - ge=0, - ), - ] = 16 - n: Annotated[ - Optional[int], - Field( - description='How many completions to generate for each prompt.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n', - examples=[1], - ge=1, - le=128, - ), - ] = 1 - presence_penalty: Annotated[ - Optional[float], - Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n", - ge=-2.0, - le=2.0, - ), - ] = 0 - seed: Annotated[ - Optional[int], - Field( - description='If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n' - ), - ] = None - stop: Optional[StopConfiguration] = None - stream: Annotated[ - Optional[bool], - Field( - description='Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n' - ), - ] = False - stream_options: Optional[ChatCompletionStreamOptions] = None - suffix: Annotated[ - Optional[str], - Field( - description='The suffix that comes after a completion of inserted text.\n\nThis parameter is only supported for `gpt-3.5-turbo-instruct`.\n', - examples=['test.'], - ), - ] = None - temperature: Annotated[ - Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n', - examples=[1], - ge=0.0, - le=2.0, - ), - ] = 1 - top_p: Annotated[ - Optional[float], - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n', - examples=[1], - ge=0.0, - le=1.0, - ), - ] = 1 - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - examples=['user-1234'], - ), - ] = None - - -class CreateEmbeddingResponse(BaseModel): - data: Annotated[ - List[Embedding], - Field(description='The list of embeddings generated by the model.'), - ] - model: Annotated[ - str, Field(description='The name of the model used to generate the embedding.') - ] - object: Annotated[ - Literal['list'], Field(description='The object type, which is always "list".') - ] - usage: Annotated[ - Usage1, Field(description='The usage information for the request.') - ] - - -class CreateEvalJsonlRunDataSource(BaseModel): - type: Annotated[ - Literal['CreateEvalJsonlRunDataSource'], - Field(description='The type of data source. Always `jsonl`.'), - ] - source: Annotated[ - Union[EvalJsonlFileContentSource, EvalJsonlFileIdSource], - Field( - description='Determines what populates the `item` namespace in the data source.', - discriminator='type', - ), - ] - - -class CreateFileRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - file: Annotated[ - bytes, Field(description='The File object (not file name) to be uploaded.\n') - ] - purpose: FilePurpose - expires_after: Optional[FileExpirationAfter] = None - - -class CreateImageEditRequest(BaseModel): - image: Annotated[ - Union[bytes, Image], - Field( - description='The image(s) to edit. Must be a supported image file or an array of images.\n\nFor `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less\nthan 50MB. You can provide up to 16 images.\n\nFor `dall-e-2`, you can only provide one image, and it should be a square\n`png` file less than 4MB.\n' - ), - ] - prompt: Annotated[ - str, - Field( - description='A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.', - examples=['A cute baby sea otter wearing a beret'], - ), - ] - mask: Annotated[ - Optional[bytes], - Field( - description='An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`.' - ), - ] = None - background: Annotated[ - Optional[Literal['transparent', 'opaque', 'auto']], - Field( - description='Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for `gpt-image-1`. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n', - examples=['transparent'], - ), - ] = 'auto' - model: Annotated[ - Optional[ - Union[Optional[str], Literal['dall-e-2', 'gpt-image-1', 'gpt-image-1-mini']] - ], - Field( - description='The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.' - ), - ] = None - n: Annotated[ - Optional[int], - Field( - description='The number of images to generate. Must be between 1 and 10.', - examples=[1], - ge=1, - le=10, - ), - ] = 1 - size: Annotated[ - Optional[ - Literal['256x256', '512x512', '1024x1024', '1536x1024', '1024x1536', 'auto'] - ], - Field( - description='The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.', - examples=['1024x1024'], - ), - ] = '1024x1024' - response_format: Annotated[ - Optional[Literal['url', 'b64_json']], - Field( - description='The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images.', - examples=['url'], - ), - ] = 'url' - output_format: Annotated[ - Optional[Literal['png', 'jpeg', 'webp']], - Field( - description='The format in which the generated images are returned. This parameter is\nonly supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\nThe default value is `png`.\n', - examples=['png'], - ), - ] = 'png' - output_compression: Annotated[ - Optional[int], - Field( - description='The compression level (0-100%) for the generated images. This parameter\nis only supported for `gpt-image-1` with the `webp` or `jpeg` output\nformats, and defaults to 100.\n', - examples=[100], - ), - ] = 100 - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - examples=['user-1234'], - ), - ] = None - input_fidelity: Optional[InputFidelity] = None - stream: Annotated[ - Optional[bool], - Field( - description='Edit the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\n', - examples=[False], - ), - ] = False - partial_images: Optional[PartialImages] = None - quality: Annotated[ - Optional[Literal['standard', 'low', 'medium', 'high', 'auto']], - Field( - description='The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`.\n', - examples=['high'], - ), - ] = 'auto' - - -class CreateImageRequest(BaseModel): - prompt: Annotated[ - str, - Field( - description='A text description of the desired image(s). The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.', - examples=['A cute baby sea otter'], - ), - ] - model: Annotated[ - Optional[ - Union[ - Optional[str], - Literal['dall-e-2', 'dall-e-3', 'gpt-image-1', 'gpt-image-1-mini'], - ] - ], - Field( - description='The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.' - ), - ] = None - n: Annotated[ - Optional[int], - Field( - description='The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.', - examples=[1], - ge=1, - le=10, - ), - ] = 1 - quality: Annotated[ - Optional[Literal['standard', 'hd', 'low', 'medium', 'high', 'auto']], - Field( - description='The quality of the image that will be generated.\n\n- `auto` (default value) will automatically select the best quality for the given model.\n- `high`, `medium` and `low` are supported for `gpt-image-1`.\n- `hd` and `standard` are supported for `dall-e-3`.\n- `standard` is the only option for `dall-e-2`.\n', - examples=['medium'], - ), - ] = 'auto' - response_format: Annotated[ - Optional[Literal['url', 'b64_json']], - Field( - description="The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images.", - examples=['url'], - ), - ] = 'url' - output_format: Annotated[ - Optional[Literal['png', 'jpeg', 'webp']], - Field( - description='The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.', - examples=['png'], - ), - ] = 'png' - output_compression: Annotated[ - Optional[int], - Field( - description='The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100.', - examples=[100], - ), - ] = 100 - stream: Annotated[ - Optional[bool], - Field( - description='Generate the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\nThis parameter is only supported for `gpt-image-1`.\n', - examples=[False], - ), - ] = False - partial_images: Optional[PartialImages] = None - size: Annotated[ - Optional[ - Literal[ - 'auto', - '1024x1024', - '1536x1024', - '1024x1536', - '256x256', - '512x512', - '1792x1024', - '1024x1792', - ] - ], - Field( - description='The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.', - examples=['1024x1024'], - ), - ] = 'auto' - moderation: Annotated[ - Optional[Literal['low', 'auto']], - Field( - description='Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value).', - examples=['low'], - ), - ] = 'auto' - background: Annotated[ - Optional[Literal['transparent', 'opaque', 'auto']], - Field( - description='Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for `gpt-image-1`. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n', - examples=['transparent'], - ), - ] = 'auto' - style: Annotated[ - Optional[Literal['vivid', 'natural']], - Field( - description='The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.', - examples=['vivid'], - ), - ] = 'vivid' - user: Annotated[ - Optional[str], - Field( - description='A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n', - examples=['user-1234'], - ), - ] = None - - -class Content61( - RootModel[ - Union[ - MessageContentImageFileObject, - MessageContentImageUrlObject, - MessageRequestContentTextObject, - ] - ] -): - root: Annotated[ - Union[ - MessageContentImageFileObject, - MessageContentImageUrlObject, - MessageRequestContentTextObject, - ], - Field(discriminator='type'), - ] - - -class Content6(RootModel[List[Content61]]): - root: Annotated[ - List[Content61], - Field( - description='An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](https://platform.openai.com/docs/models).', - min_length=1, - title='Array of content parts', - ), - ] - - -class CreateMessageRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - role: Annotated[ - Literal['user', 'assistant'], - Field( - description='The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n' - ), - ] - content: Union[str, Content6] - attachments: Optional[List[Attachment]] = None - metadata: Optional[Metadata] = None - - -class Input3(RootModel[Union[ModerationImageURLInput, ModerationTextInput]]): - root: Annotated[ - Union[ModerationImageURLInput, ModerationTextInput], Field(discriminator='type') - ] - - -class CreateModerationRequest(BaseModel): - input: Annotated[ - Union[str, List[str], List[Input3]], - Field( - description='Input (or inputs) to classify. Can be a single string, an array of strings, or\nan array of multi-modal input objects similar to other models.\n' - ), - ] - model: Annotated[ - Optional[ - Union[ - str, - Literal[ - 'omni-moderation-latest', - 'omni-moderation-2024-09-26', - 'text-moderation-latest', - 'text-moderation-stable', - ], - ] - ], - Field( - description='The content moderation model you would like to use. Learn more in\n[the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about\navailable models [here](https://platform.openai.com/docs/models#moderation).\n' - ), - ] = None - - -class CreateSpeechRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - model: Annotated[ - Union[str, Literal['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts']], - Field( - description='One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`.\n' - ), - ] - input: Annotated[ - str, - Field( - description='The text to generate audio for. The maximum length is 4096 characters.', - max_length=4096, - ), - ] - instructions: Annotated[ - Optional[str], - Field( - description='Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`.', - max_length=4096, - ), - ] = None - voice: Annotated[ - VoiceIdsShared, - Field( - description='The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options).' - ), - ] - response_format: Annotated[ - Literal['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm'], - Field( - description='The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`.' - ), - ] = 'mp3' - speed: Annotated[ - float, - Field( - description='The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default.', - ge=0.25, - le=4.0, - ), - ] = 1 - stream_format: Annotated[ - Literal['sse', 'audio'], - Field( - description='The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`.' - ), - ] = 'audio' - - -class CreateSpeechResponseStreamEvent( - RootModel[Union[SpeechAudioDeltaEvent, SpeechAudioDoneEvent]] -): - root: Annotated[ - Union[SpeechAudioDeltaEvent, SpeechAudioDoneEvent], Field(discriminator='type') - ] - - -class VectorStore2(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_length=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy4, ChunkingStrategy5]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch5(BaseModel): - vector_store_ids: Annotated[ - List[str], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_length=1, - ), - ] - vector_stores: Annotated[ - Optional[List[VectorStore2]], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_length=1, - ), - ] = None - - -class VectorStore3(BaseModel): - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n', - max_length=10000, - ), - ] = None - chunking_strategy: Annotated[ - Optional[Union[ChunkingStrategy6, ChunkingStrategy7]], - Field( - description='The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.', - discriminator='type', - ), - ] = None - metadata: Optional[Metadata] = None - - -class FileSearch6(BaseModel): - vector_store_ids: Annotated[ - Optional[List[str]], - Field( - description='The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_length=1, - ), - ] = None - vector_stores: Annotated[ - List[VectorStore3], - Field( - description='A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n', - max_length=1, - ), - ] - - -class ToolResources3(BaseModel): - code_interpreter: Optional[CodeInterpreter1] = None - file_search: Optional[Union[FileSearch5, FileSearch6]] = None - - -class CreateThreadRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - messages: Annotated[ - Optional[List[CreateMessageRequest]], - Field( - description='A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with.' - ), - ] = None - tool_resources: Optional[ToolResources3] = None - metadata: Optional[Metadata] = None - - -class CreateTranscriptionResponseDiarizedJson(BaseModel): - task: Annotated[ - Literal['transcribe'], - Field(description='The type of task that was run. Always `transcribe`.'), - ] - duration: Annotated[ - float, Field(description='Duration of the input audio in seconds.') - ] - text: Annotated[ - str, - Field( - description='The concatenated transcript text for the entire audio input.' - ), - ] - segments: Annotated[ - List[TranscriptionDiarizedSegment], - Field( - description='Segments of the transcript annotated with timestamps and speaker labels.' - ), - ] - usage: Annotated[ - Optional[Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration]], - Field( - description='Token or duration usage statistics for the request.', - discriminator='type', - ), - ] = None - - -class CreateTranscriptionResponseJson(BaseModel): - text: Annotated[str, Field(description='The transcribed text.')] - logprobs: Annotated[ - Optional[List[Logprob]], - Field( - description='The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array.\n' - ), - ] = None - usage: Annotated[ - Optional[Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration]], - Field( - description='Token usage statistics for the request.', discriminator='type' - ), - ] = None - - -class CreateTranscriptionResponseVerboseJson(BaseModel): - language: Annotated[str, Field(description='The language of the input audio.')] - duration: Annotated[float, Field(description='The duration of the input audio.')] - text: Annotated[str, Field(description='The transcribed text.')] - words: Annotated[ - Optional[List[TranscriptionWord]], - Field(description='Extracted words and their corresponding timestamps.'), - ] = None - segments: Annotated[ - Optional[List[TranscriptionSegment]], - Field( - description='Segments of the transcribed text and their corresponding details.' - ), - ] = None - usage: Optional[TranscriptTextUsageDuration] = None - - -class CreateTranslationResponseVerboseJson(BaseModel): - language: Annotated[ - str, - Field(description='The language of the output translation (always `english`).'), - ] - duration: Annotated[float, Field(description='The duration of the input audio.')] - text: Annotated[str, Field(description='The translated text.')] - segments: Annotated[ - Optional[List[TranscriptionSegment]], - Field( - description='Segments of the translated text and their corresponding details.' - ), - ] = None - - -class CreateUploadRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - filename: Annotated[str, Field(description='The name of the file to upload.\n')] - purpose: Annotated[ - Literal['assistants', 'batch', 'fine-tune', 'vision'], - Field( - description='The intended purpose of the uploaded file.\n\nSee the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose).\n' - ), - ] - bytes: Annotated[ - int, Field(description='The number of bytes in the file you are uploading.\n') - ] - mime_type: Annotated[ - str, - Field( - description='The MIME type of the file.\n\nThis must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision.\n' - ), - ] - expires_after: Optional[FileExpirationAfter] = None - - -class CreateVectorStoreFileRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - file_id: Annotated[ - str, - Field( - description='A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files.' - ), - ] - chunking_strategy: Optional[ChunkingStrategyRequestParam] = None - attributes: Optional[VectorStoreFileAttributes] = None - - -class CreateVectorStoreRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - file_ids: Annotated[ - Optional[List[str]], - Field( - description='A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.', - max_length=500, - ), - ] = None - name: Annotated[ - Optional[str], Field(description='The name of the vector store.') - ] = None - description: Annotated[ - Optional[str], - Field( - description="A description for the vector store. Can be used to describe the vector store's purpose." - ), - ] = None - expires_after: Optional[VectorStoreExpirationAfter] = None - chunking_strategy: Optional[ChunkingStrategyRequestParam] = None - metadata: Optional[Metadata] = None - - -DeletedConversation = DeletedConversationResource - - -class Drag(BaseModel): - type: Annotated[ - Literal['Drag'], - Field( - description='Specifies the event type. For a drag action, this property is \nalways set to `drag`.\n' - ), - ] - path: Annotated[ - List[DragPoint], - Field( - description='An array of coordinates representing the path of the drag action. Coordinates will appear as an array\nof objects, eg\n```\n[\n { x: 100, y: 200 },\n { x: 200, y: 300 }\n]\n```\n' - ), - ] - - -class EvalGraderPython(GraderPython): - pass_threshold: Annotated[ - Optional[float], Field(description='The threshold for the score.') - ] = None - type: Literal['EvalGraderPython'] - - -class EvalGraderStringCheck(GraderStringCheck): - type: Literal['EvalGraderStringCheck'] - - -class EvalGraderTextSimilarity(GraderTextSimilarity): - pass_threshold: Annotated[float, Field(description='The threshold for the score.')] - type: Literal['EvalGraderTextSimilarity'] - - -class EvalItem(BaseModel): - role: Annotated[ - Literal['user', 'assistant', 'system', 'developer'], - Field( - description='The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n' - ), - ] - content: Annotated[ - Union[str, InputTextContent, Content7, Content8, InputAudioModel, List], - Field(description='Inputs to the model - can contain template strings.\n'), - ] - type: Annotated[ - Optional[Literal['message']], - Field(description='The type of the message input. Always `message`.\n'), - ] = None - - -class EvalLogsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['EvalLogsDataSourceConfig'], - Field(description='The type of data source. Always `logs`.'), - ] - metadata: Optional[Metadata] = None - schema_: Annotated[ - Dict[str, Any], - Field( - alias='schema', - description='The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n', - ), - ] - - -class EvalResponsesSource(BaseModel): - type: Annotated[ - Literal['EvalResponsesSource'], - Field(description='The type of run data source. Always `responses`.'), - ] - metadata: Optional[Dict[str, Any]] = None - model: Optional[str] = None - instructions_search: Optional[str] = None - created_after: Optional[CreatedAfter] = None - created_before: Optional[CreatedBefore] = None - reasoning_effort: Optional[ReasoningEffort] = None - temperature: Optional[float] = None - top_p: Optional[float] = None - users: Optional[List[str]] = None - tools: Optional[List[str]] = None - - -class EvalRunOutputItem(BaseModel): - object: Annotated[ - Literal['eval.run.output_item'], - Field(description='The type of the object. Always "eval.run.output_item".'), - ] - id: Annotated[ - str, Field(description='Unique identifier for the evaluation run output item.') - ] - run_id: Annotated[ - str, - Field( - description='The identifier of the evaluation run associated with this output item.' - ), - ] - eval_id: Annotated[ - str, Field(description='The identifier of the evaluation group.') - ] - created_at: Annotated[ - int, - Field( - description='Unix timestamp (in seconds) when the evaluation run was created.' - ), - ] - status: Annotated[str, Field(description='The status of the evaluation run.')] - datasource_item_id: Annotated[ - int, Field(description='The identifier for the data source item.') - ] - datasource_item: Annotated[ - Dict[str, Any], Field(description='Details of the input data source item.') - ] - results: Annotated[ - List[EvalRunOutputItemResult], - Field(description='A list of grader results for this output item.'), - ] - sample: Annotated[ - Sample, - Field( - description='A sample containing the input and output of the evaluation run.' - ), - ] +class CreateChatCompletionImageResponse(BaseModel): + pass -class EvalRunOutputItemList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[ - List[EvalRunOutputItem], - Field(description='An array of eval run output item objects.\n'), - ] - first_id: Annotated[ - str, - Field( - description='The identifier of the first eval run output item in the data array.' - ), - ] - last_id: Annotated[ +class CreateImageRequest(BaseModel): + prompt: Annotated[ str, Field( - description='The identifier of the last eval run output item in the data array.' + description="A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.", + examples=["A cute baby sea otter"], ), ] - has_more: Annotated[ - bool, + model: Annotated[ + Optional[Union[Optional[str], Literal["dall-e-2", "dall-e-3"]]], + Field(description="The model to use for image generation.", examples=["dall-e-3"]), + ] = "dall-e-2" + n: Annotated[ + Optional[int], Field( - description='Indicates whether there are more eval run output items available.' + description="The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.", + examples=[1], + ge=1, + le=10, ), - ] - - -class EvalStoredCompletionsDataSourceConfig(BaseModel): - type: Annotated[ - Literal['EvalStoredCompletionsDataSourceConfig'], - Field(description='The type of data source. Always `stored_completions`.'), - ] - metadata: Optional[Metadata] = None - schema_: Annotated[ - Dict[str, Any], + ] = 1 + quality: Annotated[ + Literal["standard", "hd"], Field( - alias='schema', - description='The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n', + description="The quality of the image that will be generated. `hd` creates images with finer details and greater consistency across the image. This param is only supported for `dall-e-3`.", + examples=["standard"], ), - ] - - -class EvalStoredCompletionsSource(BaseModel): - type: Annotated[ - Literal['EvalStoredCompletionsSource'], - Field(description='The type of source. Always `stored_completions`.'), - ] - metadata: Optional[Metadata] = None - model: Optional[str] = None - created_after: Optional[int] = None - created_before: Optional[int] = None - limit: Optional[int] = None - - -class Result1(BaseModel): - file_id: Annotated[ - Optional[str], Field(description='The unique ID of the file.\n') - ] = None - text: Annotated[ - Optional[str], Field(description='The text that was retrieved from the file.\n') - ] = None - filename: Annotated[Optional[str], Field(description='The name of the file.\n')] = ( - None - ) - attributes: Optional[VectorStoreFileAttributes] = None - score: Annotated[ - Optional[float], + ] = "standard" + response_format: Annotated[ + Optional[Literal["url", "b64_json"]], Field( - description='The relevance score of the file - a value between 0 and 1.\n' + description="The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.", + examples=["url"], ), - ] = None - - -class FileSearchToolCall(BaseModel): - id: Annotated[ - str, Field(description='The unique ID of the file search tool call.\n') - ] - type: Annotated[ - Literal['FileSearchToolCall'], + ] = "url" + size: Annotated[ + Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]], Field( - description='The type of the file search tool call. Always `file_search_call`.\n' + description="The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models.", + examples=["1024x1024"], ), - ] - status: Annotated[ - Literal['in_progress', 'searching', 'completed', 'incomplete', 'failed'], + ] = "1024x1024" + style: Annotated[ + Optional[Literal["vivid", "natural"]], Field( - description='The status of the file search tool call. One of `in_progress`,\n`searching`, `incomplete` or `failed`,\n' + description="The style of the generated images. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for `dall-e-3`.", + examples=["vivid"], ), - ] - queries: Annotated[ - List[str], Field(description='The queries used to search for files.\n') - ] - results: Optional[List[Result1]] = None - - -class FunctionAndCustomToolCallOutput( - RootModel[Union[InputTextContent, InputImageContent, InputFileContent]] -): - root: Annotated[ - Union[InputTextContent, InputImageContent, InputFileContent], - Field(discriminator='type'), - ] - - -class FunctionObject(BaseModel): - description: Annotated[ + ] = "vivid" + user: Annotated[ Optional[str], Field( - description='A description of what the function does, used by the model to choose when and how to call the function.' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + examples=["user-1234"], ), ] = None - name: Annotated[ - str, - Field( - description='The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.' - ), - ] - parameters: Optional[FunctionParameters] = None - strict: Optional[bool] = None -class FunctionToolCallOutput(BaseModel): - id: Annotated[ +class Image(BaseModel): + b64_json: Annotated[ Optional[str], Field( - description='The unique ID of the function tool call output. Populated when this item\nis returned via API.\n' - ), - ] = None - type: Annotated[ - Literal['function_call_output'], - Field( - description='The type of the function tool call output. Always `function_call_output`.\n' - ), - ] - call_id: Annotated[ - str, - Field( - description='The unique ID of the function tool call generated by the model.\n' - ), - ] - output: Annotated[ - Union[str, List[FunctionAndCustomToolCallOutput]], - Field( - description='The output from the function call generated by your code.\nCan be a string or an list of output content.\n' - ), - ] - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' + description="The base64-encoded JSON of the generated image, if `response_format` is `b64_json`." ), ] = None - - -class FunctionToolCallOutputResource(FunctionToolCallOutput): - id: Annotated[ - str, Field(description='The unique ID of the function call tool output.\n') - ] - type: Literal['FunctionToolCallOutputResource'] - - -class GraderLabelModel(BaseModel): - type: Annotated[ - Literal['label_model'], - Field(description='The object type, which is always `label_model`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - model: Annotated[ - str, - Field( - description='The model to use for the evaluation. Must support structured outputs.' - ), - ] - input: List[EvalItem] - labels: Annotated[ - List[str], - Field(description='The labels to assign to each item in the evaluation.'), - ] - passing_labels: Annotated[ - List[str], + url: Annotated[ + Optional[str], Field( - description='The labels that indicate a passing result. Must be a subset of labels.' + description="The URL of the generated image, if `response_format` is `url` (default)." ), - ] - - -class SamplingParams2(BaseModel): - seed: Optional[int] = None - top_p: Optional[float] = None - temperature: Optional[float] = None - max_completions_tokens: Optional[MaxCompletionsTokens] = None - reasoning_effort: Optional[ReasoningEffort] = None - - -class GraderScoreModel(BaseModel): - type: Annotated[ - Literal['GraderScoreModel'], - Field(description='The object type, which is always `score_model`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - model: Annotated[str, Field(description='The model to use for the evaluation.')] - sampling_params: Annotated[ - Optional[SamplingParams2], - Field(description='The sampling parameters for the model.'), - ] = None - input: Annotated[ - List[EvalItem], - Field(description='The input text. This may include template strings.'), - ] - range: Annotated[ - Optional[List[float]], - Field(description='The range of the score. Defaults to `[0, 1]`.'), ] = None - - -class GroupListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[GroupResponse], Field(description='Groups returned in the current page.') - ] - has_more: Annotated[ - bool, - Field(description='Whether additional groups are available when paginating.'), - ] - next: Annotated[ + revised_prompt: Annotated[ Optional[str], Field( - description='Cursor to fetch the next page of results, or `null` if there are no more results.' + description="The prompt that was used to generate the image, if there was any revision to the prompt." ), ] = None -class GroupRoleAssignment(BaseModel): - object: Annotated[Literal['group.role'], Field(description='Always `group.role`.')] - group: Group - role: Role - - -class ImageEditCompletedEvent(BaseModel): - type: Annotated[ - Literal['ImageEditCompletedEvent'], - Field(description='The type of the event. Always `image_edit.completed`.\n'), - ] - b64_json: Annotated[ - str, - Field( - description='Base64-encoded final edited image data, suitable for rendering as an image.\n' - ), - ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the edited image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the edited image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the edited image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the edited image.\n'), - ] - usage: ImagesUsage - - -class ImageEditStreamEvent( - RootModel[Union[ImageEditPartialImageEvent, ImageEditCompletedEvent]] -): - root: Annotated[ - Union[ImageEditPartialImageEvent, ImageEditCompletedEvent], - Field(discriminator='type'), - ] - - -class ImageGenCompletedEvent(BaseModel): - type: Annotated[ - Literal['ImageGenCompletedEvent'], +class CreateImageEditRequest(BaseModel): + image: Annotated[ + bytes, Field( - description='The type of the event. Always `image_generation.completed`.\n' + description="The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask." ), ] - b64_json: Annotated[ + prompt: Annotated[ str, Field( - description='Base64-encoded image data, suitable for rendering as an image.\n' + description="A text description of the desired image(s). The maximum length is 1000 characters.", + examples=["A cute baby sea otter wearing a beret"], ), ] - created_at: Annotated[ - int, Field(description='The Unix timestamp when the event was created.\n') - ] - size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field(description='The size of the generated image.\n'), - ] - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], - Field(description='The quality setting for the generated image.\n'), - ] - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], - Field(description='The background setting for the generated image.\n'), - ] - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], - Field(description='The output format for the generated image.\n'), - ] - usage: ImagesUsage - - -class ImageGenStreamEvent( - RootModel[Union[ImageGenPartialImageEvent, ImageGenCompletedEvent]] -): - root: Annotated[ - Union[ImageGenPartialImageEvent, ImageGenCompletedEvent], - Field(discriminator='type'), - ] - - -class ImageGenTool(BaseModel): - type: Annotated[ - Literal['ImageGenTool'], + mask: Annotated[ + Optional[bytes], Field( - description='The type of the image generation tool. Always `image_generation`.\n' + description="An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`." ), - ] + ] = None model: Annotated[ - Literal['gpt-image-1', 'gpt-image-1-mini'], + Optional[Union[Optional[str], Literal["dall-e-2"]]], Field( - description='The image generation model to use. Default: `gpt-image-1`.\n' + description="The model to use for image generation. Only `dall-e-2` is supported at this time.", + examples=["dall-e-2"], ), - ] = 'gpt-image-1' - quality: Annotated[ - Literal['low', 'medium', 'high', 'auto'], + ] = "dall-e-2" + n: Annotated[ + Optional[int], Field( - description='The quality of the generated image. One of `low`, `medium`, `high`,\nor `auto`. Default: `auto`.\n' + description="The number of images to generate. Must be between 1 and 10.", + examples=[1], + ge=1, + le=10, ), - ] = 'auto' + ] = 1 size: Annotated[ - Literal['1024x1024', '1024x1536', '1536x1024', 'auto'], - Field( - description='The size of the generated image. One of `1024x1024`, `1024x1536`,\n`1536x1024`, or `auto`. Default: `auto`.\n' - ), - ] = 'auto' - output_format: Annotated[ - Literal['png', 'webp', 'jpeg'], + Optional[Literal["256x256", "512x512", "1024x1024"]], Field( - description='The output format of the generated image. One of `png`, `webp`, or\n`jpeg`. Default: `png`.\n' + description="The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.", + examples=["1024x1024"], ), - ] = 'png' - output_compression: Annotated[ - int, - Field( - description='Compression level for the output image. Default: 100.\n', - ge=0, - le=100, - ), - ] = 100 - moderation: Annotated[ - Literal['auto', 'low'], - Field( - description='Moderation level for the generated image. Default: `auto`.\n' - ), - ] = 'auto' - background: Annotated[ - Literal['transparent', 'opaque', 'auto'], + ] = "1024x1024" + response_format: Annotated[ + Optional[Literal["url", "b64_json"]], Field( - description='Background type for the generated image. One of `transparent`,\n`opaque`, or `auto`. Default: `auto`.\n' + description="The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.", + examples=["url"], ), - ] = 'auto' - input_fidelity: Optional[InputFidelity] = None - input_image_mask: Annotated[ - Optional[InputImageMask], + ] = "url" + user: Annotated[ + Optional[str], Field( - description='Optional mask for inpainting. Contains `image_url`\n(string, optional) and `file_id` (string, optional).\n' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + examples=["user-1234"], ), ] = None - partial_images: Annotated[ - int, - Field( - description='Number of partial images to generate in streaming mode, from 0 (default value) to 3.\n', - ge=0, - le=3, - ), - ] = 0 -class ImagesResponse(BaseModel): - created: Annotated[ - int, +class CreateImageVariationRequest(BaseModel): + image: Annotated[ + bytes, Field( - description='The Unix timestamp (in seconds) of when the image was created.' + description="The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square." ), ] - data: Annotated[ - Optional[List[Image1]], Field(description='The list of generated images.') - ] = None - background: Annotated[ - Optional[Literal['transparent', 'opaque']], - Field( - description='The background parameter used for the image generation. Either `transparent` or `opaque`.' - ), - ] = None - output_format: Annotated[ - Optional[Literal['png', 'webp', 'jpeg']], + model: Annotated[ + Optional[Union[Optional[str], Literal["dall-e-2"]]], Field( - description='The output format of the image generation. Either `png`, `webp`, or `jpeg`.' + description="The model to use for image generation. Only `dall-e-2` is supported at this time.", + examples=["dall-e-2"], ), - ] = None - size: Annotated[ - Optional[Literal['1024x1024', '1024x1536', '1536x1024']], + ] = "dall-e-2" + n: Annotated[ + Optional[int], Field( - description='The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`.' + description="The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.", + examples=[1], + ge=1, + le=10, ), - ] = None - quality: Annotated[ - Optional[Literal['low', 'medium', 'high']], + ] = 1 + response_format: Annotated[ + Optional[Literal["url", "b64_json"]], Field( - description='The quality of the image generated. Either `low`, `medium`, or `high`.' + description="The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.", + examples=["url"], ), - ] = None - usage: Optional[ImageGenUsage] = None - - -class InputContent( - RootModel[Union[InputTextContent, InputImageContent, InputFileContent]] -): - root: Annotated[ - Union[InputTextContent, InputImageContent, InputFileContent], - Field(discriminator='type'), - ] - - -class InputMessageContentList(RootModel[List[InputContent]]): - root: Annotated[ - List[InputContent], + ] = "url" + size: Annotated[ + Optional[Literal["256x256", "512x512", "1024x1024"]], Field( - description='A list of one or many input items to the model, containing different content \ntypes.\n', - title='Input item content list', + description="The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.", + examples=["1024x1024"], ), - ] - - -class ListBatchesResponse(BaseModel): - data: List[Batch] - first_id: Annotated[Optional[str], Field(examples=['batch_abc123'])] = None - last_id: Annotated[Optional[str], Field(examples=['batch_abc456'])] = None - has_more: bool - object: Literal['list'] - - -class ListFilesResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[OpenAIFile] - first_id: Annotated[str, Field(examples=['file-abc123'])] - last_id: Annotated[str, Field(examples=['file-abc456'])] - has_more: Annotated[bool, Field(examples=[False])] - - -class ListModelsResponse(BaseModel): - object: Literal['list'] - data: List[Model] + ] = "1024x1024" + user: Annotated[ + Optional[str], + Field( + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + examples=["user-1234"], + ), + ] = None -class ListVectorStoresResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[VectorStoreObject] - first_id: Annotated[str, Field(examples=['vs_abc123'])] - last_id: Annotated[str, Field(examples=['vs_abc456'])] - has_more: Annotated[bool, Field(examples=[False])] +class CreateModerationRequest(BaseModel): + input: Annotated[Union[str, List[str]], Field(description="The input text to classify")] + model: Annotated[ + Union[str, Literal["text-moderation-latest", "text-moderation-stable"]], + Field( + description="Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`.\n\nThe default is `text-moderation-latest` which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`.\n", + examples=["text-moderation-stable"], + ), + ] = "text-moderation-latest" -class LocalShellToolCall(BaseModel): - type: Annotated[ - Literal['LocalShellToolCall'], +class Categories(BaseModel): + hate: Annotated[ + bool, Field( - description='The type of the local shell call. Always `local_shell_call`.\n' + description="Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment." ), ] - id: Annotated[str, Field(description='The unique ID of the local shell call.\n')] - call_id: Annotated[ - str, + hate_threatening: Annotated[ + bool, Field( - description='The unique ID of the local shell tool call generated by the model.\n' + alias="hate/threatening", + description="Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.", ), ] - action: LocalShellExecAction - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], - Field(description='The status of the local shell call.\n'), - ] - - -class MCPListTools(BaseModel): - type: Annotated[ - Literal['MCPListTools'], - Field(description='The type of the item. Always `mcp_list_tools`.\n'), - ] - id: Annotated[str, Field(description='The unique ID of the list.\n')] - server_label: Annotated[str, Field(description='The label of the MCP server.\n')] - tools: Annotated[ - List[MCPListToolsTool], - Field(description='The tools available on the server.\n'), - ] - error: Optional[str] = None - - -class RequireApproval(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - always: Optional[MCPToolFilter] = None - never: Optional[MCPToolFilter] = None - - -class MCPTool(BaseModel): - type: Annotated[ - Literal['MCPTool'], Field(description='The type of the MCP tool. Always `mcp`.') + harassment: Annotated[ + bool, + Field( + description="Content that expresses, incites, or promotes harassing language towards any target." + ), ] - server_label: Annotated[ - str, + harassment_threatening: Annotated[ + bool, Field( - description='A label for this MCP server, used to identify it in tool calls.\n' + alias="harassment/threatening", + description="Harassment content that also includes violence or serious harm towards any target.", ), ] - server_url: Annotated[ - Optional[str], + self_harm: Annotated[ + bool, Field( - description='The URL for the MCP server. One of `server_url` or `connector_id` must be\nprovided.\n' + alias="self-harm", + description="Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.", ), - ] = None - connector_id: Annotated[ - Optional[ - Literal[ - 'connector_dropbox', - 'connector_gmail', - 'connector_googlecalendar', - 'connector_googledrive', - 'connector_microsoftteams', - 'connector_outlookcalendar', - 'connector_outlookemail', - 'connector_sharepoint', - ] - ], + ] + self_harm_intent: Annotated[ + bool, Field( - description='Identifier for service connectors, like those available in ChatGPT. One of\n`server_url` or `connector_id` must be provided. Learn more about service\nconnectors [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).\n\nCurrently supported `connector_id` values are:\n\n- Dropbox: `connector_dropbox`\n- Gmail: `connector_gmail`\n- Google Calendar: `connector_googlecalendar`\n- Google Drive: `connector_googledrive`\n- Microsoft Teams: `connector_microsoftteams`\n- Outlook Calendar: `connector_outlookcalendar`\n- Outlook Email: `connector_outlookemail`\n- SharePoint: `connector_sharepoint`\n' + alias="self-harm/intent", + description="Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders.", ), - ] = None - authorization: Annotated[ - Optional[str], + ] + self_harm_instructions: Annotated[ + bool, Field( - description='An OAuth access token that can be used with a remote MCP server, either\nwith a custom MCP server URL or a service connector. Your application\nmust handle the OAuth authorization flow and provide the token here.\n' + alias="self-harm/instructions", + description="Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts.", ), - ] = None - server_description: Annotated[ - Optional[str], + ] + sexual: Annotated[ + bool, Field( - description='Optional description of the MCP server, used to provide more context.\n' + description="Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness)." ), - ] = None - headers: Optional[Dict[str, str]] = None - allowed_tools: Optional[Union[List[str], MCPToolFilter]] = None - require_approval: Optional[Union[RequireApproval, Literal['always', 'never']]] = ( - None - ) - - -class MCPToolCall(BaseModel): - type: Annotated[ - Literal['MCPToolCall'], - Field(description='The type of the item. Always `mcp_call`.\n'), ] - id: Annotated[str, Field(description='The unique ID of the tool call.\n')] - server_label: Annotated[ - str, Field(description='The label of the MCP server running the tool.\n') + sexual_minors: Annotated[ + bool, + Field( + alias="sexual/minors", + description="Sexual content that includes an individual who is under 18 years old.", + ), ] - name: Annotated[str, Field(description='The name of the tool that was run.\n')] - arguments: Annotated[ - str, Field(description='A JSON string of the arguments passed to the tool.\n') + violence: Annotated[ + bool, + Field(description="Content that depicts death, violence, or physical injury."), ] - output: Optional[str] = None - error: Optional[str] = None - status: Annotated[ - Optional[MCPToolCallStatus], + violence_graphic: Annotated[ + bool, Field( - description='The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`.\n' + alias="violence/graphic", + description="Content that depicts death, violence, or physical injury in graphic detail.", ), - ] = None - approval_request_id: Optional[str] = None - - -class Text1(BaseModel): - value: Annotated[str, Field(description='The data that makes up the text.')] - annotations: List[TextAnnotation] - - -class MessageContentTextObject(BaseModel): - type: Annotated[ - Literal['MessageContentTextObject'], Field(description='Always `text`.') ] - text: Text1 -class Text2(BaseModel): - value: Annotated[ - Optional[str], Field(description='The data that makes up the text.') - ] = None - annotations: Optional[List[TextAnnotationDelta]] = None - - -class MessageDeltaContentTextObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the content part in the message.') +class CategoryScores(BaseModel): + hate: Annotated[float, Field(description="The score for the category 'hate'.")] + hate_threatening: Annotated[ + float, + Field( + alias="hate/threatening", + description="The score for the category 'hate/threatening'.", + ), ] - type: Annotated[ - Literal['MessageDeltaContentTextObject'], Field(description='Always `text`.') + harassment: Annotated[float, Field(description="The score for the category 'harassment'.")] + harassment_threatening: Annotated[ + float, + Field( + alias="harassment/threatening", + description="The score for the category 'harassment/threatening'.", + ), ] - text: Optional[Text2] = None - - -class ModelIdsShared(RootModel[Union[str, ChatModel]]): - root: Annotated[Union[str, ChatModel], Field(examples=['gpt-4o'])] - - -class ModelResponseProperties(BaseModel): - metadata: Optional[Metadata] = None - top_logprobs: Optional[TopLogprobs] = None - temperature: Optional[Temperature2] = None - top_p: Optional[TopP2] = None - user: Annotated[ - Optional[str], + self_harm: Annotated[ + float, + Field(alias="self-harm", description="The score for the category 'self-harm'."), + ] + self_harm_intent: Annotated[ + float, Field( - description='This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n', - examples=['user-1234'], + alias="self-harm/intent", + description="The score for the category 'self-harm/intent'.", ), - ] = None - safety_identifier: Annotated[ - Optional[str], + ] + self_harm_instructions: Annotated[ + float, Field( - description="A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n", - examples=['safety-identifier-1234'], + alias="self-harm/instructions", + description="The score for the category 'self-harm/instructions'.", ), - ] = None - prompt_cache_key: Annotated[ - Optional[str], + ] + sexual: Annotated[float, Field(description="The score for the category 'sexual'.")] + sexual_minors: Annotated[ + float, Field( - description='Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n', - examples=['prompt-cache-key-1234'], + alias="sexual/minors", + description="The score for the category 'sexual/minors'.", + ), + ] + violence: Annotated[float, Field(description="The score for the category 'violence'.")] + violence_graphic: Annotated[ + float, + Field( + alias="violence/graphic", + description="The score for the category 'violence/graphic'.", ), - ] = None - service_tier: Optional[ServiceTier] = None - prompt_cache_retention: Optional[Literal['in-memory', '24h']] = None - - -class OutputContent( - RootModel[Union[OutputTextContent, RefusalContent, ReasoningTextContent]] -): - root: Annotated[ - Union[OutputTextContent, RefusalContent, ReasoningTextContent], - Field(discriminator='type'), ] -class OutputMessageContent(RootModel[Union[OutputTextContent, RefusalContent]]): - root: Annotated[ - Union[OutputTextContent, RefusalContent], Field(discriminator='type') +class Result(BaseModel): + flagged: Annotated[bool, Field(description="Whether any of the below categories are flagged.")] + categories: Annotated[ + Categories, + Field(description="A list of the categories, and whether they are flagged or not."), + ] + category_scores: Annotated[ + CategoryScores, + Field( + description="A list of the categories along with their scores as predicted by model." + ), ] -class Owner1(BaseModel): - type: Annotated[ - Optional[Literal['user', 'service_account']], - Field(description='`user` or `service_account`'), - ] = None - user: Optional[ProjectUser] = None - service_account: Optional[ProjectServiceAccount] = None +class CreateModerationResponse(BaseModel): + id: Annotated[str, Field(description="The unique identifier for the moderation request.")] + model: Annotated[str, Field(description="The model used to generate the moderation results.")] + results: Annotated[List[Result], Field(description="A list of moderation objects.")] -class ProjectApiKey(BaseModel): - object: Annotated[ - Literal['organization.project.api_key'], +class CreateFileRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + file: Annotated[bytes, Field(description="The File object (not file name) to be uploaded.\n")] + purpose: Annotated[ + Literal["assistants", "batch", "fine-tune", "vision"], Field( - description='The object type, which is always `organization.project.api_key`' + description='The intended purpose of the uploaded file.\n\nUse "assistants" for [Assistants](/docs/api-reference/assistants) and [Message](/docs/api-reference/messages) files, "vision" for Assistants image file inputs, "batch" for [Batch API](/docs/guides/batch), and "fine-tune" for [Fine-tuning](/docs/api-reference/fine-tuning).\n' ), ] - redacted_value: Annotated[ - str, Field(description='The redacted value of the API key') - ] - name: Annotated[str, Field(description='The name of the API key')] - created_at: Annotated[ - int, + + +class DeleteFileResponse(BaseModel): + id: str + object: Literal["file"] + deleted: bool + + +class CreateUploadRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + filename: Annotated[str, Field(description="The name of the file to upload.\n")] + purpose: Annotated[ + Literal["assistants", "batch", "fine-tune", "vision"], Field( - description='The Unix timestamp (in seconds) of when the API key was created' + description="The intended purpose of the uploaded file.\n\nSee the [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose).\n" ), ] - last_used_at: Annotated[ - int, + bytes: Annotated[int, Field(description="The number of bytes in the file you are uploading.\n")] + mime_type: Annotated[ + str, Field( - description='The Unix timestamp (in seconds) of when the API key was last used.' + description="The MIME type of the file.\n\nThis must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision.\n" ), ] - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints'), - ] - owner: Owner1 -class ProjectApiKeyListResponse(BaseModel): - object: Literal['list'] - data: List[ProjectApiKey] - first_id: str - last_id: str - has_more: bool +class AddUploadPartRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + data: Annotated[bytes, Field(description="The chunk of bytes for this Part.\n")] -class PublicRoleListResource(BaseModel): - object: Annotated[Literal['list'], Field(description='Always `list`.')] - data: Annotated[ - List[Role], Field(description='Roles returned in the current page.') - ] - has_more: Annotated[ - bool, Field(description='Whether more roles are available when paginating.') - ] - next: Annotated[ +class CompleteUploadRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + part_ids: Annotated[List[str], Field(description="The ordered list of Part IDs.\n")] + md5: Annotated[ Optional[str], Field( - description='Cursor to fetch the next page of results, or `null` when there are no additional roles.' + description="The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n" ), ] = None -class RealtimeBetaClientEventTranscriptionSessionUpdate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['transcription_session.update'], - Field(description='The event type, must be `transcription_session.update`.'), - ] - session: RealtimeTranscriptionSessionCreateRequest +class CancelUploadRequest(BaseModel): + pass + model_config = ConfigDict( + extra="forbid", + ) -class RealtimeBetaServerEventConversationItemInputAudioTranscriptionCompleted( - BaseModel -): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.input_audio_transcription.completed'], +class BatchSize(RootModel[int]): + root: Annotated[ + int, Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.completed`.\n' + description="Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n", + ge=1, + le=256, ), ] - item_id: Annotated[ - str, Field(description='The ID of the user message item containing the audio.') - ] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - transcript: Annotated[str, Field(description='The transcribed text.')] - logprobs: Optional[List[LogProbProperties]] = None - usage: Annotated[ - Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration], - Field(description='Usage statistics for the transcription.'), - ] -class RealtimeBetaServerEventTranscriptionSessionCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['transcription_session.created'], - Field(description='The event type, must be `transcription_session.created`.'), +class LearningRateMultiplier(RootModel[float]): + root: Annotated[ + float, + Field( + description="Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n", + gt=0.0, + ), ] - session: RealtimeTranscriptionSessionCreateResponse -class RealtimeBetaServerEventTranscriptionSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['transcription_session.updated'], - Field(description='The event type, must be `transcription_session.updated`.'), +class NEpochs(RootModel[int]): + root: Annotated[ + int, + Field( + description="The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n", + ge=1, + le=50, + ), ] - session: RealtimeTranscriptionSessionCreateResponse -class RealtimeClientEventTranscriptionSessionUpdate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), - ] = None - type: Annotated[ - Literal['transcription_session.update'], - Field(description='The event type, must be `transcription_session.update`.'), - ] - session: RealtimeTranscriptionSessionCreateRequest +class Hyperparameters(BaseModel): + batch_size: Annotated[ + Union[Literal["auto"], BatchSize], + Field( + description="Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n" + ), + ] = "auto" + learning_rate_multiplier: Annotated[ + Union[Literal["auto"], LearningRateMultiplier], + Field( + description="Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n" + ), + ] = "auto" + n_epochs: Annotated[ + Union[Literal["auto"], NEpochs], + Field( + description="The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n" + ), + ] = "auto" -class RealtimeMCPToolCall(BaseModel): - type: Annotated[ - Literal['RealtimeMCPToolCall'], - Field(description='The type of the item. Always `mcp_call`.'), - ] - id: Annotated[str, Field(description='The unique ID of the tool call.')] - server_label: Annotated[ - str, Field(description='The label of the MCP server running the tool.') - ] - name: Annotated[str, Field(description='The name of the tool that was run.')] - arguments: Annotated[ - str, Field(description='A JSON string of the arguments passed to the tool.') +class Wandb(BaseModel): + project: Annotated[ + str, + Field( + description="The name of the project that the new run will be created under.\n", + examples=["my-wandb-project"], + ), ] - approval_request_id: Optional[str] = None - output: Optional[str] = None - error: Optional[ - Union[ - RealtimeMCPProtocolError, - RealtimeMCPToolExecutionError, - RealtimeMCPHTTPError, - ] + name: Annotated[ + Optional[str], + Field( + description="A display name to set for the run. If not set, we will use the Job ID as the name.\n" + ), ] = None - - -class Output(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the output audio.'), + entity: Annotated[ + Optional[str], + Field( + description="The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n" + ), ] = None - voice: Annotated[ - VoiceIdsShared, + tags: Annotated[ + Optional[List[str]], Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n' + description='A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}".\n' ), - ] = 'alloy' - - -class Audio3(BaseModel): - output: Optional[Output] = None - - -class Audio4(BaseModel): - output: Optional[Output] = None + ] = None -class RealtimeServerEventConversationItemInputAudioTranscriptionCompleted(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] +class Integration(BaseModel): type: Annotated[ - Literal['RealtimeServerEventConversationItemInputAudioTranscriptionCompleted'], + Literal["wandb"], Field( - description='The event type, must be\n`conversation.item.input_audio_transcription.completed`.\n' + description='The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported.\n' ), ] - item_id: Annotated[ - str, + wandb: Annotated[ + Wandb, Field( - description='The ID of the item containing the audio that is being transcribed.' + description="The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n" ), ] - content_index: Annotated[ - int, Field(description='The index of the content part containing the audio.') - ] - transcript: Annotated[str, Field(description='The transcribed text.')] - logprobs: Optional[List[LogProbProperties]] = None - usage: Annotated[ - Union[TranscriptTextUsageTokens, TranscriptTextUsageDuration], + + +class CreateFineTuningJobRequest(BaseModel): + model: Annotated[ + Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"]], Field( - description="Usage statistics for the transcription, this is billed according to the ASR model's pricing rather than the realtime model's pricing." + description="The name of the model to fine-tune. You can select one of the\n[supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned).\n", + examples=["gpt-4o-mini"], ), ] - - -class RealtimeServerEventTranscriptionSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['transcription_session.updated'], - Field(description='The event type, must be `transcription_session.updated`.'), + training_file: Annotated[ + str, + Field( + description="The ID of an uploaded file that contains training data.\n\nSee [upload file](/docs/api-reference/files/create) for how to upload a file.\n\nYour dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n\nThe contents of the file should differ depending on if the model uses the [chat](/docs/api-reference/fine-tuning/chat-input) or [completions](/docs/api-reference/fine-tuning/completions-input) format.\n\nSee the [fine-tuning guide](/docs/guides/fine-tuning) for more details.\n", + examples=["file-abc123"], + ), ] - session: RealtimeTranscriptionSessionCreateResponse - - -class Input5(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the input audio.'), + hyperparameters: Annotated[ + Optional[Hyperparameters], + Field(description="The hyperparameters used for the fine-tuning job."), ] = None - transcription: Annotated[ - Optional[AudioTranscription], + suffix: Annotated[ + Optional[str], Field( - description='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.\n' + description='A string of up to 18 characters that will be added to your fine-tuned model name.\n\nFor example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n', + max_length=40, + min_length=1, ), ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], + validation_file: Annotated[ + Optional[str], Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' + description="The ID of an uploaded file that contains validation data.\n\nIf you provide this file, the data is used to generate validation\nmetrics periodically during fine-tuning. These metrics can be viewed in\nthe fine-tuning results file.\nThe same data should not be present in both train and validation files.\n\nYour dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n\nSee the [fine-tuning guide](/docs/guides/fine-tuning) for more details.\n", + examples=["file-abc123"], ), ] = None - turn_detection: Optional[RealtimeTurnDetection] = None - - -class Output2(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the output audio.'), + integrations: Annotated[ + Optional[List[Integration]], + Field(description="A list of integrations to enable for your fine-tuning job."), ] = None - voice: Annotated[ - VoiceIdsShared, - Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n' - ), - ] = 'alloy' - speed: Annotated[ - float, + seed: Annotated[ + Optional[int], Field( - description="The speed of the model's spoken response as a multiple of the original speed.\n1.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.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n", - ge=0.25, - le=1.5, + description="The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\nIf a seed is not specified, one will be generated for you.\n", + examples=[42], + ge=0, + le=2147483647, ), - ] = 1 + ] = None -class Audio5(BaseModel): - input: Optional[Input5] = None - output: Optional[Output2] = None +class Input(RootModel[List[str]]): + root: Annotated[ + List[str], + Field( + description="The array of strings that will be turned into an embedding.", + examples=["The quick brown fox jumped over the lazy dog"], + max_length=2048, + min_length=1, + title="array", + ), + ] -class Tools2(RootModel[Union[RealtimeFunctionTool, MCPTool]]): - root: Annotated[Union[RealtimeFunctionTool, MCPTool], Field(discriminator='type')] +class Input1(RootModel[List[int]]): + root: Annotated[ + List[int], + Field( + description="The array of integers that will be turned into an embedding.", + examples=["[1212, 318, 257, 1332, 13]"], + max_length=2048, + min_length=1, + title="array", + ), + ] -class Output3(BaseModel): - format: Optional[RealtimeAudioFormats] = None - voice: Optional[VoiceIdsShared] = None - speed: Optional[float] = None +class Input2Item(RootModel[List[int]]): + root: Annotated[List[int], Field(min_length=1)] -class Audio6(BaseModel): - input: Optional[Input6] = None - output: Optional[Output3] = None +class Input2(RootModel[List[Input2Item]]): + root: Annotated[ + List[Input2Item], + Field( + description="The array of arrays containing integers that will be turned into an embedding.", + examples=["[[1212, 318, 257, 1332, 13]]"], + max_length=2048, + min_length=1, + title="array", + ), + ] -class RealtimeSessionCreateResponse(BaseModel): - id: Annotated[ - Optional[str], +class CreateEmbeddingRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + input: Annotated[ + Union[str, Input, Input1, Input2], Field( - description='Unique identifier for the session that looks like `sess_1234567890abcdef`.\n' + description="Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n", + examples=["The quick brown fox jumped over the lazy dog"], ), - ] = None - object: Annotated[ - Optional[str], Field(description='The object type. Always `realtime.session`.') - ] = None - expires_at: Annotated[ - Optional[int], + ] + model: Annotated[ + Union[ + str, + Literal[ + "text-embedding-ada-002", + "text-embedding-3-small", + "text-embedding-3-large", + ], + ], Field( - description='Expiration timestamp for the session, in seconds since epoch.' + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n", + examples=["text-embedding-3-small"], ), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], + ] + encoding_format: Annotated[ + Literal["float", "base64"], Field( - description='Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' + description="The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).", + examples=["float"], ), - ] = None - model: Annotated[ - Optional[str], Field(description='The Realtime model used for this session.') - ] = None - output_modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], + ] = "float" + dimensions: Annotated[ + Optional[int], Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' + description="The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n", + ge=1, ), ] = None - instructions: Annotated[ + user: Annotated[ Optional[str], Field( - description='The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. "be extremely succinct", "act friendly", "here are examples of good\nresponses") and on audio behavior (e.g. "talk quickly", "inject emotion\ninto your voice", "laugh frequently"). The instructions are not guaranteed\nto be followed by the model, but they provide guidance to the model on the\ndesired behavior.\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n' - ), - ] = None - audio: Annotated[ - Optional[Audio6], - Field( - description='Configuration for input and output audio for the session.\n' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + examples=["user-1234"], ), ] = None - tracing: Annotated[ - Optional[Union[Literal['auto'], Tracing3]], + + +class Usage1(BaseModel): + prompt_tokens: Annotated[int, Field(description="The number of tokens used by the prompt.")] + total_tokens: Annotated[ + int, Field(description="The total number of tokens used by the request.") + ] + + +class CreateTranscriptionRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + file: Annotated[ + bytes, Field( - description='Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n', - title='Tracing Configuration', + description="The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n" ), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection2], + ] + model: Annotated[ + Union[str, Literal["whisper-1"]], Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' + description="ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n", + examples=["whisper-1"], ), - ] = None - tools: Annotated[ - Optional[List[RealtimeFunctionTool]], - Field(description='Tools (functions) available to the model.'), - ] = None - tool_choice: Annotated[ + ] + language: Annotated[ Optional[str], Field( - description='How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n' - ), - ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="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) format will improve accuracy and latency.\n" ), ] = None - - -class Input7(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the input audio.'), - ] = None - transcription: Annotated[ - Optional[AudioTranscription], + prompt: Annotated[ + Optional[str], Field( - description='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.\n' + description="An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language.\n" ), ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], + response_format: Annotated[ + Literal["json", "text", "srt", "verbose_json", "vtt"], Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' + description="The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n" ), - ] = None - turn_detection: Optional[RealtimeTurnDetection] = None - - -class Output4(BaseModel): - format: Annotated[ - Optional[RealtimeAudioFormats], - Field(description='The format of the output audio.'), - ] = None - voice: Annotated[ - VoiceIdsShared, + ] = "json" + temperature: Annotated[ + float, Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n' + description="The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n" ), - ] = 'alloy' - speed: Annotated[ - float, + ] = 0 + timestamp_granularities__: Annotated[ + List[Literal["word", "segment"]], Field( - description="The speed of the model's spoken response as a multiple of the original speed.\n1.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.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n", - ge=0.25, - le=1.5, + alias="timestamp_granularities[]", + description="The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\n", ), - ] = 1 + ] = ["segment"] -class Audio7(BaseModel): - input: Optional[Input7] = None - output: Optional[Output4] = None +class CreateTranscriptionResponseJson(BaseModel): + text: Annotated[str, Field(description="The transcribed text.")] -class Input8(BaseModel): - format: Optional[RealtimeAudioFormats] = None - transcription: Annotated[ - Optional[AudioTranscription], - Field( - description='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.\n' - ), - ] = None - noise_reduction: Annotated[ - Optional[NoiseReduction], +class TranscriptionSegment(BaseModel): + id: Annotated[int, Field(description="Unique identifier of the segment.")] + seek: Annotated[int, Field(description="Seek offset of the segment.")] + start: Annotated[float, Field(description="Start time of the segment in seconds.")] + end: Annotated[float, Field(description="End time of the segment in seconds.")] + text: Annotated[str, Field(description="Text content of the segment.")] + tokens: Annotated[List[int], Field(description="Array of token IDs for the text content.")] + temperature: Annotated[ + float, + Field(description="Temperature parameter used for generating the segment."), + ] + avg_logprob: Annotated[ + float, Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' + description="Average logprob of the segment. If the value is lower than -1, consider the logprobs failed." ), - ] = None - turn_detection: Optional[RealtimeTurnDetection] = None - - -class Audio8(BaseModel): - input: Optional[Input8] = None - - -class RealtimeTranscriptionSessionCreateRequestGA(BaseModel): - type: Annotated[ - Literal['RealtimeTranscriptionSessionCreateRequestGA'], + ] + compression_ratio: Annotated[ + float, Field( - description='The type of session to create. Always `transcription` for transcription sessions.\n' + description="Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed." ), ] - audio: Annotated[ - Optional[Audio8], - Field(description='Configuration for input and output audio.\n'), - ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], + no_speech_prob: Annotated[ + float, Field( - description='Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' + description="Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent." ), - ] = None + ] -class Reasoning(BaseModel): - effort: Optional[ReasoningEffort] = None - summary: Optional[Literal['auto', 'concise', 'detailed']] = None - generate_summary: Optional[Literal['auto', 'concise', 'detailed']] = None +class TranscriptionWord(BaseModel): + word: Annotated[str, Field(description="The text content of the word.")] + start: Annotated[float, Field(description="Start time of the word in seconds.")] + end: Annotated[float, Field(description="End time of the word in seconds.")] -class ReasoningItem(BaseModel): - type: Annotated[ - Literal['ReasoningItem'], - Field(description='The type of the object. Always `reasoning`.\n'), - ] - id: Annotated[ - str, Field(description='The unique identifier of the reasoning content.\n') - ] - encrypted_content: Optional[str] = None - summary: Annotated[List[Summary], Field(description='Reasoning summary content.\n')] - content: Annotated[ - Optional[List[ReasoningTextContent]], - Field(description='Reasoning text content.\n'), +class CreateTranscriptionResponseVerboseJson(BaseModel): + language: Annotated[str, Field(description="The language of the input audio.")] + duration: Annotated[str, Field(description="The duration of the input audio.")] + text: Annotated[str, Field(description="The transcribed text.")] + words: Annotated[ + Optional[List[TranscriptionWord]], + Field(description="Extracted words and their corresponding timestamps."), ] = None - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], - Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' - ), + segments: Annotated[ + Optional[List[TranscriptionSegment]], + Field(description="Segments of the transcribed text and their corresponding details."), ] = None -class ResponseContentPartAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseContentPartAddedEvent'], - Field( - description='The type of the event. Always `response.content_part.added`.\n' - ), - ] - item_id: Annotated[ - str, +class CreateTranslationRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + file: Annotated[ + bytes, Field( - description='The ID of the output item that the content part was added to.\n' + description="The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n" ), ] - output_index: Annotated[ - int, + model: Annotated[ + Union[str, Literal["whisper-1"]], Field( - description='The index of the output item that the content part was added to.\n' + description="ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n", + examples=["whisper-1"], ), ] - content_index: Annotated[ - int, Field(description='The index of the content part that was added.\n') - ] - part: Annotated[ - OutputContent, Field(description='The content part that was added.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - - -class ResponseContentPartDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseContentPartDoneEvent'], + prompt: Annotated[ + Optional[str], Field( - description='The type of the event. Always `response.content_part.done`.\n' + description="An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English.\n" ), - ] - item_id: Annotated[ + ] = None + response_format: Annotated[ str, Field( - description='The ID of the output item that the content part was added to.\n' + description="The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n" ), - ] - output_index: Annotated[ - int, + ] = "json" + temperature: Annotated[ + float, Field( - description='The index of the output item that the content part was added to.\n' + description="The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n" ), - ] - content_index: Annotated[ - int, Field(description='The index of the content part that is done.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - part: Annotated[ - OutputContent, Field(description='The content part that is done.\n') - ] + ] = 0 -class ResponseError1(BaseModel): - code: ResponseErrorCode - message: Annotated[ - str, Field(description='A human-readable description of the error.\n') - ] +class CreateTranslationResponseJson(BaseModel): + text: str -class ResponseError(RootModel[Optional[ResponseError1]]): - root: Optional[ResponseError1] +class CreateTranslationResponseVerboseJson(BaseModel): + language: Annotated[ + str, + Field(description="The language of the output translation (always `english`)."), + ] + duration: Annotated[str, Field(description="The duration of the input audio.")] + text: Annotated[str, Field(description="The translated text.")] + segments: Annotated[ + Optional[List[TranscriptionSegment]], + Field(description="Segments of the translated text and their corresponding details."), + ] = None -class JsonSchema(BaseModel): - description: Annotated[ - Optional[str], +class CreateSpeechRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + model: Annotated[ + Union[str, Literal["tts-1", "tts-1-hd"]], Field( - description='A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n' + description="One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd`\n" ), - ] = None - name: Annotated[ + ] + input: Annotated[ str, Field( - description='The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n' + description="The text to generate audio for. The maximum length is 4096 characters.", + max_length=4096, + ), + ] + voice: Annotated[ + Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], + Field( + description="The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech/voice-options)." ), ] - schema_: Annotated[ - Optional[ResponseFormatJsonSchemaSchema], Field(alias='schema') - ] = None - strict: Optional[bool] = None - - -class ResponseFormatJsonSchema(BaseModel): - type: Annotated[ - Literal['ResponseFormatJsonSchema'], + response_format: Annotated[ + Literal["mp3", "opus", "aac", "flac", "wav", "pcm"], Field( - description='The type of response format being defined. Always `json_schema`.' + description="The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." ), - ] - json_schema: Annotated[ - JsonSchema, + ] = "mp3" + speed: Annotated[ + float, Field( - description='Structured Outputs configuration options, including a JSON Schema.\n', - title='JSON schema', + description="The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default.", + ge=0.25, + le=4.0, ), - ] + ] = 1.0 -class ResponsePromptVariables( - RootModel[ - Optional[ - Dict[str, Union[str, InputTextContent, InputImageContent, InputFileContent]] - ] +class Model(BaseModel): + id: Annotated[ + str, + Field(description="The model identifier, which can be referenced in the API endpoints."), ] -): - root: Optional[ - Dict[str, Union[str, InputTextContent, InputImageContent, InputFileContent]] + created: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) when the model was created."), ] - - -class SubmitToolOutputs(BaseModel): - tool_calls: Annotated[ - List[RunToolCallObject], Field(description='A list of the relevant tool calls.') + object: Annotated[ + Literal["model"], Field(description='The object type, which is always "model".') ] + owned_by: Annotated[str, Field(description="The organization that owns the model.")] -class RequiredAction(BaseModel): - type: Annotated[ - Literal['submit_tool_outputs'], - Field(description='For now, this is always `submit_tool_outputs`.'), +class OpenAIFile(BaseModel): + id: Annotated[ + str, + Field(description="The file identifier, which can be referenced in the API endpoints."), ] - submit_tool_outputs: Annotated[ - SubmitToolOutputs, - Field( - description='Details on the tool outputs needed for this run to continue.' - ), + bytes: Annotated[int, Field(description="The size of the file, in bytes.")] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the file was created."), ] - - -class Outputs1( - RootModel[ - Union[ - RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, - RunStepDeltaStepDetailsToolCallsCodeOutputImageObject, - ] + filename: Annotated[str, Field(description="The name of the file.")] + object: Annotated[ + Literal["file"], Field(description="The object type, which is always `file`.") ] -): - root: Annotated[ - Union[ - RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, - RunStepDeltaStepDetailsToolCallsCodeOutputImageObject, + purpose: Annotated[ + Literal[ + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", ], - Field(discriminator='type'), + Field( + description="The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`." + ), ] - - -class CodeInterpreter6(BaseModel): - input: Annotated[ - Optional[str], Field(description='The input to the Code Interpreter tool call.') - ] = None - outputs: Annotated[ - Optional[List[Outputs1]], + status: Annotated[ + Literal["uploaded", "processed", "error"], Field( - description='The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.' + description="Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`." + ), + ] + status_details: Annotated[ + Optional[str], + Field( + description="Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`." ), ] = None -class RunStepDeltaStepDetailsToolCallsCodeObject(BaseModel): - index: Annotated[ - int, Field(description='The index of the tool call in the tool calls array.') +class Upload(BaseModel): + id: Annotated[ + str, + Field( + description="The Upload unique identifier, which can be referenced in API endpoints." + ), ] - id: Annotated[Optional[str], Field(description='The ID of the tool call.')] = None - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsCodeObject'], + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the Upload was created."), + ] + filename: Annotated[str, Field(description="The name of the file to be uploaded.")] + bytes: Annotated[int, Field(description="The intended number of bytes to be uploaded.")] + purpose: Annotated[ + str, Field( - description='The type of tool call. This is always going to be `code_interpreter` for this type of tool call.' + description="The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values." ), ] - code_interpreter: Annotated[ - Optional[CodeInterpreter6], - Field(description='The Code Interpreter tool call definition.'), - ] = None - - -class Outputs2( - RootModel[ - Union[ - RunStepDetailsToolCallsCodeOutputLogsObject, - RunStepDetailsToolCallsCodeOutputImageObject, - ] + status: Annotated[ + Literal["pending", "completed", "cancelled", "expired"], + Field(description="The status of the Upload."), ] -): - root: Annotated[ - Union[ - RunStepDetailsToolCallsCodeOutputLogsObject, - RunStepDetailsToolCallsCodeOutputImageObject, - ], - Field(discriminator='type'), + expires_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the Upload was created."), ] + object: Annotated[ + Optional[Literal["upload"]], + Field(description='The object type, which is always "upload".'), + ] = None + file: Annotated[ + Optional[OpenAIFile], + Field(description="The ready File object after the Upload is completed."), + ] = None -class CodeInterpreter7(BaseModel): - input: Annotated[ - str, Field(description='The input to the Code Interpreter tool call.') - ] - outputs: Annotated[ - List[Outputs2], +class UploadPart(BaseModel): + id: Annotated[ + str, Field( - description='The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.' + description="The upload Part unique identifier, which can be referenced in API endpoints." ), ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the Part was created."), + ] + upload_id: Annotated[ + str, + Field(description="The ID of the Upload object that this Part was added to."), + ] + object: Annotated[ + Literal["upload.part"], + Field(description="The object type, which is always `upload.part`."), + ] -class RunStepDetailsToolCallsCodeObject(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call.')] - type: Annotated[ - Literal['RunStepDetailsToolCallsCodeObject'], +class Embedding(BaseModel): + index: Annotated[ + int, Field(description="The index of the embedding in the list of embeddings.") + ] + embedding: Annotated[ + List[float], Field( - description='The type of tool call. This is always going to be `code_interpreter` for this type of tool call.' + description="The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings).\n" ), ] - code_interpreter: Annotated[ - CodeInterpreter7, - Field(description='The Code Interpreter tool call definition.'), + object: Annotated[ + Literal["embedding"], + Field(description='The object type, which is always "embedding".'), ] -class FileSearch9(BaseModel): - ranking_options: Optional[RunStepDetailsToolCallsFileSearchRankingOptionsObject] = ( - None - ) - results: Annotated[ - Optional[List[RunStepDetailsToolCallsFileSearchResultObject]], - Field(description='The results of the file search.'), +class Error1(BaseModel): + code: Annotated[str, Field(description="A machine-readable error code.")] + message: Annotated[str, Field(description="A human-readable error message.")] + param: Annotated[ + Optional[str], + Field( + description="The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific." + ), ] = None -class RunStepDetailsToolCallsFileSearchObject(BaseModel): - id: Annotated[str, Field(description='The ID of the tool call object.')] - type: Annotated[ - Literal['RunStepDetailsToolCallsFileSearchObject'], +class NEpochs1(RootModel[int]): + root: Annotated[ + int, Field( - description='The type of tool call. This is always going to be `file_search` for this type of tool call.' + description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n"auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs.', + ge=1, + le=50, ), ] - file_search: Annotated[ - FileSearch9, - Field(description='For now, this is always going to be an empty object.'), - ] -class TextResponseFormatConfiguration( - RootModel[ - Union[ - ResponseFormatText, TextResponseFormatJsonSchema, ResponseFormatJsonObject - ] - ] -): - root: Annotated[ - Union[ - ResponseFormatText, TextResponseFormatJsonSchema, ResponseFormatJsonObject - ], +class Hyperparameters1(BaseModel): + n_epochs: Annotated[ + Union[Literal["auto"], NEpochs1], Field( - description='An object specifying the format that the model must output.\n\nConfiguring `{ "type": "json_schema" }` enables Structured Outputs, \nwhich ensures the model will match your supplied JSON schema. Learn more in the \n[Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n\nThe default format is `{ "type": "text" }` with no additional options.\n\n**Not recommended for gpt-4o and newer models:**\n\nSetting to `{ "type": "json_object" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n', - discriminator='type', + description='The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n"auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs.' ), ] -class TranscriptTextDoneEvent(BaseModel): +class FineTuningIntegration(BaseModel): type: Annotated[ - Literal['TranscriptTextDoneEvent'], - Field(description='The type of the event. Always `transcript.text.done`.\n'), + Literal["wandb"], + Field(description="The type of the integration being enabled for the fine-tuning job"), ] - text: Annotated[str, Field(description='The text that was transcribed.\n')] - logprobs: Annotated[ - Optional[List[Logprob1]], + wandb: Annotated[ + Wandb, Field( - description='The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n' + description="The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n" ), - ] = None - usage: Optional[TranscriptTextUsageTokens] = None - - -class TranscriptionChunkingStrategy( - RootModel[Optional[Union[Literal['auto'], VadConfig]]] -): - root: Optional[Union[Literal['auto'], VadConfig]] - - -class UpdateVectorStoreFileAttributesRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - attributes: VectorStoreFileAttributes - - -class UpdateVectorStoreRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - name: Annotated[ - Optional[str], Field(description='The name of the vector store.') - ] = None - expires_after: Optional[VectorStoreExpirationAfter] = None - metadata: Optional[Metadata] = None + ] -class Result2( - RootModel[ - Union[ - UsageCompletionsResult, - UsageEmbeddingsResult, - UsageModerationsResult, - UsageImagesResult, - UsageAudioSpeechesResult, - UsageAudioTranscriptionsResult, - UsageVectorStoresResult, - UsageCodeInterpreterSessionsResult, - CostsResult, - ] - ] -): - root: Annotated[ - Union[ - UsageCompletionsResult, - UsageEmbeddingsResult, - UsageModerationsResult, - UsageImagesResult, - UsageAudioSpeechesResult, - UsageAudioTranscriptionsResult, - UsageVectorStoresResult, - UsageCodeInterpreterSessionsResult, - CostsResult, - ], - Field(discriminator='object'), - ] +class FineTuningJobEvent(BaseModel): + id: str + created_at: int + level: Literal["info", "warn", "error"] + message: str + object: Literal["fine_tuning.job.event"] -class UsageTimeBucket(BaseModel): - object: Literal['bucket'] - start_time: int - end_time: int - result: List[Result2] +class Metrics(BaseModel): + step: Optional[float] = None + train_loss: Optional[float] = None + train_mean_token_accuracy: Optional[float] = None + valid_loss: Optional[float] = None + valid_mean_token_accuracy: Optional[float] = None + full_valid_loss: Optional[float] = None + full_valid_mean_token_accuracy: Optional[float] = None -class VectorStoreFileObject(BaseModel): +class FineTuningJobCheckpoint(BaseModel): id: Annotated[ str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['vector_store.file'], - Field(description='The object type, which is always `vector_store.file`.'), - ] - usage_bytes: Annotated[ - int, Field( - description='The total vector store usage in bytes. Note that this may be different from the original file size.' + description="The checkpoint identifier, which can be referenced in the API endpoints." ), ] created_at: Annotated[ int, - Field( - description='The Unix timestamp (in seconds) for when the vector store file was created.' - ), + Field(description="The Unix timestamp (in seconds) for when the checkpoint was created."), ] - vector_store_id: Annotated[ + fine_tuned_model_checkpoint: Annotated[ str, - Field( - description='The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.' - ), - ] - status: Annotated[ - Literal['in_progress', 'completed', 'cancelled', 'failed'], - Field( - description='The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use.' - ), - ] - last_error: Optional[LastError2] = None - chunking_strategy: Optional[ChunkingStrategyResponse] = None - attributes: Optional[VectorStoreFileAttributes] = None - - -class VectorStoreSearchRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - query: Annotated[ - Union[str, List[QueryItem]], Field(description='A query string for a search') + Field(description="The name of the fine-tuned checkpoint model that is created."), ] - rewrite_query: Annotated[ - bool, - Field( - description='Whether to rewrite the natural language query for vector search.' - ), - ] = False - max_num_results: Annotated[ - int, - Field( - description='The maximum number of results to return. This number should be between 1 and 50 inclusive.', - ge=1, - le=50, - ), - ] = 10 - ranking_options: Annotated[ - Optional[RankingOptions], Field(description='Ranking options for search.') - ] = None - - -class FileSearchTool(BaseModel): - type: Annotated[ - Literal['FileSearchTool'], - Field(description='The type of the file search tool. Always `file_search`.'), + step_number: Annotated[ + int, Field(description="The step number that the checkpoint was created at.") ] - vector_store_ids: Annotated[ - List[str], Field(description='The IDs of the vector stores to search.') + metrics: Annotated[ + Metrics, + Field(description="Metrics at the step number during the fine-tuning job."), ] - max_num_results: Annotated[ - Optional[int], - Field( - description='The maximum number of results to return. This number should be between 1 and 50 inclusive.' - ), - ] = None - ranking_options: Annotated[ - Optional[RankingOptions1], Field(description='Ranking options for search.') - ] = None - - -class RunStepDetailsToolCall( - RootModel[ - Union[ - RunStepDetailsToolCallsCodeObject, - RunStepDetailsToolCallsFileSearchObject, - RunStepDetailsToolCallsFunctionObject, - ] + fine_tuning_job_id: Annotated[ + str, + Field(description="The name of the fine-tuning job that this checkpoint was created from."), ] -): - root: Annotated[ - Union[ - RunStepDetailsToolCallsCodeObject, - RunStepDetailsToolCallsFileSearchObject, - RunStepDetailsToolCallsFunctionObject, - ], - Field(discriminator='type'), + object: Annotated[ + Literal["fine_tuning.job.checkpoint"], + Field(description='The object type, which is always "fine_tuning.job.checkpoint".'), ] -class RunStepDeltaStepDetailsToolCall( - RootModel[ - Union[ - RunStepDeltaStepDetailsToolCallsCodeObject, - RunStepDeltaStepDetailsToolCallsFileSearchObject, - RunStepDeltaStepDetailsToolCallsFunctionObject, - ] - ] -): - root: Annotated[ - Union[ - RunStepDeltaStepDetailsToolCallsCodeObject, - RunStepDeltaStepDetailsToolCallsFileSearchObject, - RunStepDeltaStepDetailsToolCallsFunctionObject, - ], - Field(discriminator='type'), - ] - +class FinetuneCompletionRequestInput(BaseModel): + prompt: Annotated[ + Optional[str], Field(description="The input prompt for this training example.") + ] = None + completion: Annotated[ + Optional[str], + Field(description="The desired completion for this training example."), + ] = None -class MessageContent( - RootModel[ - Union[ - MessageContentImageFileObject, - MessageContentImageUrlObject, - MessageContentTextObject, - MessageContentRefusalObject, - ] + +class CompletionUsage(BaseModel): + completion_tokens: Annotated[ + int, Field(description="Number of tokens in the generated completion.") ] -): - root: Annotated[ - Union[ - MessageContentImageFileObject, - MessageContentImageUrlObject, - MessageContentTextObject, - MessageContentRefusalObject, - ], - Field(discriminator='type'), + prompt_tokens: Annotated[int, Field(description="Number of tokens in the prompt.")] + total_tokens: Annotated[ + int, + Field(description="Total number of tokens used in the request (prompt + completion)."), ] -class MessageContentDelta( - RootModel[ - Union[ - MessageDeltaContentImageFileObject, - MessageDeltaContentTextObject, - MessageDeltaContentRefusalObject, - MessageDeltaContentImageUrlObject, - ] +class RunCompletionUsage(BaseModel): + completion_tokens: Annotated[ + int, + Field(description="Number of completion tokens used over the course of the run."), ] -): - root: Annotated[ - Union[ - MessageDeltaContentImageFileObject, - MessageDeltaContentTextObject, - MessageDeltaContentRefusalObject, - MessageDeltaContentImageUrlObject, - ], - Field(discriminator='type'), + prompt_tokens: Annotated[ + int, + Field(description="Number of prompt tokens used over the course of the run."), + ] + total_tokens: Annotated[ + int, Field(description="Total number of tokens used (prompt + completion).") ] -class AssistantToolsFunction(BaseModel): - type: Annotated[ - Literal['AssistantToolsFunction'], - Field(description='The type of tool being defined: `function`'), +class RunStepCompletionUsage(BaseModel): + completion_tokens: Annotated[ + int, + Field(description="Number of completion tokens used over the course of the run step."), + ] + prompt_tokens: Annotated[ + int, + Field(description="Number of prompt tokens used over the course of the run step."), + ] + total_tokens: Annotated[ + int, Field(description="Total number of tokens used (prompt + completion).") ] - function: FunctionObject class AssistantsApiResponseFormatOption( RootModel[ Union[ - Literal['auto'], + Literal["auto"], ResponseFormatText, ResponseFormatJsonObject, ResponseFormatJsonSchema, @@ -16556,2701 +1739,2762 @@ class AssistantsApiResponseFormatOption( ): root: Annotated[ Union[ - Literal['auto'], + Literal["auto"], ResponseFormatText, ResponseFormatJsonObject, ResponseFormatJsonSchema, ], Field( - description='Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n' + description='Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n' ), ] -class AuditLogActor(BaseModel): - type: Annotated[ - Optional[Literal['session', 'api_key']], - Field(description='The type of actor. Is either `session` or `api_key`.'), +class CodeInterpreter(BaseModel): + file_ids: Annotated[ + List[str], + Field( + description="A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n", + max_length=20, + ), + ] = [] + + +class FileSearch(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], + Field( + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, + ), ] = None - session: Optional[AuditLogActorSession] = None - api_key: Optional[AuditLogActorApiKey] = None -class ChatCompletionList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[ - List[CreateChatCompletionResponse], - Field(description='An array of chat completion objects.\n'), - ] - first_id: Annotated[ - str, +class ToolResources(BaseModel): + code_interpreter: Optional[CodeInterpreter] = None + file_search: Optional[FileSearch] = None + + +class CodeInterpreter1(BaseModel): + file_ids: Annotated[ + List[str], Field( - description='The identifier of the first chat completion in the data array.' + description="A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + max_length=20, ), - ] - last_id: Annotated[ - str, + ] = [] + + +class ChunkingStrategy(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] + + +class Static(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + max_chunk_size_tokens: Annotated[ + int, Field( - description='The identifier of the last chat completion in the data array.' + description="The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.", + ge=100, + le=4096, ), ] - has_more: Annotated[ - bool, + chunk_overlap_tokens: Annotated[ + int, Field( - description='Indicates whether there are more Chat Completions available.' + description="The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" ), ] -class Content(RootModel[List[ChatCompletionRequestAssistantMessageContentPart]]): - root: Annotated[ - List[ChatCompletionRequestAssistantMessageContentPart], - Field( - description='An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.', - min_length=1, - title='Array of content parts', - ), - ] +class ChunkingStrategy1(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static -class ChatCompletionRequestAssistantMessage(BaseModel): - content: Optional[Union[str, Content]] = None - refusal: Optional[str] = None - role: Annotated[ - Literal['ChatCompletionRequestAssistantMessage'], - Field(description='The role of the messages author, in this case `assistant`.'), - ] - name: Annotated[ - Optional[str], +class VectorStore(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='An optional name for the participant. Provides the model information to differentiate between participants of the same role.' + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_length=10000, + ), + ] = None + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy, ChunkingStrategy1]], + Field( + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - audio: Optional[Audio] = None - tool_calls: Optional[ChatCompletionMessageToolCalls] = None - function_call: Optional[FunctionCall] = None - - -class ChatCompletionRequestMessage( - RootModel[ - Union[ - ChatCompletionRequestDeveloperMessage, - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - ChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ] - ] -): - root: Annotated[ - Union[ - ChatCompletionRequestDeveloperMessage, - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - ChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ], - Field(discriminator='role'), - ] -class ChatCompletionTool(BaseModel): - type: Annotated[ - Literal['ChatCompletionTool'], +class FileSearch1(BaseModel): + vector_store_ids: Annotated[ + List[str], Field( - description='The type of the tool. Currently, only `function` is supported.' + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, ), ] - function: FunctionObject + vector_stores: Annotated[ + Optional[List[VectorStore]], + Field( + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, + ), + ] = None -class ComputerAction( - RootModel[ - Union[ - ClickParam, - DoubleClickAction, - Drag, - KeyPressAction, - Move, - Screenshot, - Scroll, - Type, - Wait, - ] - ] -): - root: Annotated[ - Union[ - ClickParam, - DoubleClickAction, - Drag, - KeyPressAction, - Move, - Screenshot, - Scroll, - Type, - Wait, - ], - Field(discriminator='type'), - ] +class ChunkingStrategy2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class ComputerToolCall(BaseModel): - type: Annotated[ - Literal['ComputerToolCall'], - Field(description='The type of the computer call. Always `computer_call`.'), - ] - id: Annotated[str, Field(description='The unique ID of the computer call.')] - call_id: Annotated[ - str, +class ChunkingStrategy3(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static + + +class VectorStore1(BaseModel): + file_ids: Annotated[ + Optional[List[str]], Field( - description='An identifier used when responding to the tool call with output.\n' + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_length=10000, ), - ] - action: ComputerAction - pending_safety_checks: Annotated[ - List[ComputerCallSafetyCheckParam], - Field(description='The pending safety checks for the computer call.\n'), - ] - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], + ] = None + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy2, ChunkingStrategy3]], Field( - description='The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." ), - ] + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None -class Content5(RootModel[Union[InputContent, OutputContent]]): - root: Annotated[ - Union[InputContent, OutputContent], - Field(description='Multi-modal input and output contents.\n'), +class FileSearch2(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], + Field( + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, + ), + ] = None + vector_stores: Annotated[ + List[VectorStore1], + Field( + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, + ), ] -class Tools(RootModel[Union[ChatCompletionTool, CustomToolChatCompletions]]): - root: Annotated[ - Union[ChatCompletionTool, CustomToolChatCompletions], - Field(discriminator='type'), - ] +class ToolResources1(BaseModel): + code_interpreter: Optional[CodeInterpreter1] = None + file_search: Optional[Union[FileSearch1, FileSearch2]] = None -class SamplingParams(BaseModel): - reasoning_effort: Optional[ReasoningEffort] = None - temperature: Annotated[ - float, - Field(description='A higher temperature increases randomness in the outputs.'), - ] = 1 - max_completion_tokens: Annotated[ - Optional[int], - Field(description='The maximum number of tokens in the generated output.'), - ] = None - top_p: Annotated[ - float, - Field( - description='An alternative to temperature for nucleus sampling; 1.0 includes all tokens.' - ), - ] = 1 - seed: Annotated[ - int, +class CodeInterpreter2(BaseModel): + file_ids: Annotated[ + List[str], Field( - description='A seed value to initialize the randomness, during sampling.' + description="Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + max_length=20, ), - ] = 42 - response_format: Annotated[ - Optional[ - Union[ - ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject - ] - ], + ] = [] + + +class FileSearch3(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='An object specifying the format that the model must output.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n' + description="Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, ), ] = None - tools: Annotated[ - Optional[List[ChatCompletionTool]], + + +class ToolResources2(BaseModel): + code_interpreter: Optional[CodeInterpreter2] = None + file_search: Optional[FileSearch3] = None + + +class DeleteAssistantResponse(BaseModel): + id: str + deleted: bool + object: Literal["assistant.deleted"] + + +class AssistantToolsCode(BaseModel): + type: Annotated[ + Literal["code_interpreter"], + Field(description="The type of tool being defined: `code_interpreter`"), + ] + + +class FileSearch4(BaseModel): + max_num_results: Annotated[ + Optional[int], Field( - description='A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n' + description="The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n\nNote that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information.\n", + ge=1, + le=50, ), ] = None -class CreateEvalItem(RootModel[Union[CreateEvalItem1, EvalItem]]): - root: Annotated[ - Union[CreateEvalItem1, EvalItem], - Field( - description='A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.', - title='CreateEvalItem', - ), +class AssistantToolsFileSearch(BaseModel): + type: Annotated[ + Literal["file_search"], + Field(description="The type of tool being defined: `file_search`"), ] + file_search: Annotated[ + Optional[FileSearch4], Field(description="Overrides for the file search tool.") + ] = None -class CreateEvalLabelModelGrader(BaseModel): +class AssistantToolsFileSearchTypeOnly(BaseModel): type: Annotated[ - Literal['CreateEvalLabelModelGrader'], - Field(description='The object type, which is always `label_model`.'), + Literal["file_search"], + Field(description="The type of tool being defined: `file_search`"), ] - name: Annotated[str, Field(description='The name of the grader.')] - model: Annotated[ - str, - Field( - description='The model to use for the evaluation. Must support structured outputs.' - ), + + +class AssistantToolsFunction(BaseModel): + type: Annotated[ + Literal["function"], + Field(description="The type of tool being defined: `function`"), ] - input: Annotated[ - List[CreateEvalItem], + function: FunctionObject + + +class TruncationObject(BaseModel): + type: Annotated[ + Literal["auto", "last_messages"], Field( - description='A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.' + description="The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`." ), ] - labels: Annotated[ - List[str], - Field(description='The labels to classify to each item in the evaluation.'), - ] - passing_labels: Annotated[ - List[str], + last_messages: Annotated[ + Optional[int], Field( - description='The labels that indicate a passing result. Must be a subset of labels.' + description="The number of most recent messages from the thread when constructing the context for the run.", + ge=1, ), - ] + ] = None + + +class Function3(BaseModel): + name: Annotated[str, Field(description="The name of the function to call.")] -class InputMessages2(BaseModel): +class AssistantsNamedToolChoice(BaseModel): type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `template`.'), - ] - template: Annotated[ - List[Union[Template, EvalItem]], + Literal["function", "code_interpreter", "file_search"], Field( - description='A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.' + description="The type of the tool. If type is `function`, the function name must be set" ), ] + function: Optional[Function3] = None -class Text(BaseModel): - format: Optional[TextResponseFormatConfiguration] = None +class LastError(BaseModel): + code: Annotated[ + Literal["server_error", "rate_limit_exceeded", "invalid_prompt"], + Field(description="One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`."), + ] + message: Annotated[str, Field(description="A human-readable description of the error.")] -class CreateModelResponseProperties(ModelResponseProperties): - top_logprobs: Annotated[ - Optional[int], +class IncompleteDetails(BaseModel): + reason: Annotated[ + Optional[Literal["max_completion_tokens", "max_prompt_tokens"]], Field( - description='An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n', - ge=0, - le=20, + description="The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run." ), ] = None -class CreateTranscriptionRequest(BaseModel): +class ModifyRunRequest(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - file: Annotated[ - bytes, - Field( - description='The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n' - ), - ] - model: Annotated[ - Union[ - str, - Literal[ - 'whisper-1', - 'gpt-4o-transcribe', - 'gpt-4o-mini-transcribe', - 'gpt-4o-transcribe-diarize', - ], - ], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `whisper-1` (which is powered by our open source Whisper V2 model), and `gpt-4o-transcribe-diarize`.\n', - examples=['gpt-4o-transcribe'], + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] - language: Annotated[ + ] = None + + +class ToolOutput(BaseModel): + tool_call_id: Annotated[ Optional[str], Field( - description='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.\n' + description="The ID of the tool call in the `required_action` object within the run object the output is being submitted for." ), ] = None - prompt: Annotated[ + output: Annotated[ Optional[str], - Field( - description="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. This field is not supported when using `gpt-4o-transcribe-diarize`.\n" - ), + Field(description="The output of the tool call to be submitted to continue the run."), ] = None - response_format: Annotated[Optional[AudioResponseFormat], Field()] = 'json' - temperature: Annotated[ - float, + + +class SubmitToolOutputsRunRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + tool_outputs: Annotated[ + List[ToolOutput], + Field(description="A list of tools for which the outputs are being submitted."), + ] + stream: Annotated[ + Optional[bool], Field( - description='The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n' + description="If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" ), - ] = 0 - include: Annotated[ - Optional[List[TranscriptionInclude]], + ] = None + + +class Function4(BaseModel): + name: Annotated[str, Field(description="The name of the function.")] + arguments: Annotated[ + str, + Field(description="The arguments that the model expects you to pass to the function."), + ] + + +class RunToolCallObject(BaseModel): + id: Annotated[ + str, Field( - description="Additional information to include in the transcription response.\n`logprobs` will return the log probabilities of the tokens in the\nresponse to understand the model's confidence in the transcription.\n`logprobs` only works with response_format set to `json` and only with\nthe models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`. This field is not supported when using `gpt-4o-transcribe-diarize`.\n" + description="The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint." ), - ] = None - timestamp_granularities: Annotated[ - List[Literal['word', 'segment']], + ] + type: Annotated[ + Literal["function"], Field( - description='The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\nThis option is not available for `gpt-4o-transcribe-diarize`.\n' + description="The type of tool call the output is required for. For now, this is always `function`." ), - ] = ['segment'] - stream: Optional[bool] = None - chunking_strategy: Optional[TranscriptionChunkingStrategy] = None - known_speaker_names: Annotated[ - Optional[List[str]], + ] + function: Annotated[Function4, Field(description="The function definition.")] + + +class CodeInterpreter3(BaseModel): + file_ids: Annotated[ + List[str], Field( - description='Optional list of speaker names that correspond to the audio samples provided in `known_speaker_references[]`. Each entry should be a short identifier (for example `customer` or `agent`). Up to 4 speakers are supported.\n', - max_length=4, + description="A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + max_length=20, ), - ] = None - known_speaker_references: Annotated[ + ] = [] + + +class FileSearch5(BaseModel): + vector_store_ids: Annotated[ Optional[List[str]], Field( - description='Optional list of audio samples (as [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)) that contain known speaker references matching `known_speaker_names[]`. Each sample must be between 2 and 10 seconds, and can use any of the same input audio formats supported by `file`.\n', - max_length=4, + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + max_length=1, ), ] = None -class CreateTranscriptionResponseStreamEvent( - RootModel[ - Union[ - TranscriptTextSegmentEvent, - TranscriptTextDeltaEvent, - TranscriptTextDoneEvent, - ] - ] -): - root: Annotated[ - Union[ - TranscriptTextSegmentEvent, - TranscriptTextDeltaEvent, - TranscriptTextDoneEvent, - ], - Field(discriminator='type'), - ] +class ToolResources3(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[FileSearch5] = None -class CreateVectorStoreFileBatchRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - file_ids: Annotated[ +class FileSearch6(BaseModel): + vector_store_ids: Annotated[ Optional[List[str]], Field( - description='A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. If `attributes` or `chunking_strategy` are provided, they will be applied to all files in the batch. Mutually exclusive with `files`.', - max_length=500, - min_length=1, - ), - ] = None - files: Annotated[ - Optional[List[CreateVectorStoreFileRequest]], - Field( - description='A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. Use this when you need to override metadata for specific files. The global `attributes` or `chunking_strategy` will be ignored and must be specified for each file. Mutually exclusive with `file_ids`.', - max_length=500, - min_length=1, + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_length=1, ), ] = None - chunking_strategy: Optional[ChunkingStrategyRequestParam] = None - attributes: Optional[VectorStoreFileAttributes] = None -class CustomToolCallOutput(BaseModel): - type: Annotated[ - Literal['CustomToolCallOutput'], - Field( - description='The type of the custom tool call output. Always `custom_tool_call_output`.\n' - ), - ] +class ToolResources4(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[FileSearch6] = None + + +class ThreadObject(BaseModel): id: Annotated[ - Optional[str], - Field( - description='The unique ID of the custom tool call output in the OpenAI platform.\n' - ), - ] = None - call_id: Annotated[ str, - Field( - description='The call ID, used to map this custom tool call output to a custom tool call.\n' - ), + Field(description="The identifier, which can be referenced in API endpoints."), ] - output: Annotated[ - Union[str, List[FunctionAndCustomToolCallOutput]], - Field( - description='The output from the custom tool call generated by your code.\nCan be a string or an list of output content.\n' - ), + object: Annotated[ + Literal["thread"], + Field(description="The object type, which is always `thread`."), ] - - -class EasyInputMessage(BaseModel): - role: Annotated[ - Literal['user', 'assistant', 'system', 'developer'], + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the thread was created."), + ] + tool_resources: Annotated[ + Optional[ToolResources4], Field( - description='The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n' + description="A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), ] - content: Annotated[ - Union[str, InputMessageContentList], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Text, image, or audio input to the model, used to generate a response.\nCan also contain previous assistant responses.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] - type: Annotated[ - Literal['EasyInputMessage'], - Field(description='The type of the message input. Always `message`.\n'), - ] -EvalGraderLabelModel = GraderLabelModel +class ChunkingStrategy4(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] -class EvalGraderScoreModel(GraderScoreModel): - pass_threshold: Annotated[ - Optional[float], Field(description='The threshold for the score.') - ] = None - type: Literal['EvalGraderScoreModel'] +class ChunkingStrategy5(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static -class FineTuneChatCompletionRequestAssistantMessage( - ChatCompletionRequestAssistantMessage -): - weight: Annotated[ - Optional[Literal[0, 1]], +class VectorStore2(BaseModel): + file_ids: Annotated[ + Optional[List[str]], + Field( + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_length=10000, + ), + ] = None + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy4, ChunkingStrategy5]], Field( - description='Controls whether the assistant message is trained against (0 or 1)' + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - role: Annotated[ - Literal['assistant'], - Field(description='The role of the messages author, in this case `assistant`.'), - ] -class FineTuneChatRequestInput(BaseModel): - messages: Annotated[ - Optional[ - List[ - Union[ - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - FineTuneChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ] - ] - ], - Field(min_length=1), - ] = None - tools: Annotated[ - Optional[List[ChatCompletionTool]], - Field(description='A list of tools the model may generate JSON inputs for.'), - ] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - functions: Annotated[ - Optional[List[ChatCompletionFunctions]], +class FileSearch7(BaseModel): + vector_store_ids: Annotated[ + List[str], Field( - description='A list of functions the model may generate JSON inputs for.', - max_length=128, - min_length=1, + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_length=1, + ), + ] + vector_stores: Annotated[ + Optional[List[VectorStore2]], + Field( + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_length=1, ), ] = None -class Input4(BaseModel): - messages: Annotated[ - Optional[ - List[ - Union[ - ChatCompletionRequestSystemMessage, - ChatCompletionRequestUserMessage, - FineTuneChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ChatCompletionRequestFunctionMessage, - ] - ] - ], - Field(min_length=1), +class ChunkingStrategy6(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] + + +class ChunkingStrategy7(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: Static + + +class VectorStore3(BaseModel): + file_ids: Annotated[ + Optional[List[str]], + Field( + description="A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + max_length=10000, + ), ] = None - tools: Annotated[ - Optional[List[ChatCompletionTool]], - Field(description='A list of tools the model may generate JSON inputs for.'), + chunking_strategy: Annotated[ + Optional[Union[ChunkingStrategy6, ChunkingStrategy7]], + Field( + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), ] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True -class FineTunePreferenceRequestInput(BaseModel): - input: Optional[Input4] = None - preferred_output: Annotated[ - Optional[List[ChatCompletionRequestAssistantMessage]], +class FileSearch8(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], Field( - description='The preferred completion message for the output.', max_length=1 + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_length=1, ), ] = None - non_preferred_output: Annotated[ - Optional[List[ChatCompletionRequestAssistantMessage]], + vector_stores: Annotated[ + List[VectorStore3], Field( - description='The non-preferred completion message for the output.', + description="A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n", max_length=1, ), - ] = None + ] -class FineTuneReinforcementRequestInput(BaseModel): - messages: Annotated[ - List[ - Union[ - ChatCompletionRequestDeveloperMessage, - ChatCompletionRequestUserMessage, - FineTuneChatCompletionRequestAssistantMessage, - ChatCompletionRequestToolMessage, - ] - ], - Field(min_length=1), - ] - tools: Annotated[ - Optional[List[ChatCompletionTool]], - Field(description='A list of tools the model may generate JSON inputs for.'), +class ToolResources5(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[Union[FileSearch7, FileSearch8]] = None + + +class FileSearch9(BaseModel): + vector_store_ids: Annotated[ + Optional[List[str]], + Field( + description="The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + max_length=1, + ), ] = None -class GraderMulti(BaseModel): - type: Annotated[ - Literal['GraderMulti'], - Field(description='The object type, which is always `multi`.'), - ] - name: Annotated[str, Field(description='The name of the grader.')] - graders: Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderLabelModel, - ] - calculate_output: Annotated[ - str, - Field(description='A formula to calculate the output based on grader results.'), - ] +class ToolResources6(BaseModel): + code_interpreter: Optional[CodeInterpreter3] = None + file_search: Optional[FileSearch9] = None -class InputMessage(BaseModel): - type: Annotated[ - Literal['InputMessage'], - Field(description='The type of the message input. Always set to `message`.\n'), - ] - role: Annotated[ - Literal['user', 'system', 'developer'], +class ModifyThreadRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + tool_resources: Annotated[ + Optional[ToolResources6], Field( - description='The role of the message input. One of `user`, `system`, or `developer`.\n' + description="A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), - ] - status: Annotated[ - Optional[Literal['in_progress', 'completed', 'incomplete']], + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The status of item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - content: InputMessageContentList -class InputMessageResource(InputMessage): - id: Annotated[str, Field(description='The unique ID of the message input.\n')] - type: Literal['InputMessageResource'] +class DeleteThreadResponse(BaseModel): + id: str + deleted: bool + object: Literal["thread.deleted"] -class ListVectorStoreFilesResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[VectorStoreFileObject] - first_id: Annotated[str, Field(examples=['file-abc123'])] - last_id: Annotated[str, Field(examples=['file-abc456'])] +class ListThreadsResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[ThreadObject] + first_id: Annotated[str, Field(examples=["asst_abc123"])] + last_id: Annotated[str, Field(examples=["asst_abc456"])] has_more: Annotated[bool, Field(examples=[False])] -class Delta(BaseModel): - role: Annotated[ - Optional[Literal['user', 'assistant']], +class IncompleteDetails1(BaseModel): + reason: Annotated[ + Literal["content_filter", "max_tokens", "run_cancelled", "run_expired", "run_failed"], + Field(description="The reason the message is incomplete."), + ] + + +class Attachment(BaseModel): + file_id: Annotated[ + Optional[str], Field(description="The ID of the file to attach to the message.") + ] = None + tools: Annotated[ + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearchTypeOnly]]], + Field(description="The tools to add this file to."), + ] = None + + +class ModifyMessageRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The entity that produced the message. One of `user` or `assistant`.' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - content: Annotated[ - Optional[List[MessageContentDelta]], - Field(description='The content of the message in array of text and/or images.'), - ] = None -class MessageDeltaObject(BaseModel): - id: Annotated[ +class DeleteMessageResponse(BaseModel): + id: str + deleted: bool + object: Literal["thread.message.deleted"] + + +class ImageFile(BaseModel): + file_id: Annotated[ str, Field( - description='The identifier of the message, which can be referenced in API endpoints.' + description='The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' ), ] - object: Annotated[ - Literal['thread.message.delta'], - Field(description='The object type, which is always `thread.message.delta`.'), - ] - delta: Annotated[ - Delta, + detail: Annotated[ + Literal["auto", "low", "high"], Field( - description='The delta containing the fields that have changed on the Message.' + description="Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`." ), - ] + ] = "auto" -class MessageObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['thread.message'], - Field(description='The object type, which is always `thread.message`.'), - ] - created_at: Annotated[ - int, +class MessageContentImageFileObject(BaseModel): + type: Annotated[Literal["image_file"], Field(description="Always `image_file`.")] + image_file: ImageFile + + +class ImageFile1(BaseModel): + file_id: Annotated[ + Optional[str], Field( - description='The Unix timestamp (in seconds) for when the message was created.' + description='The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content.' ), - ] - thread_id: Annotated[ - str, + ] = None + detail: Annotated[ + Literal["auto", "low", "high"], Field( - description='The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs to.' + description="Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`." ), - ] - status: Annotated[ - Literal['in_progress', 'incomplete', 'completed'], + ] = "auto" + + +class MessageDeltaContentImageFileObject(BaseModel): + index: Annotated[int, Field(description="The index of the content part in the message.")] + type: Annotated[Literal["image_file"], Field(description="Always `image_file`.")] + image_file: Optional[ImageFile1] = None + + +class ImageUrl1(BaseModel): + url: Annotated[ + AnyUrl, Field( - description='The status of the message, which can be either `in_progress`, `incomplete`, or `completed`.' + description="The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." ), ] - incomplete_details: Optional[IncompleteDetails] = None - completed_at: Optional[int] = None - incomplete_at: Optional[int] = None - role: Annotated[ - Literal['user', 'assistant'], + detail: Annotated[ + Literal["auto", "low", "high"], Field( - description='The entity that produced the message. One of `user` or `assistant`.' + description="Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`" ), - ] - content: Annotated[ - List[MessageContent], - Field(description='The content of the message in array of text and/or images.'), - ] - assistant_id: Optional[str] = None - run_id: Optional[str] = None - attachments: Optional[List[Attachment1]] = None - metadata: Metadata + ] = "auto" -class MessageStreamEvent1(BaseModel): - event: Literal['0#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject +class MessageContentImageUrlObject(BaseModel): + type: Annotated[Literal["image_url"], Field(description="The type of the content part.")] + image_url: ImageUrl1 -class MessageStreamEvent2(BaseModel): - event: Literal['1#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject +class ImageUrl2(BaseModel): + url: Annotated[ + Optional[str], + Field( + description="The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." + ), + ] = None + detail: Annotated[ + Literal["auto", "low", "high"], + Field( + description="Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`." + ), + ] = "auto" -class MessageStreamEvent3(BaseModel): - event: Literal['2#-datamodel-code-generator-#-object-#-special-#'] - data: MessageDeltaObject +class MessageDeltaContentImageUrlObject(BaseModel): + index: Annotated[int, Field(description="The index of the content part in the message.")] + type: Annotated[Literal["image_url"], Field(description="Always `image_url`.")] + image_url: Optional[ImageUrl2] = None -class MessageStreamEvent4(BaseModel): - event: Literal['3#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject +class MessageContentRefusalObject(BaseModel): + type: Annotated[Literal["refusal"], Field(description="Always `refusal`.")] + refusal: str -class MessageStreamEvent5(BaseModel): - event: Literal['4#-datamodel-code-generator-#-object-#-special-#'] - data: MessageObject +class MessageRequestContentTextObject(BaseModel): + type: Annotated[Literal["text"], Field(description="Always `text`.")] + text: Annotated[str, Field(description="Text content to be sent to the model")] -class MessageStreamEvent( - RootModel[ - Union[ - MessageStreamEvent1, - MessageStreamEvent2, - MessageStreamEvent3, - MessageStreamEvent4, - MessageStreamEvent5, - ] - ] -): - root: Annotated[ - Union[ - MessageStreamEvent1, - MessageStreamEvent2, - MessageStreamEvent3, - MessageStreamEvent4, - MessageStreamEvent5, - ], - Field(discriminator='event'), - ] +class FileCitation(BaseModel): + file_id: Annotated[str, Field(description="The ID of the specific File the citation is from.")] -class ModelIdsResponses( - RootModel[ - Union[ - ModelIdsShared, - Literal[ - 'o1-pro', - 'o1-pro-2025-03-19', - 'o3-pro', - 'o3-pro-2025-06-10', - 'o3-deep-research', - 'o3-deep-research-2025-06-26', - 'o4-mini-deep-research', - 'o4-mini-deep-research-2025-06-26', - 'computer-use-preview', - 'computer-use-preview-2025-03-11', - 'gpt-5-codex', - 'gpt-5-pro', - 'gpt-5-pro-2025-10-06', - ], - ] - ] -): - root: Annotated[ - Union[ - ModelIdsShared, - Literal[ - 'o1-pro', - 'o1-pro-2025-03-19', - 'o3-pro', - 'o3-pro-2025-06-10', - 'o3-deep-research', - 'o3-deep-research-2025-06-26', - 'o4-mini-deep-research', - 'o4-mini-deep-research-2025-06-26', - 'computer-use-preview', - 'computer-use-preview-2025-03-11', - 'gpt-5-codex', - 'gpt-5-pro', - 'gpt-5-pro-2025-10-06', - ], - ], - Field(examples=['gpt-4o']), +class MessageContentTextAnnotationsFileCitationObject(BaseModel): + type: Annotated[Literal["file_citation"], Field(description="Always `file_citation`.")] + text: Annotated[ + str, + Field(description="The text in the message content that needs to be replaced."), ] + file_citation: FileCitation + start_index: Annotated[int, Field(ge=0)] + end_index: Annotated[int, Field(ge=0)] -class OutputMessage(BaseModel): - id: Annotated[str, Field(description='The unique ID of the output message.\n')] - type: Annotated[ - Literal['OutputMessage'], - Field(description='The type of the output message. Always `message`.\n'), - ] - role: Annotated[ - Literal['assistant'], - Field(description='The role of the output message. Always `assistant`.\n'), +class FilePath(BaseModel): + file_id: Annotated[str, Field(description="The ID of the file that was generated.")] + + +class MessageContentTextAnnotationsFilePathObject(BaseModel): + type: Annotated[Literal["file_path"], Field(description="Always `file_path`.")] + text: Annotated[ + str, + Field(description="The text in the message content that needs to be replaced."), ] - content: Annotated[ - List[OutputMessageContent], - Field(description='The content of the output message.\n'), + file_path: FilePath + start_index: Annotated[int, Field(ge=0)] + end_index: Annotated[int, Field(ge=0)] + + +class MessageDeltaContentRefusalObject(BaseModel): + index: Annotated[int, Field(description="The index of the refusal part in the message.")] + type: Annotated[Literal["refusal"], Field(description="Always `refusal`.")] + refusal: Optional[str] = None + + +class FileCitation1(BaseModel): + file_id: Annotated[ + Optional[str], + Field(description="The ID of the specific File the citation is from."), + ] = None + quote: Annotated[Optional[str], Field(description="The specific quote in the file.")] = None + + +class MessageDeltaContentTextAnnotationsFileCitationObject(BaseModel): + index: Annotated[ + int, Field(description="The index of the annotation in the text content part.") ] - status: Annotated[ - Literal['in_progress', 'completed', 'incomplete'], - Field( - description='The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n' - ), + type: Annotated[Literal["file_citation"], Field(description="Always `file_citation`.")] + text: Annotated[ + Optional[str], + Field(description="The text in the message content that needs to be replaced."), + ] = None + file_citation: Optional[FileCitation1] = None + start_index: Annotated[Optional[int], Field(ge=0)] = None + end_index: Annotated[Optional[int], Field(ge=0)] = None + + +class FilePath1(BaseModel): + file_id: Annotated[ + Optional[str], Field(description="The ID of the file that was generated.") + ] = None + + +class MessageDeltaContentTextAnnotationsFilePathObject(BaseModel): + index: Annotated[ + int, Field(description="The index of the annotation in the text content part.") ] + type: Annotated[Literal["file_path"], Field(description="Always `file_path`.")] + text: Annotated[ + Optional[str], + Field(description="The text in the message content that needs to be replaced."), + ] = None + file_path: Optional[FilePath1] = None + start_index: Annotated[Optional[int], Field(ge=0)] = None + end_index: Annotated[Optional[int], Field(ge=0)] = None -class Prompt3(BaseModel): - id: Annotated[ - str, Field(description='The unique identifier of the prompt template to use.') +class LastError1(BaseModel): + code: Annotated[ + Literal["server_error", "rate_limit_exceeded"], + Field(description="One of `server_error` or `rate_limit_exceeded`."), ] - version: Optional[str] = None - variables: Optional[ResponsePromptVariables] = None + message: Annotated[str, Field(description="A human-readable description of the error.")] -class Prompt2(RootModel[Optional[Prompt3]]): - root: Optional[Prompt3] +class MessageCreation(BaseModel): + message_id: Annotated[ + str, + Field(description="The ID of the message that was created by this run step."), + ] -class RealtimeConversationItem( - RootModel[ - Union[ - RealtimeConversationItemMessageSystem, - RealtimeConversationItemMessageUser, - RealtimeConversationItemMessageAssistant, - RealtimeConversationItemFunctionCall, - RealtimeConversationItemFunctionCallOutput, - RealtimeMCPApprovalResponse, - RealtimeMCPListTools, - RealtimeMCPToolCall, - RealtimeMCPApprovalRequest, - ] - ] -): - root: Annotated[ - Union[ - RealtimeConversationItemMessageSystem, - RealtimeConversationItemMessageUser, - RealtimeConversationItemMessageAssistant, - RealtimeConversationItemFunctionCall, - RealtimeConversationItemFunctionCallOutput, - RealtimeMCPApprovalResponse, - RealtimeMCPListTools, - RealtimeMCPToolCall, - RealtimeMCPApprovalRequest, - ], - Field( - description='A single item within a Realtime conversation.', - discriminator='type', - ), - ] +class RunStepDetailsMessageCreationObject(BaseModel): + type: Annotated[Literal["message_creation"], Field(description="Always `message_creation`.")] + message_creation: MessageCreation -class RealtimeResponse(BaseModel): - id: Annotated[ - Optional[str], - Field(description='The unique ID of the response, will look like `resp_1234`.'), - ] = None - object: Annotated[ - Literal['realtime.response'], - Field(description='The object type, must be `realtime.response`.'), - ] = 'realtime.response' - status: Annotated[ - Optional[ - Literal['completed', 'cancelled', 'failed', 'incomplete', 'in_progress'] - ], - Field( - description='The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n' - ), - ] = None - status_details: Annotated[ - Optional[StatusDetails1], - Field(description='Additional details about the status.'), - ] = None - output: Annotated[ - Optional[List[RealtimeConversationItem]], - Field(description='The list of output items generated by the response.'), - ] = None - metadata: Optional[Metadata] = None - audio: Annotated[ - Optional[Audio3], Field(description='Configuration for audio output.') - ] = None - usage: Annotated[ - Optional[Usage4], - Field( - description='Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n' - ), - ] = None - conversation_id: Annotated[ +class MessageCreation1(BaseModel): + message_id: Annotated[ Optional[str], - Field( - description='Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nautomatically by VAD the response will be added to the default conversation\n' - ), - ] = None - output_modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model used to respond, currently the only possible values are\n`[\\"audio\\"]`, `[\\"text\\"]`. Audio output always include a text transcript. Setting the\noutput to mode `text` will disable audio output from the model.\n' - ), - ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n' - ), + Field(description="The ID of the message that was created by this run step."), ] = None -class RealtimeResponseCreateParams(BaseModel): - output_modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model used to respond, currently the only possible values are\n`[\\"audio\\"]`, `[\\"text\\"]`. Audio output always include a text transcript. Setting the\noutput to mode `text` will disable audio output from the model.\n' - ), - ] = None - instructions: Annotated[ - Optional[str], - Field( - description='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.\nNote 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.\n' - ), - ] = None - audio: Annotated[ - Optional[Audio4], Field(description='Configuration for audio input and output.') - ] = None - tools: Annotated[ - Optional[List[Union[RealtimeFunctionTool, MCPTool]]], - Field(description='Tools available to the model.'), - ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), - ] = None - conversation: Annotated[ - Optional[Union[str, Literal['auto', 'none']]], - Field( - description='Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which\nwill not add items to default conversation.\n' - ), - ] = None - metadata: Optional[Metadata] = None - prompt: Optional[Prompt2] = None - input: Annotated[ - Optional[List[RealtimeConversationItem]], - Field( - description='Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items that previously appeared in the session\nusing their id.\n' - ), - ] = None +class RunStepDeltaStepDetailsMessageCreationObject(BaseModel): + type: Annotated[Literal["message_creation"], Field(description="Always `message_creation`.")] + message_creation: Optional[MessageCreation1] = None -class RealtimeServerEventConversationItemAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.added'], - Field(description='The event type, must be `conversation.item.added`.'), - ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem +class RunStepDetailsToolCallsCodeOutputLogsObject(BaseModel): + type: Annotated[Literal["logs"], Field(description="Always `logs`.")] + logs: Annotated[str, Field(description="The text output from the Code Interpreter tool call.")] -class RealtimeServerEventConversationItemCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.created'], - Field(description='The event type, must be `conversation.item.created`.'), - ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem +class RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(BaseModel): + index: Annotated[int, Field(description="The index of the output in the outputs array.")] + type: Annotated[Literal["logs"], Field(description="Always `logs`.")] + logs: Annotated[ + Optional[str], + Field(description="The text output from the Code Interpreter tool call."), + ] = None -class RealtimeServerEventConversationItemDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.done'], - Field(description='The event type, must be `conversation.item.done`.'), +class Image1(BaseModel): + file_id: Annotated[ + str, Field(description="The [file](/docs/api-reference/files) ID of the image.") ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem -class RealtimeServerEventConversationItemRetrieved(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.retrieved'], - Field(description='The event type, must be `conversation.item.retrieved`.'), - ] - item: RealtimeConversationItem +class RunStepDetailsToolCallsCodeOutputImageObject(BaseModel): + type: Annotated[Literal["image"], Field(description="Always `image`.")] + image: Image1 -class RealtimeServerEventResponseCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.created'], - Field(description='The event type, must be `response.created`.'), - ] - response: RealtimeResponse +class Image2(BaseModel): + file_id: Annotated[ + Optional[str], + Field(description="The [file](/docs/api-reference/files) ID of the image."), + ] = None -class RealtimeServerEventResponseDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.done'], - Field(description='The event type, must be `response.done`.'), - ] - response: RealtimeResponse +class RunStepDeltaStepDetailsToolCallsCodeOutputImageObject(BaseModel): + index: Annotated[int, Field(description="The index of the output in the outputs array.")] + type: Annotated[Literal["image"], Field(description="Always `image`.")] + image: Optional[Image2] = None -class RealtimeServerEventResponseOutputItemAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] +class RunStepDetailsToolCallsFileSearchObject(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call object.")] type: Annotated[ - Literal['response.output_item.added'], - Field(description='The event type, must be `response.output_item.added`.'), - ] - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') + Literal["file_search"], + Field( + description="The type of tool call. This is always going to be `file_search` for this type of tool call." + ), ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') + file_search: Annotated[ + Dict[str, Any], + Field(description="For now, this is always going to be an empty object."), ] - item: RealtimeConversationItem -class RealtimeServerEventResponseOutputItemDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] +class RunStepDeltaStepDetailsToolCallsFileSearchObject(BaseModel): + index: Annotated[int, Field(description="The index of the tool call in the tool calls array.")] + id: Annotated[Optional[str], Field(description="The ID of the tool call object.")] = None type: Annotated[ - Literal['response.output_item.done'], - Field(description='The event type, must be `response.output_item.done`.'), - ] - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') + Literal["file_search"], + Field( + description="The type of tool call. This is always going to be `file_search` for this type of tool call." + ), ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') + file_search: Annotated[ + Dict[str, Any], + Field(description="For now, this is always going to be an empty object."), ] - item: RealtimeConversationItem -class RealtimeSession(BaseModel): - id: Annotated[ +class Function5(BaseModel): + name: Annotated[str, Field(description="The name of the function.")] + arguments: Annotated[str, Field(description="The arguments passed to the function.")] + output: Annotated[ Optional[str], Field( - description='Unique identifier for the session that looks like `sess_1234567890abcdef`.\n' + description="The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet." ), ] = None - object: Annotated[ - Optional[Literal['realtime.session']], - Field(description='The object type. Always `realtime.session`.'), - ] = None - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], + + +class RunStepDetailsToolCallsFunctionObject(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call object.")] + type: Annotated[ + Literal["function"], Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' + description="The type of tool call. This is always going to be `function` for this type of tool call." ), + ] + function: Annotated[ + Function5, Field(description="The definition of the function that was called.") + ] + + +class Function6(BaseModel): + name: Annotated[Optional[str], Field(description="The name of the function.")] = None + arguments: Annotated[ + Optional[str], Field(description="The arguments passed to the function.") ] = None - model: Annotated[ - Optional[ - Literal[ - 'gpt-realtime', - 'gpt-realtime-2025-08-28', - 'gpt-4o-realtime-preview', - 'gpt-4o-realtime-preview-2024-10-01', - 'gpt-4o-realtime-preview-2024-12-17', - 'gpt-4o-realtime-preview-2025-06-03', - 'gpt-4o-mini-realtime-preview', - 'gpt-4o-mini-realtime-preview-2024-12-17', - 'gpt-realtime-mini', - 'gpt-realtime-mini-2025-10-06', - 'gpt-audio-mini', - 'gpt-audio-mini-2025-10-06', - ] - ], - Field(description='The Realtime model used for this session.\n'), - ] = None - instructions: Annotated[ + output: Annotated[ Optional[str], Field( - description='The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. "be extremely succinct", "act friendly", "here are examples of good\nresponses") and on audio behavior (e.g. "talk quickly", "inject emotion\ninto your voice", "laugh frequently"). The instructions are not\nguaranteed to be followed by the model, but they provide guidance to the\nmodel on the desired behavior.\n\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n' + description="The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet." ), ] = None - voice: Annotated[ - Optional[VoiceIdsShared], + + +class RunStepDeltaStepDetailsToolCallsFunctionObject(BaseModel): + index: Annotated[int, Field(description="The index of the tool call in the tool calls array.")] + id: Annotated[Optional[str], Field(description="The ID of the tool call object.")] = None + type: Annotated[ + Literal["function"], Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' + description="The type of tool call. This is always going to be `function` for this type of tool call." ), + ] + function: Annotated[ + Optional[Function6], + Field(description="The definition of the function that was called."), ] = None - input_audio_format: Annotated[ - Literal['pcm16', 'g711_ulaw', 'g711_alaw'], + + +class VectorStoreExpirationAfter(BaseModel): + anchor: Annotated[ + Literal["last_active_at"], Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n' + description="Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." ), - ] = 'pcm16' - output_audio_format: Annotated[ - Literal['pcm16', 'g711_ulaw', 'g711_alaw'], + ] + days: Annotated[ + int, Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, output audio is sampled at a rate of 24kHz.\n' + description="The number of days after the anchor time that the vector store will expire.", + ge=1, + le=365, ), - ] = 'pcm16' - input_audio_transcription: Optional[AudioTranscription] = None - turn_detection: Optional[RealtimeTurnDetection] = None - input_audio_noise_reduction: Annotated[ - Optional[InputAudioNoiseReduction], + ] + + +class FileCounts(BaseModel): + in_progress: Annotated[ + int, + Field(description="The number of files that are currently being processed."), + ] + completed: Annotated[ + int, + Field(description="The number of files that have been successfully processed."), + ] + failed: Annotated[int, Field(description="The number of files that have failed to process.")] + cancelled: Annotated[int, Field(description="The number of files that were cancelled.")] + total: Annotated[int, Field(description="The total number of files.")] + + +class VectorStoreObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["vector_store"], + Field(description="The object type, which is always `vector_store`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the vector store was created."), + ] + name: Annotated[str, Field(description="The name of the vector store.")] + usage_bytes: Annotated[ + int, + Field(description="The total number of bytes used by the files in the vector store."), + ] + file_counts: FileCounts + status: Annotated[ + Literal["expired", "in_progress", "completed"], Field( - description='Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n' + description="The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use." ), + ] + expires_after: Optional[VectorStoreExpirationAfter] = None + expires_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the vector store will expire."), ] = None - speed: Annotated[ - float, + last_active_at: Annotated[ + Optional[int], Field( - description="The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n", - ge=0.25, - le=1.5, + description="The Unix timestamp (in seconds) for when the vector store was last active." ), - ] = 1 - tracing: Optional[Union[Literal['auto'], Tracing]] = None - tools: Annotated[ - Optional[List[RealtimeFunctionTool]], - Field(description='Tools (functions) available to the model.'), ] = None - tool_choice: Annotated[ - str, - Field( - description='How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n' - ), - ] = 'auto' - temperature: Annotated[ - float, - Field( - description='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.\n' - ), - ] = 0.8 - max_response_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = None - expires_at: Annotated[ - Optional[int], + ] + + +class UpdateVectorStoreRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[Optional[str], Field(description="The name of the vector store.")] = None + expires_after: Optional[VectorStoreExpirationAfter] = None + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Expiration timestamp for the session, in seconds since epoch.' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - prompt: Optional[Prompt2] = None - include: Optional[List[Literal['item.input_audio_transcription.logprobs']]] = None -class RealtimeSessionCreateRequest(BaseModel): - client_secret: Annotated[ - ClientSecret, Field(description='Ephemeral key returned by the API.') +class ListVectorStoresResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[VectorStoreObject] + first_id: Annotated[str, Field(examples=["vs_abc123"])] + last_id: Annotated[str, Field(examples=["vs_abc456"])] + has_more: Annotated[bool, Field(examples=[False])] + + +class DeleteVectorStoreResponse(BaseModel): + id: str + deleted: bool + object: Literal["vector_store.deleted"] + + +class LastError2(BaseModel): + code: Annotated[ + Literal["server_error", "unsupported_file", "invalid_file"], + Field(description="One of `server_error` or `rate_limit_exceeded`."), ] - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], - Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' - ), - ] = None - instructions: Annotated[ - Optional[str], + message: Annotated[str, Field(description="A human-readable description of the error.")] + + +class OtherChunkingStrategyResponseParam(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["other"], Field(description="Always `other`.")] + + +class StaticChunkingStrategy(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + max_chunk_size_tokens: Annotated[ + int, Field( - description='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.\nNote 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.\n' + description="The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.", + ge=100, + le=4096, ), - ] = None - voice: Annotated[ - Optional[VoiceIdsShared], + ] + chunk_overlap_tokens: Annotated[ + int, Field( - description='The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' + description="The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" ), - ] = None - input_audio_format: Annotated[ - Optional[str], + ] + + +class AutoChunkingStrategyRequestParam(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["auto"], Field(description="Always `auto`.")] + + +class StaticChunkingStrategyRequestParam(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: StaticChunkingStrategy + + +class ChunkingStrategyRequestParam( + RootModel[Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam]] +): + root: Annotated[ + Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam], Field( - description='The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." ), - ] = None - output_audio_format: Annotated[ - Optional[str], + ] + + +class CreateVectorStoreFileRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + file_id: Annotated[ + str, Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' + description="A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files." ), - ] = None - input_audio_transcription: Annotated[ - Optional[InputAudioTranscription], + ] + chunking_strategy: Optional[ChunkingStrategyRequestParam] = None + + +class DeleteVectorStoreFileResponse(BaseModel): + id: str + deleted: bool + object: Literal["vector_store.file.deleted"] + + +class FileCounts1(BaseModel): + in_progress: Annotated[ + int, + Field(description="The number of files that are currently being processed."), + ] + completed: Annotated[int, Field(description="The number of files that have been processed.")] + failed: Annotated[int, Field(description="The number of files that have failed to process.")] + cancelled: Annotated[int, Field(description="The number of files that where cancelled.")] + total: Annotated[int, Field(description="The total number of files.")] + + +class VectorStoreFileBatchObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["vector_store.files_batch"], + Field(description="The object type, which is always `vector_store.file_batch`."), + ] + created_at: Annotated[ + int, Field( - description='Configuration for input audio transcription, defaults to off and can be\nset to `null` to turn off once on. Input audio transcription is not native\nto the model, since the model consumes audio directly. Transcription runs\nasynchronously and should be treated as rough guidance\nrather than the representation understood by the model.\n' + description="The Unix timestamp (in seconds) for when the vector store files batch was created." ), - ] = None - speed: Annotated[ - float, + ] + vector_store_id: Annotated[ + str, Field( - description="The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n", - ge=0.25, - le=1.5, + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to." ), - ] = 1 - tracing: Annotated[ - Optional[Union[Literal['auto'], Tracing]], + ] + status: Annotated[ + Literal["in_progress", "completed", "cancelled", "failed"], Field( - description='Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n', - title='Tracing Configuration', + description="The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`." ), - ] = None - turn_detection: Annotated[ - Optional[TurnDetection], + ] + file_counts: FileCounts1 + + +class CreateVectorStoreFileBatchRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + file_ids: Annotated[ + List[str], Field( - description='Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n' + description="A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.", + max_length=500, + min_length=1, ), + ] + chunking_strategy: Optional[ChunkingStrategyRequestParam] = None + + +class ThreadStreamEvent1(BaseModel): + event: Literal["thread.created"] + data: ThreadObject + + +class ThreadStreamEvent(RootModel[ThreadStreamEvent1]): + root: ThreadStreamEvent1 + + +class ErrorEvent(BaseModel): + event: Literal["error"] + data: Error + + +class DoneEvent(BaseModel): + event: Literal["done"] + data: Literal["[DONE]"] + + +class Datum(BaseModel): + code: Annotated[ + Optional[str], Field(description="An error code identifying the error type.") ] = None - tools: Annotated[ - Optional[List[Tool2]], - Field(description='Tools (functions) available to the model.'), + message: Annotated[ + Optional[str], + Field(description="A human-readable message providing more details about the error."), ] = None - tool_choice: Annotated[ + param: Annotated[ Optional[str], - Field( - description='How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n' - ), + Field(description="The name of the parameter that caused the error, if applicable."), ] = None - temperature: Annotated[ - Optional[float], + line: Annotated[ + Optional[int], Field( - description='Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n' + description="The line number of the input file where the error occurred, if applicable." ), ] = None - max_response_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), + + +class Errors(BaseModel): + object: Annotated[ + Optional[str], Field(description="The object type, which is always `list`.") ] = None - truncation: Optional[RealtimeTruncation] = None - prompt: Optional[Prompt2] = None + data: Optional[List[Datum]] = None -class RealtimeSessionCreateRequestGA(BaseModel): - type: Annotated[ - Literal['RealtimeSessionCreateRequestGA'], - Field( - description='The type of session to create. Always `realtime` for the Realtime API.\n' - ), +class RequestCounts(BaseModel): + total: Annotated[int, Field(description="Total number of requests in the batch.")] + completed: Annotated[ + int, + Field(description="Number of requests that have been completed successfully."), ] - output_modalities: Annotated[ - List[Literal['text', 'audio']], - Field( - description='The set of modalities the model can respond with. It defaults to `["audio"]`, indicating\nthat the model will respond with audio plus a transcript. `["text"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n' - ), - ] = ['audio'] - model: Annotated[ - Optional[ - Union[ - str, - Literal[ - 'gpt-realtime', - 'gpt-realtime-2025-08-28', - 'gpt-4o-realtime-preview', - 'gpt-4o-realtime-preview-2024-10-01', - 'gpt-4o-realtime-preview-2024-12-17', - 'gpt-4o-realtime-preview-2025-06-03', - 'gpt-4o-mini-realtime-preview', - 'gpt-4o-mini-realtime-preview-2024-12-17', - 'gpt-realtime-mini', - 'gpt-realtime-mini-2025-10-06', - 'gpt-audio-mini', - 'gpt-audio-mini-2025-10-06', - ], - ] + failed: Annotated[int, Field(description="Number of requests that have failed.")] + + +class Batch(BaseModel): + id: str + object: Annotated[ + Literal["batch"], Field(description="The object type, which is always `batch`.") + ] + endpoint: Annotated[str, Field(description="The OpenAI API endpoint used by the batch.")] + errors: Optional[Errors] = None + input_file_id: Annotated[str, Field(description="The ID of the input file for the batch.")] + completion_window: Annotated[ + str, + Field(description="The time frame within which the batch should be processed."), + ] + status: Annotated[ + Literal[ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled", ], - Field(description='The Realtime model used for this session.\n'), - ] = None - instructions: Annotated[ + Field(description="The current status of the batch."), + ] + output_file_id: Annotated[ Optional[str], Field( - description='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.\n\nNote 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.\n' + description="The ID of the file containing the outputs of successfully executed requests." ), ] = None - audio: Annotated[ - Optional[Audio5], - Field(description='Configuration for input and output audio.\n'), + error_file_id: Annotated[ + Optional[str], + Field(description="The ID of the file containing the outputs of requests with errors."), ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' - ), + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the batch was created."), + ] + in_progress_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch started processing."), ] = None - tracing: Annotated[ - Optional[Union[Literal['auto'], Tracing2]], - Field( - description='Realtime API can write session traces to the [Traces Dashboard](/logs?api=traces). Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n', - title='Tracing Configuration', - ), + expires_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch will expire."), ] = None - tools: Annotated[ - Optional[List[Tools2]], Field(description='Tools available to the model.') + finalizing_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch started finalizing."), ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], - Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' - ), + completed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch was completed."), ] = None - truncation: Optional[RealtimeTruncation] = None - prompt: Optional[Prompt2] = None - - -class RealtimeSessionCreateResponseGA(BaseModel): - client_secret: Annotated[ - ClientSecret1, Field(description='Ephemeral key returned by the API.') - ] - type: Annotated[ - Literal['RealtimeSessionCreateResponseGA'], - Field( - description='The type of session to create. Always `realtime` for the Realtime API.\n' - ), - ] - output_modalities: Annotated[ - List[Literal['text', 'audio']], - Field( - description='The set of modalities the model can respond with. It defaults to `["audio"]`, indicating\nthat the model will respond with audio plus a transcript. `["text"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n' - ), - ] = ['audio'] - model: Annotated[ - Optional[ - Union[ - str, - Literal[ - 'gpt-realtime', - 'gpt-realtime-2025-08-28', - 'gpt-4o-realtime-preview', - 'gpt-4o-realtime-preview-2024-10-01', - 'gpt-4o-realtime-preview-2024-12-17', - 'gpt-4o-realtime-preview-2025-06-03', - 'gpt-4o-mini-realtime-preview', - 'gpt-4o-mini-realtime-preview-2024-12-17', - 'gpt-realtime-mini', - 'gpt-realtime-mini-2025-10-06', - 'gpt-audio-mini', - 'gpt-audio-mini-2025-10-06', - ], - ] - ], - Field(description='The Realtime model used for this session.\n'), + failed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch failed."), ] = None - instructions: Annotated[ - Optional[str], - Field( - description='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.\n\nNote 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.\n' - ), + expired_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch expired."), ] = None - audio: Annotated[ - Optional[Audio7], - Field(description='Configuration for input and output audio.\n'), + cancelling_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch started cancelling."), ] = None - include: Annotated[ - Optional[List[Literal['item.input_audio_transcription.logprobs']]], - Field( - description='Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n' - ), + cancelled_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the batch was cancelled."), ] = None - tracing: Optional[Union[Literal['auto'], Tracing4]] = None - tools: Annotated[ - Optional[List[Union[RealtimeFunctionTool, MCPTool]]], - Field(description='Tools available to the model.'), + request_counts: Annotated[ + Optional[RequestCounts], + Field(description="The request counts for different statuses within the batch."), ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], - Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' - ), - ] = 'auto' - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - truncation: Optional[RealtimeTruncation] = None - prompt: Optional[Prompt2] = None - -class ResponseTextParam(BaseModel): - format: Optional[TextResponseFormatConfiguration] = None - verbosity: Optional[Verbosity] = None - -class RunGraderRequest(BaseModel): - grader: Annotated[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ], +class BatchRequestInput(BaseModel): + custom_id: Annotated[ + Optional[str], Field( - description='The grader used for the fine-tuning job.', discriminator='type' + description="A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch." ), - ] - item: Annotated[ - Optional[Dict[str, Any]], + ] = None + method: Annotated[ + Optional[Literal["POST"]], Field( - description='The dataset item provided to the grader. This will be used to populate \nthe `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details. \n' + description="The HTTP method to be used for the request. Currently only `POST` is supported." ), ] = None - model_sample: Annotated[ - str, + url: Annotated[ + Optional[str], Field( - description='The model sample to be evaluated. This value will be used to populate \nthe `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details.\nThe `output_json` variable will be populated if the model sample is a \nvalid JSON string.\n \n' + description="The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported." ), - ] + ] = None -class RunStepDeltaStepDetailsToolCallsObject(BaseModel): - type: Annotated[ - Literal['RunStepDeltaStepDetailsToolCallsObject'], - Field(description='Always `tool_calls`.'), - ] - tool_calls: Annotated[ - Optional[List[RunStepDeltaStepDetailsToolCall]], +class Response(BaseModel): + status_code: Annotated[ + Optional[int], Field(description="The HTTP status code of the response") + ] = None + request_id: Annotated[ + Optional[str], Field( - description='An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n' + description="An unique identifier for the OpenAI API request. Please include this request ID when contacting support." ), ] = None + body: Annotated[ + Optional[Dict[str, Any]], Field(description="The JSON body of the response") + ] = None -class RunStepDetailsToolCallsObject(BaseModel): - type: Annotated[ - Literal['RunStepDetailsToolCallsObject'], - Field(description='Always `tool_calls`.'), - ] - tool_calls: Annotated[ - List[RunStepDetailsToolCall], - Field( - description='An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n' - ), - ] +class Error2(BaseModel): + code: Annotated[Optional[str], Field(description="A machine-readable error code.")] = None + message: Annotated[Optional[str], Field(description="A human-readable error message.")] = None -class RunStepObject(BaseModel): - id: Annotated[ - str, - Field( - description='The identifier of the run step, which can be referenced in API endpoints.' - ), - ] - object: Annotated[ - Literal['thread.run.step'], - Field(description='The object type, which is always `thread.run.step`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the run step was created.' - ), - ] - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated with the run step.' - ), - ] - thread_id: Annotated[ - str, - Field( - description='The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run.' - ), - ] - run_id: Annotated[ - str, - Field( - description='The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a part of.' - ), - ] - type: Annotated[ - Literal['message_creation', 'tool_calls'], +class BatchRequestOutput(BaseModel): + id: Optional[str] = None + custom_id: Annotated[ + Optional[str], Field( - description='The type of run step, which can be either `message_creation` or `tool_calls`.' + description="A developer-provided per-request id that will be used to match outputs to inputs." ), - ] - status: Annotated[ - Literal['in_progress', 'cancelled', 'failed', 'completed', 'expired'], + ] = None + response: Optional[Response] = None + error: Annotated[ + Optional[Error2], Field( - description='The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`.' + description="For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure." ), - ] - step_details: Annotated[ - Union[RunStepDetailsMessageCreationObject, RunStepDetailsToolCallsObject], - Field(description='The details of the run step.', discriminator='type'), - ] - last_error: Optional[LastError1] = None - expired_at: Optional[int] = None - cancelled_at: Optional[int] = None - failed_at: Optional[int] = None - completed_at: Optional[int] = None - metadata: Metadata - usage: RunStepCompletionUsage + ] = None -class RunStepStreamEvent1(BaseModel): - event: Literal['0#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class ListBatchesResponse(BaseModel): + data: List[Batch] + first_id: Annotated[Optional[str], Field(examples=["batch_abc123"])] = None + last_id: Annotated[Optional[str], Field(examples=["batch_abc456"])] = None + has_more: bool + object: Literal["list"] -class RunStepStreamEvent2(BaseModel): - event: Literal['1#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorServiceAccount(BaseModel): + id: Annotated[Optional[str], Field(description="The service account id.")] = None -class RunStepStreamEvent4(BaseModel): - event: Literal['3#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorUser(BaseModel): + id: Annotated[Optional[str], Field(description="The user id.")] = None + email: Annotated[Optional[str], Field(description="The user email.")] = None -class RunStepStreamEvent5(BaseModel): - event: Literal['4#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorApiKey(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking id of the API key.")] = None + type: Annotated[ + Optional[Literal["user", "service_account"]], + Field(description="The type of API key. Can be either `user` or `service_account`."), + ] = None + user: Optional[AuditLogActorUser] = None + service_account: Optional[AuditLogActorServiceAccount] = None -class RunStepStreamEvent6(BaseModel): - event: Literal['5#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActorSession(BaseModel): + user: Optional[AuditLogActorUser] = None + ip_address: Annotated[ + Optional[str], + Field(description="The IP address from which the action was performed."), + ] = None -class RunStepStreamEvent7(BaseModel): - event: Literal['6#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepObject +class AuditLogActor(BaseModel): + type: Annotated[ + Optional[Literal["session", "api_key"]], + Field(description="The type of actor. Is either `session` or `api_key`."), + ] = None + session: Optional[AuditLogActorSession] = None + api_key: Optional[AuditLogActorApiKey] = None -class Tool( +class AuditLogEventType( RootModel[ - Union[ - FunctionTool, - FileSearchTool, - ComputerUsePreviewTool, - WebSearchTool, - MCPTool, - CodeInterpreterTool, - ImageGenTool, - LocalShellToolParam, - FunctionShellToolParam, - CustomToolParam, - WebSearchPreviewTool, - ApplyPatchToolParam, + Literal[ + "api_key.created", + "api_key.updated", + "api_key.deleted", + "invite.sent", + "invite.accepted", + "invite.deleted", + "login.succeeded", + "login.failed", + "logout.succeeded", + "logout.failed", + "organization.updated", + "project.created", + "project.updated", + "project.archived", + "service_account.created", + "service_account.updated", + "service_account.deleted", + "user.added", + "user.updated", + "user.deleted", ] ] ): root: Annotated[ - Union[ - FunctionTool, - FileSearchTool, - ComputerUsePreviewTool, - WebSearchTool, - MCPTool, - CodeInterpreterTool, - ImageGenTool, - LocalShellToolParam, - FunctionShellToolParam, - CustomToolParam, - WebSearchPreviewTool, - ApplyPatchToolParam, + Literal[ + "api_key.created", + "api_key.updated", + "api_key.deleted", + "invite.sent", + "invite.accepted", + "invite.deleted", + "login.succeeded", + "login.failed", + "logout.succeeded", + "logout.failed", + "organization.updated", + "project.created", + "project.updated", + "project.archived", + "service_account.created", + "service_account.updated", + "service_account.deleted", + "user.added", + "user.updated", + "user.deleted", ], - Field( - description='A tool that can be used to generate a response.\n', - discriminator='type', - ), + Field(description="The event type."), ] -class ToolsArray(RootModel[List[Tool]]): - root: Annotated[ - List[Tool], - Field( - description="An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n [built-in tools](https://platform.openai.com/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" - ), - ] +class Project(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + name: Annotated[Optional[str], Field(description="The project title.")] = None -class UsageResponse(BaseModel): - object: Literal['page'] - data: List[UsageTimeBucket] - has_more: bool - next_page: str +class Data(BaseModel): + scopes: Annotated[ + Optional[List[str]], + Field(description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`'), + ] = None -class ValidateGraderRequest(BaseModel): - grader: Annotated[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ], - Field(description='The grader used for the fine-tuning job.'), - ] +class ApiKeyCreated(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking ID of the API key.")] = None + data: Annotated[ + Optional[Data], Field(description="The payload used to create the API key.") + ] = None -class ValidateGraderResponse(BaseModel): - grader: Annotated[ - Optional[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, - ] - ], - Field(description='The grader used for the fine-tuning job.'), +class ChangesRequested(BaseModel): + scopes: Annotated[ + Optional[List[str]], + Field(description='A list of scopes allowed for the API key, e.g. `["api.model.request"]`'), ] = None -class AssistantTool( - RootModel[ - Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction] - ] -): - root: Annotated[ - Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], - Field(discriminator='type'), - ] +class ApiKeyUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking ID of the API key.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested], + Field(description="The payload used to update the API key."), + ] = None -class CreateThreadAndRunRequestWithoutStream(BaseModel): - model_config = ConfigDict( - extra='forbid', +class ApiKeyDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The tracking ID of the API key.")] = None + + +class Data1(BaseModel): + email: Annotated[Optional[str], Field(description="The email invited to the organization.")] = ( + None ) - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' - ), - ] - thread: Optional[CreateThreadRequest] = None - model: Annotated[ - Optional[ - Union[ - Optional[str], - Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ], - ] - ], - Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' - ), - ] = None - instructions: Annotated[ + role: Annotated[ Optional[str], - Field( - description='Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.' - ), + Field(description="The role the email was invited to be. Is either `owner` or `member`."), ] = None - tools: Annotated[ - Optional[List[AssistantTool]], - Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', - max_length=20, - ), + + +class InviteSent(BaseModel): + id: Annotated[Optional[str], Field(description="The ID of the invite.")] = None + data: Annotated[ + Optional[Data1], Field(description="The payload used to create the invite.") ] = None - tool_resources: Annotated[ - Optional[ToolResources7], - Field( - description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" - ), + + +class InviteAccepted(BaseModel): + id: Annotated[Optional[str], Field(description="The ID of the invite.")] = None + + +class InviteDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The ID of the invite.")] = None + + +class LoginFailed(BaseModel): + error_code: Annotated[Optional[str], Field(description="The error code of the failure.")] = None + error_message: Annotated[ + Optional[str], Field(description="The error message of the failure.") ] = None - metadata: Optional[Metadata] = None - temperature: Annotated[ - Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - examples=[1], - ge=0.0, - le=2.0, - ), - ] = 1 - top_p: Annotated[ - Optional[float], - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - examples=[1], - ge=0.0, - le=1.0, - ), - ] = 1 - max_prompt_tokens: Annotated[ - Optional[int], + + +class LogoutFailed(BaseModel): + error_code: Annotated[Optional[str], Field(description="The error code of the failure.")] = None + error_message: Annotated[ + Optional[str], Field(description="The error message of the failure.") + ] = None + + +class Settings(BaseModel): + threads_ui_visibility: Annotated[ + Optional[str], Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, + description="Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`." ), ] = None - max_completion_tokens: Annotated[ - Optional[int], + usage_dashboard_visibility: Annotated[ + Optional[str], Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, + description="Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`." ), ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None -class CreateRunRequestWithoutStream(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' - ), - ] - model: Annotated[ - Optional[Union[Optional[str], AssistantSupportedModels]], - Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' - ), +class ChangesRequested1(BaseModel): + title: Annotated[Optional[str], Field(description="The organization title.")] = None + description: Annotated[Optional[str], Field(description="The organization description.")] = None + name: Annotated[Optional[str], Field(description="The organization name.")] = None + settings: Optional[Settings] = None + + +class OrganizationUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The organization ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested1], + Field(description="The payload used to update the organization settings."), ] = None - reasoning_effort: Optional[ReasoningEffort] = None - instructions: Annotated[ + + +class Data2(BaseModel): + name: Annotated[Optional[str], Field(description="The project name.")] = None + title: Annotated[ Optional[str], - Field( - description='Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.' - ), + Field(description="The title of the project as seen on the dashboard."), ] = None - additional_instructions: Annotated[ + + +class ProjectCreated(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + data: Annotated[ + Optional[Data2], Field(description="The payload used to create the project.") + ] = None + + +class ChangesRequested2(BaseModel): + title: Annotated[ Optional[str], - Field( - description='Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.' - ), + Field(description="The title of the project as seen on the dashboard."), ] = None - additional_messages: Annotated[ - Optional[List[CreateMessageRequest]], - Field( - description='Adds additional messages to the thread before creating the run.' - ), + + +class ProjectUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested2], + Field(description="The payload used to update the project."), ] = None - tools: Annotated[ - Optional[List[AssistantTool]], - Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', - max_length=20, - ), + + +class ProjectArchived(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + + +class Data3(BaseModel): + role: Annotated[ + Optional[str], + Field(description="The role of the service account. Is either `owner` or `member`."), ] = None - metadata: Optional[Metadata] = None - temperature: Annotated[ - Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - examples=[1], - ge=0.0, - le=2.0, - ), - ] = 1 - top_p: Annotated[ - Optional[float], - Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - examples=[1], - ge=0.0, - le=1.0, - ), - ] = 1 - max_prompt_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), + + +class ServiceAccountCreated(BaseModel): + id: Annotated[Optional[str], Field(description="The service account ID.")] = None + data: Annotated[ + Optional[Data3], + Field(description="The payload used to create the service account."), + ] = None + + +class ChangesRequested3(BaseModel): + role: Annotated[ + Optional[str], + Field(description="The role of the service account. Is either `owner` or `member`."), + ] = None + + +class ServiceAccountUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The service account ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested3], + Field(description="The payload used to updated the service account."), + ] = None + + +class ServiceAccountDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The service account ID.")] = None + + +class Data4(BaseModel): + role: Annotated[ + Optional[str], + Field(description="The role of the user. Is either `owner` or `member`."), ] = None - max_completion_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), + + +class UserAdded(BaseModel): + id: Annotated[Optional[str], Field(description="The user ID.")] = None + data: Annotated[ + Optional[Data4], + Field(description="The payload used to add the user to the project."), ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None -class RunStepDeltaObjectDelta(BaseModel): - step_details: Annotated[ - Optional[ - Union[ - RunStepDeltaStepDetailsMessageCreationObject, - RunStepDeltaStepDetailsToolCallsObject, - ] - ], - Field(description='The details of the run step.', discriminator='type'), +class ChangesRequested4(BaseModel): + role: Annotated[ + Optional[str], + Field(description="The role of the user. Is either `owner` or `member`."), ] = None -class AssistantObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), - ] - object: Annotated[ - Literal['assistant'], - Field(description='The object type, which is always `assistant`.'), - ] - created_at: Annotated[ - int, - Field( - description='The Unix timestamp (in seconds) for when the assistant was created.' - ), - ] - name: Optional[Name] = None - description: Optional[Description] = None - model: Annotated[ - str, - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n' - ), - ] - instructions: Optional[Instructions] = None - tools: Annotated[ - List[AssistantTool], - Field( - description='A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n', - max_length=128, - ), - ] - tool_resources: Optional[ToolResources] = None - metadata: Metadata - temperature: Optional[Temperature] = None - top_p: Optional[TopP] = None - response_format: Optional[AssistantsApiResponseFormatOption] = None +class UserUpdated(BaseModel): + id: Annotated[Optional[str], Field(description="The project ID.")] = None + changes_requested: Annotated[ + Optional[ChangesRequested4], + Field(description="The payload used to update the user."), + ] = None + + +class UserDeleted(BaseModel): + id: Annotated[Optional[str], Field(description="The user ID.")] = None class AuditLog(BaseModel): - id: Annotated[str, Field(description='The ID of this log.')] + id: Annotated[str, Field(description="The ID of this log.")] type: AuditLogEventType - effective_at: Annotated[ - int, Field(description='The Unix timestamp (in seconds) of the event.') - ] + effective_at: Annotated[int, Field(description="The Unix timestamp (in seconds) of the event.")] project: Annotated[ Optional[Project], Field( - description='The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project.' + description="The project that the action was scoped to. Absent for actions not scoped to projects." ), ] = None actor: AuditLogActor api_key_created: Annotated[ Optional[ApiKeyCreated], Field( - alias='api_key.created', - description='The details for events with this `type`.', + alias="api_key.created", + description="The details for events with this `type`.", ), ] = None api_key_updated: Annotated[ Optional[ApiKeyUpdated], Field( - alias='api_key.updated', - description='The details for events with this `type`.', + alias="api_key.updated", + description="The details for events with this `type`.", ), ] = None api_key_deleted: Annotated[ Optional[ApiKeyDeleted], Field( - alias='api_key.deleted', - description='The details for events with this `type`.', + alias="api_key.deleted", + description="The details for events with this `type`.", ), ] = None - checkpoint_permission_created: Annotated[ - Optional[CheckpointPermissionCreated], + invite_sent: Annotated[ + Optional[InviteSent], + Field(alias="invite.sent", description="The details for events with this `type`."), + ] = None + invite_accepted: Annotated[ + Optional[InviteAccepted], Field( - alias='checkpoint.permission.created', - description='The project and fine-tuned model checkpoint that the checkpoint permission was created for.', + alias="invite.accepted", + description="The details for events with this `type`.", ), ] = None - checkpoint_permission_deleted: Annotated[ - Optional[CheckpointPermissionDeleted], + invite_deleted: Annotated[ + Optional[InviteDeleted], Field( - alias='checkpoint.permission.deleted', - description='The details for events with this `type`.', + alias="invite.deleted", + description="The details for events with this `type`.", ), ] = None - external_key_registered: Annotated[ - Optional[ExternalKeyRegistered], + login_failed: Annotated[ + Optional[LoginFailed], + Field(alias="login.failed", description="The details for events with this `type`."), + ] = None + logout_failed: Annotated[ + Optional[LogoutFailed], Field( - alias='external_key.registered', - description='The details for events with this `type`.', + alias="logout.failed", + description="The details for events with this `type`.", ), ] = None - external_key_removed: Annotated[ - Optional[ExternalKeyRemoved], + organization_updated: Annotated[ + Optional[OrganizationUpdated], Field( - alias='external_key.removed', - description='The details for events with this `type`.', + alias="organization.updated", + description="The details for events with this `type`.", ), ] = None - group_created: Annotated[ - Optional[GroupCreated], + project_created: Annotated[ + Optional[ProjectCreated], Field( - alias='group.created', - description='The details for events with this `type`.', + alias="project.created", + description="The details for events with this `type`.", ), ] = None - group_updated: Annotated[ - Optional[GroupUpdated], + project_updated: Annotated[ + Optional[ProjectUpdated], Field( - alias='group.updated', - description='The details for events with this `type`.', + alias="project.updated", + description="The details for events with this `type`.", ), ] = None - group_deleted: Annotated[ - Optional[GroupDeleted], + project_archived: Annotated[ + Optional[ProjectArchived], Field( - alias='group.deleted', - description='The details for events with this `type`.', + alias="project.archived", + description="The details for events with this `type`.", ), ] = None - scim_enabled: Annotated[ - Optional[ScimEnabled], + service_account_created: Annotated[ + Optional[ServiceAccountCreated], Field( - alias='scim.enabled', description='The details for events with this `type`.' + alias="service_account.created", + description="The details for events with this `type`.", ), ] = None - scim_disabled: Annotated[ - Optional[ScimDisabled], + service_account_updated: Annotated[ + Optional[ServiceAccountUpdated], Field( - alias='scim.disabled', - description='The details for events with this `type`.', + alias="service_account.updated", + description="The details for events with this `type`.", ), ] = None - invite_sent: Annotated[ - Optional[InviteSent], + service_account_deleted: Annotated[ + Optional[ServiceAccountDeleted], Field( - alias='invite.sent', description='The details for events with this `type`.' + alias="service_account.deleted", + description="The details for events with this `type`.", ), ] = None - invite_accepted: Annotated[ - Optional[InviteAccepted], + user_added: Annotated[ + Optional[UserAdded], + Field(alias="user.added", description="The details for events with this `type`."), + ] = None + user_updated: Annotated[ + Optional[UserUpdated], + Field(alias="user.updated", description="The details for events with this `type`."), + ] = None + user_deleted: Annotated[ + Optional[UserDeleted], + Field(alias="user.deleted", description="The details for events with this `type`."), + ] = None + + +class ListAuditLogsResponse(BaseModel): + object: Literal["list"] + data: List[AuditLog] + first_id: Annotated[str, Field(examples=["audit_log-defb456h8dks"])] + last_id: Annotated[str, Field(examples=["audit_log-hnbkd8s93s"])] + has_more: bool + + +class Invite(BaseModel): + object: Annotated[ + Literal["organization.invite"], + Field(description="The object type, which is always `organization.invite`"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + email: Annotated[ + str, + Field(description="The email address of the individual to whom the invite was sent"), + ] + role: Annotated[Literal["owner", "reader"], Field(description="`owner` or `reader`")] + status: Annotated[ + Literal["accepted", "expired", "pending"], + Field(description="`accepted`,`expired`, or `pending`"), + ] + invited_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the invite was sent."), + ] + expires_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the invite expires."), + ] + accepted_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) of when the invite was accepted."), + ] = None + + +class InviteListResponse(BaseModel): + object: Annotated[Literal["list"], Field(description="The object type, which is always `list`")] + data: List[Invite] + first_id: Annotated[ + Optional[str], + Field(description="The first `invite_id` in the retrieved `list`"), + ] = None + last_id: Annotated[ + Optional[str], Field(description="The last `invite_id` in the retrieved `list`") + ] = None + has_more: Annotated[ + Optional[bool], Field( - alias='invite.accepted', - description='The details for events with this `type`.', + description="The `has_more` property is used for pagination to indicate there are additional results." ), ] = None - invite_deleted: Annotated[ - Optional[InviteDeleted], + + +class InviteRequest(BaseModel): + email: Annotated[str, Field(description="Send an email to this address")] + role: Annotated[Literal["reader", "owner"], Field(description="`owner` or `reader`")] + + +class InviteDeleteResponse(BaseModel): + object: Annotated[ + Literal["organization.invite.deleted"], + Field(description="The object type, which is always `organization.invite.deleted`"), + ] + id: str + deleted: bool + + +class User(BaseModel): + object: Annotated[ + Literal["organization.user"], + Field(description="The object type, which is always `organization.user`"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + name: Annotated[str, Field(description="The name of the user")] + email: Annotated[str, Field(description="The email address of the user")] + role: Annotated[Literal["owner", "reader"], Field(description="`owner` or `reader`")] + added_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the user was added."), + ] + + +class UserListResponse(BaseModel): + object: Literal["list"] + data: List[User] + first_id: str + last_id: str + has_more: bool + + +class UserRoleUpdateRequest(BaseModel): + role: Annotated[Literal["owner", "reader"], Field(description="`owner` or `reader`")] + + +class UserDeleteResponse(BaseModel): + object: Literal["organization.user.deleted"] + id: str + deleted: bool + + +class Project1(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + object: Annotated[ + Literal["organization.project"], + Field(description="The object type, which is always `organization.project`"), + ] + name: Annotated[str, Field(description="The name of the project. This appears in reporting.")] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the project was created."), + ] + archived_at: Annotated[ + Optional[int], Field( - alias='invite.deleted', - description='The details for events with this `type`.', + description="The Unix timestamp (in seconds) of when the project was archived or `null`." ), ] = None - ip_allowlist_created: Annotated[ - Optional[IpAllowlistCreated], + status: Annotated[Literal["active", "archived"], Field(description="`active` or `archived`")] + + +class ProjectListResponse(BaseModel): + object: Literal["list"] + data: List[Project1] + first_id: str + last_id: str + has_more: bool + + +class ProjectCreateRequest(BaseModel): + name: Annotated[ + str, + Field(description="The friendly name of the project, this name appears in reports."), + ] + + +class ProjectUpdateRequest(BaseModel): + name: Annotated[ + str, + Field(description="The updated name of the project, this name appears in reports."), + ] + + +class DefaultProjectErrorResponse(BaseModel): + code: int + message: str + + +class ProjectUser(BaseModel): + object: Annotated[ + Literal["organization.project.user"], + Field(description="The object type, which is always `organization.project.user`"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + name: Annotated[str, Field(description="The name of the user")] + email: Annotated[str, Field(description="The email address of the user")] + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + added_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the project was added."), + ] + + +class ProjectUserListResponse(BaseModel): + object: str + data: List[ProjectUser] + first_id: str + last_id: str + has_more: bool + + +class ProjectUserCreateRequest(BaseModel): + user_id: Annotated[str, Field(description="The ID of the user.")] + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + + +class ProjectUserUpdateRequest(BaseModel): + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + + +class ProjectUserDeleteResponse(BaseModel): + object: Literal["organization.project.user.deleted"] + id: str + deleted: bool + + +class ProjectServiceAccount(BaseModel): + object: Annotated[ + Literal["organization.project.service_account"], Field( - alias='ip_allowlist.created', - description='The details for events with this `type`.', + description="The object type, which is always `organization.project.service_account`" ), - ] = None - ip_allowlist_updated: Annotated[ - Optional[IpAllowlistUpdated], + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + name: Annotated[str, Field(description="The name of the service account")] + role: Annotated[Literal["owner", "member"], Field(description="`owner` or `member`")] + created_at: Annotated[ + int, Field( - alias='ip_allowlist.updated', - description='The details for events with this `type`.', + description="The Unix timestamp (in seconds) of when the service account was created" ), - ] = None - ip_allowlist_deleted: Annotated[ - Optional[IpAllowlistDeleted], + ] + + +class ProjectServiceAccountListResponse(BaseModel): + object: Literal["list"] + data: List[ProjectServiceAccount] + first_id: str + last_id: str + has_more: bool + + +class ProjectServiceAccountCreateRequest(BaseModel): + name: Annotated[str, Field(description="The name of the service account being created.")] + + +class ProjectServiceAccountApiKey(BaseModel): + object: Annotated[ + Literal["organization.project.service_account.api_key"], Field( - alias='ip_allowlist.deleted', - description='The details for events with this `type`.', + description="The object type, which is always `organization.project.service_account.api_key`" ), + ] + value: str + name: str + created_at: int + id: str + + +class ProjectServiceAccountDeleteResponse(BaseModel): + object: Literal["organization.project.service_account.deleted"] + id: str + deleted: bool + + +class Owner(BaseModel): + type: Annotated[ + Optional[Literal["user", "service_account"]], + Field(description="`user` or `service_account`"), ] = None - ip_allowlist_config_activated: Annotated[ - Optional[IpAllowlistConfigActivated], + user: Optional[ProjectUser] = None + service_account: Optional[ProjectServiceAccount] = None + + +class ProjectApiKey(BaseModel): + object: Annotated[ + Literal["organization.project.api_key"], + Field(description="The object type, which is always `organization.project.api_key`"), + ] + redacted_value: Annotated[str, Field(description="The redacted value of the API key")] + name: Annotated[str, Field(description="The name of the API key")] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the API key was created"), + ] + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints"), + ] + owner: Owner + + +class ProjectApiKeyListResponse(BaseModel): + object: Literal["list"] + data: List[ProjectApiKey] + first_id: str + last_id: str + has_more: bool + + +class ProjectApiKeyDeleteResponse(BaseModel): + object: Literal["organization.project.api_key.deleted"] + id: str + deleted: bool + + +class ListModelsResponse(BaseModel): + object: Literal["list"] + data: List[Model] + + +class CreateCompletionRequest(BaseModel): + model: Annotated[ + Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], Field( - alias='ip_allowlist.config.activated', - description='The details for events with this `type`.', + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n" ), - ] = None - ip_allowlist_config_deactivated: Annotated[ - Optional[IpAllowlistConfigDeactivated], + ] + prompt: Annotated[ + Optional[Union[Optional[str], List[str], Prompt, Prompt1]], Field( - alias='ip_allowlist.config.deactivated', - description='The details for events with this `type`.', + description="The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n" ), - ] = None - login_succeeded: Annotated[ - Optional[Dict[str, Any]], + ] + best_of: Annotated[ + Optional[int], Field( - alias='login.succeeded', - description='This event has no additional fields beyond the standard audit log attributes.', + description='Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed.\n\nWhen used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n', + ge=0, + le=20, ), - ] = None - login_failed: Annotated[ - Optional[LoginFailed], + ] = 1 + echo: Annotated[ + Optional[bool], + Field(description="Echo back the prompt in addition to the completion\n"), + ] = False + frequency_penalty: Annotated[ + Optional[float], Field( - alias='login.failed', description='The details for events with this `type`.' + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] = None - logout_succeeded: Annotated[ - Optional[Dict[str, Any]], + ] = 0 + logit_bias: Annotated[ + Optional[Dict[str, int]], Field( - alias='logout.succeeded', - description='This event has no additional fields beyond the standard audit log attributes.', + description='Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n\nAs an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated.\n' ), ] = None - logout_failed: Annotated[ - Optional[LogoutFailed], + logprobs: Annotated[ + Optional[int], Field( - alias='logout.failed', - description='The details for events with this `type`.', + description="Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n\nThe maximum value for `logprobs` is 5.\n", + ge=0, + le=5, ), ] = None - organization_updated: Annotated[ - Optional[OrganizationUpdated], + max_tokens: Annotated[ + Optional[int], Field( - alias='organization.updated', - description='The details for events with this `type`.', + description="The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n\nThe token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n", + examples=[16], + ge=0, ), - ] = None - project_created: Annotated[ - Optional[ProjectCreated], + ] = 16 + n: Annotated[ + Optional[int], Field( - alias='project.created', - description='The details for events with this `type`.', + description="How many completions to generate for each prompt.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n", + examples=[1], + ge=1, + le=128, ), - ] = None - project_updated: Annotated[ - Optional[ProjectUpdated], + ] = 1 + presence_penalty: Annotated[ + Optional[float], Field( - alias='project.updated', - description='The details for events with this `type`.', + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] = None - project_archived: Annotated[ - Optional[ProjectArchived], + ] = 0 + seed: Annotated[ + Optional[int], Field( - alias='project.archived', - description='The details for events with this `type`.', + description="If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n", + ge=-9223372036854775808, + le=9223372036854775807, ), ] = None - project_deleted: Annotated[ - Optional[ProjectDeleted], + stop: Annotated[ + Optional[Union[Optional[str], Stop]], Field( - alias='project.deleted', - description='The details for events with this `type`.', + description="Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.\n" ), ] = None - rate_limit_updated: Annotated[ - Optional[RateLimitUpdated], + stream: Annotated[ + Optional[bool], Field( - alias='rate_limit.updated', - description='The details for events with this `type`.', + description="Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n" ), - ] = None - rate_limit_deleted: Annotated[ - Optional[RateLimitDeleted], + ] = False + stream_options: Optional[ChatCompletionStreamOptions] = None + suffix: Annotated[ + Optional[str], Field( - alias='rate_limit.deleted', - description='The details for events with this `type`.', + description="The suffix that comes after a completion of inserted text.\n\nThis parameter is only supported for `gpt-3.5-turbo-instruct`.\n", + examples=["test."], ), ] = None - role_created: Annotated[ - Optional[RoleCreated], + temperature: Annotated[ + Optional[float], Field( - alias='role.created', description='The details for events with this `type`.' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n", + examples=[1], + ge=0.0, + le=2.0, ), - ] = None - role_updated: Annotated[ - Optional[RoleUpdated], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - alias='role.updated', description='The details for events with this `type`.' + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n", + examples=[1], + ge=0.0, + le=1.0, ), - ] = None - role_deleted: Annotated[ - Optional[RoleDeleted], + ] = 1 + user: Annotated[ + Optional[str], Field( - alias='role.deleted', description='The details for events with this `type`.' + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + examples=["user-1234"], ), ] = None - role_assignment_created: Annotated[ - Optional[RoleAssignmentCreated], + + +class CreateCompletionResponse(BaseModel): + id: Annotated[str, Field(description="A unique identifier for the completion.")] + choices: Annotated[ + List[Choice], Field( - alias='role.assignment.created', - description='The details for events with this `type`.', + description="The list of completion choices the model generated for the input prompt." ), - ] = None - role_assignment_deleted: Annotated[ - Optional[RoleAssignmentDeleted], + ] + created: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) of when the completion was created."), + ] + model: Annotated[str, Field(description="The model used for completion.")] + system_fingerprint: Annotated[ + Optional[str], Field( - alias='role.assignment.deleted', - description='The details for events with this `type`.', + description="This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None - service_account_created: Annotated[ - Optional[ServiceAccountCreated], + object: Annotated[ + Literal["text_completion"], + Field(description='The object type, which is always "text_completion"'), + ] + usage: Optional[CompletionUsage] = None + + +class ChatCompletionTool(BaseModel): + type: Annotated[ + Literal["function"], + Field(description="The type of the tool. Currently, only `function` is supported."), + ] + function: FunctionObject + + +class ChatCompletionToolChoiceOption( + RootModel[Union[Literal["none", "auto", "required"], ChatCompletionNamedToolChoice]] +): + root: Annotated[ + Union[Literal["none", "auto", "required"], ChatCompletionNamedToolChoice], Field( - alias='service_account.created', - description='The details for events with this `type`.', + description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tool and instead generates a message.\n`auto` means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools.\nSpecifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n\n`none` is the default when no tools are present. `auto` is the default if tools are present.\n' ), + ] + + +class ChatCompletionMessageToolCalls(RootModel[List[ChatCompletionMessageToolCall]]): + root: Annotated[ + List[ChatCompletionMessageToolCall], + Field(description="The tool calls generated by the model, such as function calls."), + ] + + +class ChatCompletionResponseMessage(BaseModel): + content: Annotated[Optional[str], Field(description="The contents of the message.")] = None + refusal: Annotated[ + Optional[str], Field(description="The refusal message generated by the model.") ] = None - service_account_updated: Annotated[ - Optional[ServiceAccountUpdated], + tool_calls: Optional[ChatCompletionMessageToolCalls] = None + role: Annotated[ + Literal["assistant"], + Field(description="The role of the author of this message."), + ] + function_call: Annotated[ + Optional[FunctionCall], Field( - alias='service_account.updated', - description='The details for events with this `type`.', + description="Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." ), ] = None - service_account_deleted: Annotated[ - Optional[ServiceAccountDeleted], + + +class Choice1(BaseModel): + finish_reason: Annotated[ + Literal["stop", "length", "tool_calls", "content_filter", "function_call"], Field( - alias='service_account.deleted', - description='The details for events with this `type`.', + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" ), + ] + index: Annotated[int, Field(description="The index of the choice in the list of choices.")] + message: ChatCompletionResponseMessage + logprobs: Annotated[ + Optional[Logprobs2], + Field(description="Log probability information for the choice."), ] = None - user_added: Annotated[ - Optional[UserAdded], + + +class CreateChatCompletionResponse(BaseModel): + id: Annotated[str, Field(description="A unique identifier for the chat completion.")] + choices: Annotated[ + List[Choice1], Field( - alias='user.added', description='The details for events with this `type`.' + description="A list of chat completion choices. Can be more than one if `n` is greater than 1." ), - ] = None - user_updated: Annotated[ - Optional[UserUpdated], + ] + created: Annotated[ + int, Field( - alias='user.updated', description='The details for events with this `type`.' + description="The Unix timestamp (in seconds) of when the chat completion was created." ), - ] = None - user_deleted: Annotated[ - Optional[UserDeleted], + ] + model: Annotated[str, Field(description="The model used for the chat completion.")] + service_tier: Annotated[ + Optional[Literal["scale", "default"]], Field( - alias='user.deleted', description='The details for events with this `type`.' + description="The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.", + examples=["scale"], ), ] = None - certificate_created: Annotated[ - Optional[CertificateCreated], + system_fingerprint: Annotated[ + Optional[str], Field( - alias='certificate.created', - description='The details for events with this `type`.', + description="This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None - certificate_updated: Annotated[ - Optional[CertificateUpdated], + object: Annotated[ + Literal["chat.completion"], + Field(description="The object type, which is always `chat.completion`."), + ] + usage: Optional[CompletionUsage] = None + + +class Choice2(BaseModel): + finish_reason: Annotated[ + Literal["stop", "length", "function_call", "content_filter"], Field( - alias='certificate.updated', - description='The details for events with this `type`.', + description="The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, or `function_call` if the model called a function.\n" ), - ] = None - certificate_deleted: Annotated[ - Optional[CertificateDeleted], + ] + index: Annotated[int, Field(description="The index of the choice in the list of choices.")] + message: ChatCompletionResponseMessage + + +class CreateChatCompletionFunctionResponse(BaseModel): + id: Annotated[str, Field(description="A unique identifier for the chat completion.")] + choices: Annotated[ + List[Choice2], Field( - alias='certificate.deleted', - description='The details for events with this `type`.', + description="A list of chat completion choices. Can be more than one if `n` is greater than 1." ), - ] = None - certificates_activated: Annotated[ - Optional[CertificatesActivated], + ] + created: Annotated[ + int, Field( - alias='certificates.activated', - description='The details for events with this `type`.', + description="The Unix timestamp (in seconds) of when the chat completion was created." ), - ] = None - certificates_deactivated: Annotated[ - Optional[CertificatesDeactivated], + ] + model: Annotated[str, Field(description="The model used for the chat completion.")] + system_fingerprint: Annotated[ + Optional[str], Field( - alias='certificates.deactivated', - description='The details for events with this `type`.', + description="This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" ), ] = None + object: Annotated[ + Literal["chat.completion"], + Field(description="The object type, which is always `chat.completion`."), + ] + usage: Optional[CompletionUsage] = None + + +class ImagesResponse(BaseModel): + created: int + data: List[Image] + + +class ListFilesResponse(BaseModel): + data: List[OpenAIFile] + object: Literal["list"] + + +class ListFineTuningJobEventsResponse(BaseModel): + data: List[FineTuningJobEvent] + object: Literal["list"] + + +class ListFineTuningJobCheckpointsResponse(BaseModel): + data: List[FineTuningJobCheckpoint] + object: Literal["list"] + first_id: Optional[str] = None + last_id: Optional[str] = None + has_more: bool -class ConversationItem( - RootModel[ - Union[ - Message, - FunctionToolCallResource, - FunctionToolCallOutputResource, - FileSearchToolCall, - WebSearchToolCall, - ImageGenToolCall, - ComputerToolCall, - ComputerToolCallOutputResource, - ReasoningItem, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponseResource, - MCPToolCall, - CustomToolCall, - CustomToolCallOutput, - ] +class CreateEmbeddingResponse(BaseModel): + data: Annotated[ + List[Embedding], + Field(description="The list of embeddings generated by the model."), ] -): - root: Annotated[ - Union[ - Message, - FunctionToolCallResource, - FunctionToolCallOutputResource, - FileSearchToolCall, - WebSearchToolCall, - ImageGenToolCall, - ComputerToolCall, - ComputerToolCallOutputResource, - ReasoningItem, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponseResource, - MCPToolCall, - CustomToolCall, - CustomToolCallOutput, - ], - Field( - description='A single item within a conversation. The set of possible types are the same as the `output` type of a [Response object](https://platform.openai.com/docs/api-reference/responses/object#responses/object-output).', - discriminator='type', - title='Conversation item', - ), + model: Annotated[ + str, Field(description="The name of the model used to generate the embedding.") ] - - -class ConversationItemList(BaseModel): object: Annotated[ - Literal['list'], - Field(description='The type of object returned, must be `list`.'), + Literal["list"], Field(description='The object type, which is always "list".') ] - data: Annotated[ - List[ConversationItem], Field(description='A list of conversation items.') - ] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') - ] - first_id: Annotated[str, Field(description='The ID of the first item in the list.')] - last_id: Annotated[str, Field(description='The ID of the last item in the list.')] + usage: Annotated[Usage1, Field(description="The usage information for the request.")] -class CreateAssistantRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - model: Annotated[ - Union[str, AssistantSupportedModels], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n', - examples=['gpt-4o'], - ), +class FineTuningJob(BaseModel): + id: Annotated[ + str, + Field(description="The object identifier, which can be referenced in the API endpoints."), ] - name: Optional[Name] = None - description: Optional[Description] = None - instructions: Optional[Instructions] = None - reasoning_effort: Optional[ReasoningEffort] = None - tools: Annotated[ - List[AssistantTool], + created_at: Annotated[ + int, Field( - description='A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n', - max_length=128, + description="The Unix timestamp (in seconds) for when the fine-tuning job was created." ), - ] = [] - tool_resources: Optional[ToolResources1] = None - metadata: Optional[Metadata] = None - temperature: Optional[Temperature] = None - top_p: Optional[TopP] = None - response_format: Optional[AssistantsApiResponseFormatOption] = None - - -class CreateChatCompletionRequest(CreateModelResponseProperties): - messages: Annotated[ - List[ChatCompletionRequestMessage], + ] + error: Annotated[ + Optional[Error1], Field( - description='A list of messages comprising the conversation so far. Depending on the\n[model](https://platform.openai.com/docs/models) you use, different message types (modalities) are\nsupported, like [text](https://platform.openai.com/docs/guides/text-generation),\n[images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).\n', - min_length=1, + description="For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure." ), ] - model: Annotated[ - str, + fine_tuned_model: Annotated[ + Optional[str], Field( - description='Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\nto browse and compare available models.\n' + description="The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running." ), - ] - modalities: Optional[ResponseModalities] = None - verbosity: Optional[Verbosity] = None - reasoning_effort: Optional[ReasoningEffort] = None - max_completion_tokens: Annotated[ + ] = None + finished_at: Annotated[ Optional[int], Field( - description='An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n' + description="The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running." ), ] = None - frequency_penalty: Annotated[ - Optional[float], + hyperparameters: Annotated[ + Hyperparameters1, Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on\ntheir existing frequency in the text so far, decreasing the model's\nlikelihood to repeat the same line verbatim.\n", - ge=-2.0, - le=2.0, + description="The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details." ), - ] = 0 - presence_penalty: Annotated[ - Optional[float], + ] + model: Annotated[str, Field(description="The base model that is being fine-tuned.")] + object: Annotated[ + Literal["fine_tuning.job"], + Field(description='The object type, which is always "fine_tuning.job".'), + ] + organization_id: Annotated[ + str, Field(description="The organization that owns the fine-tuning job.") + ] + result_files: Annotated[ + List[str], Field( - description="Number between -2.0 and 2.0. Positive values penalize new tokens based on\nwhether they appear in the text so far, increasing the model's likelihood\nto talk about new topics.\n", - ge=-2.0, - le=2.0, + description="The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents)." ), - ] = 0 - web_search_options: Annotated[ - Optional[WebSearchOptions], + ] + status: Annotated[ + Literal["validating_files", "queued", "running", "succeeded", "failed", "cancelled"], Field( - description='This tool searches the web for relevant results to use in a response.\nLearn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n', - title='Web search', + description="The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`." ), - ] = None - top_logprobs: Annotated[ + ] + trained_tokens: Annotated[ Optional[int], Field( - description='An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n`logprobs` must be set to `true` if this parameter is used.\n', - ge=0, - le=20, + description="The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running." ), ] = None - response_format: Annotated[ - Optional[ - Union[ - ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject - ] - ], + training_file: Annotated[ + str, Field( - description='An object specifying the format that the model must output.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n', - discriminator='type', + description="The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents)." ), - ] = None - audio: Annotated[ - Optional[Audio2], + ] + validation_file: Annotated[ + Optional[str], Field( - description='Parameters for audio output. Required when audio output is requested with\n`modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio).\n' + description="The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents)." ), ] = None - store: Annotated[ - Optional[bool], - Field( - description='Whether or not to store the output of this chat completion request for\nuse in our [model distillation](https://platform.openai.com/docs/guides/distillation) or\n[evals](https://platform.openai.com/docs/guides/evals) products.\n\nSupports text and image inputs. Note: image inputs over 8MB will be dropped.\n' - ), - ] = False - stream: Annotated[ - Optional[bool], - Field( - description='If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\nfor more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\nguide for more information on how to handle the streaming events.\n' - ), - ] = False - stop: Optional[StopConfiguration] = None - logit_bias: Annotated[ - Optional[Dict[str, int]], + integrations: Annotated[ + Optional[List[FineTuningIntegration]], Field( - description='Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the\ntokenizer) to an associated bias value from -100 to 100. Mathematically,\nthe bias is added to the logits generated by the model prior to sampling.\nThe exact effect will vary per model, but values between -1 and 1 should\ndecrease or increase likelihood of selection; values like -100 or 100\nshould result in a ban or exclusive selection of the relevant token.\n' + description="A list of integrations to enable for this fine-tuning job.", + max_length=5, ), ] = None - logprobs: Annotated[ - Optional[bool], - Field( - description='Whether to return log probabilities of the output tokens or not. If true,\nreturns the log probabilities of each output token returned in the\n`content` of `message`.\n' - ), - ] = False - max_tokens: Annotated[ + seed: Annotated[int, Field(description="The seed used for the fine-tuning job.")] + estimated_finish: Annotated[ Optional[int], Field( - description='The maximum number of [tokens](/tokenizer) that can be generated in the\nchat completion. This value can be used to control\n[costs](https://openai.com/api/pricing/) for text generated via API.\n\nThis value is now deprecated in favor of `max_completion_tokens`, and is\nnot compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning).\n' + description="The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running." ), ] = None - n: Annotated[ - Optional[int], - Field( - description='How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs.', - examples=[1], - ge=1, - le=128, - ), - ] = 1 - prediction: Annotated[ - Optional[PredictionContent], + + +class AssistantObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["assistant"], + Field(description="The object type, which is always `assistant`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the assistant was created."), + ] + name: Annotated[ + Optional[str], Field( - description='Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs),\nwhich can greatly improve response times when large parts of the model\nresponse are known ahead of time. This is most common when you are\nregenerating a file with only minor changes to most of the content.\n', - discriminator='type', + description="The name of the assistant. The maximum length is 256 characters.\n", + max_length=256, ), ] = None - seed: Annotated[ - Optional[int], + description: Annotated[ + Optional[str], Field( - description='This feature is in Beta.\nIf specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n', - ge=-9223372036854776000, - le=9223372036854776000, + description="The description of the assistant. The maximum length is 512 characters.\n", + max_length=512, ), ] = None - stream_options: Optional[ChatCompletionStreamOptions] = None - tools: Annotated[ - Optional[List[Tools]], + model: Annotated[ + str, Field( - description='A list of tools the model may call. You can provide either\n[custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or\n[function tools](https://platform.openai.com/docs/guides/function-calling).\n' + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n" ), - ] = None - tool_choice: Optional[ChatCompletionToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - function_call: Annotated[ - Optional[Union[Literal['none', 'auto'], ChatCompletionFunctionCallOption]], + ] + instructions: Annotated[ + Optional[str], Field( - description='Deprecated in favor of `tool_choice`.\n\nControls which (if any) function is called by the model.\n\n`none` means the model will not call a function and instead generates a\nmessage.\n\n`auto` means the model can pick between generating a message or calling a\nfunction.\n\nSpecifying a particular function via `{"name": "my_function"}` forces the\nmodel to call that function.\n\n`none` is the default when no functions are present. `auto` is the default\nif functions are present.\n' + description="The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + max_length=256000, ), ] = None - functions: Annotated[ - Optional[List[ChatCompletionFunctions]], + tools: Annotated[ + List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]], Field( - description='Deprecated in favor of `tools`.\n\nA list of functions the model may generate JSON inputs for.\n', + description="A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", max_length=128, - min_length=1, ), - ] = None - - -class InputMessages(BaseModel): - type: Annotated[ - Literal['0#-datamodel-code-generator-#-object-#-special-#'], - Field(description='The type of input messages. Always `template`.'), ] - template: Annotated[ - List[Union[EasyInputMessage, EvalItem]], + tool_resources: Annotated[ + Optional[ToolResources], Field( - description='A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.' + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), - ] - - -class CreateEvalCompletionsRunDataSource(BaseModel): - type: Annotated[ - Literal['CreateEvalCompletionsRunDataSource'], - Field(description='The type of run data source. Always `completions`.'), - ] - input_messages: Annotated[ - Optional[Union[InputMessages, InputMessages1]], + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.', - discriminator='type', + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = None - sampling_params: Optional[SamplingParams] = None - model: Annotated[ - Optional[str], + ] + temperature: Annotated[ + Optional[float], Field( - description='The name of the model to use for generating completions (e.g. "o3-mini").' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + examples=[1], + ge=0.0, + le=2.0, ), - ] = None - source: Annotated[ - Union[ - EvalJsonlFileContentSource, - EvalJsonlFileIdSource, - EvalStoredCompletionsSource, - ], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - description="Determines what populates the `item` namespace in this run's data source.", - discriminator='type', + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + examples=[1], + ge=0.0, + le=1.0, ), - ] - - -class TestingCriteria( - RootModel[ - Union[ - CreateEvalLabelModelGrader, - EvalGraderStringCheck, - EvalGraderTextSimilarity, - EvalGraderPython, - EvalGraderScoreModel, - ] - ] -): - root: Annotated[ - Union[ - CreateEvalLabelModelGrader, - EvalGraderStringCheck, - EvalGraderTextSimilarity, - EvalGraderPython, - EvalGraderScoreModel, - ], - Field(discriminator='type'), - ] + ] = 1 + response_format: Optional[AssistantsApiResponseFormatOption] = None -class CreateEvalRequest(BaseModel): - name: Annotated[Optional[str], Field(description='The name of the evaluation.')] = ( - None +class CreateAssistantRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", ) - metadata: Optional[Metadata] = None - data_source_config: Annotated[ + model: Annotated[ Union[ - CreateEvalCustomDataSourceConfig, - CreateEvalLogsDataSourceConfig, - CreateEvalStoredCompletionsDataSourceConfig, + str, + Literal[ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], ], Field( - description='The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation.', - discriminator='type', + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n", + examples=["gpt-4o"], ), ] - testing_criteria: Annotated[ - List[TestingCriteria], + name: Annotated[ + Optional[str], Field( - description="A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`)." + description="The name of the assistant. The maximum length is 256 characters.\n", + max_length=256, ), - ] - - -class SamplingParams1(BaseModel): - reasoning_effort: Optional[ReasoningEffort] = None - temperature: Annotated[ - float, - Field(description='A higher temperature increases randomness in the outputs.'), - ] = 1 - max_completion_tokens: Annotated[ - Optional[int], - Field(description='The maximum number of tokens in the generated output.'), ] = None - top_p: Annotated[ - float, + description: Annotated[ + Optional[str], Field( - description='An alternative to temperature for nucleus sampling; 1.0 includes all tokens.' + description="The description of the assistant. The maximum length is 512 characters.\n", + max_length=512, ), - ] = 1 - seed: Annotated[ - int, + ] = None + instructions: Annotated[ + Optional[str], Field( - description='A seed value to initialize the randomness, during sampling.' + description="The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + max_length=256000, ), - ] = 42 + ] = None tools: Annotated[ - Optional[List[Tool]], + List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]], Field( - description="An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nThe two categories of tools you can provide the model are:\n\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n [built-in tools](https://platform.openai.com/docs/guides/tools).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code. Learn more about\n [function calling](https://platform.openai.com/docs/guides/function-calling).\n" + description="A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + max_length=128, ), - ] = None - text: Annotated[ - Optional[Text], + ] = [] + tool_resources: Annotated[ + Optional[ToolResources1], Field( - description='Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n' + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), ] = None - - -class CreateEvalResponsesRunDataSource(BaseModel): - type: Annotated[ - Literal['CreateEvalResponsesRunDataSource'], - Field(description='The type of run data source. Always `responses`.'), - ] - input_messages: Annotated[ - Optional[Union[InputMessages2, InputMessages3]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.', - discriminator='type', + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - sampling_params: Optional[SamplingParams1] = None - model: Annotated[ - Optional[str], + temperature: Annotated[ + Optional[float], Field( - description='The name of the model to use for generating completions (e.g. "o3-mini").' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + examples=[1], + ge=0.0, + le=2.0, ), - ] = None - source: Annotated[ - Union[EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalResponsesSource], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - description="Determines what populates the `item` namespace in this run's data source.", - discriminator='type', - ), - ] - - -class CreateEvalRunRequest(BaseModel): - name: Annotated[Optional[str], Field(description='The name of the run.')] = None - metadata: Optional[Metadata] = None - data_source: Annotated[ - Union[ - CreateEvalJsonlRunDataSource, - CreateEvalCompletionsRunDataSource, - CreateEvalResponsesRunDataSource, - ], - Field(description="Details about the run's data source."), - ] + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + examples=[1], + ge=0.0, + le=1.0, + ), + ] = 1 + response_format: Optional[AssistantsApiResponseFormatOption] = None -class CreateRunRequest(BaseModel): +class ModifyAssistantRequest(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - assistant_id: Annotated[ - str, - Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' - ), - ] model: Annotated[ - Optional[Union[Optional[str], AssistantSupportedModels]], + Optional[str], Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' + description="ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them.\n" ), ] = None - reasoning_effort: Optional[ReasoningEffort] = None - instructions: Annotated[ + name: Annotated[ Optional[str], Field( - description='Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.' + description="The name of the assistant. The maximum length is 256 characters.\n", + max_length=256, ), ] = None - additional_instructions: Annotated[ + description: Annotated[ Optional[str], Field( - description='Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.' + description="The description of the assistant. The maximum length is 512 characters.\n", + max_length=512, ), ] = None - additional_messages: Annotated[ - Optional[List[CreateMessageRequest]], + instructions: Annotated[ + Optional[str], Field( - description='Adds additional messages to the thread before creating the run.' + description="The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + max_length=256000, ), ] = None tools: Annotated[ - Optional[List[AssistantTool]], + List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]], Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', - max_length=20, + description="A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + max_length=128, + ), + ] = [] + tool_resources: Annotated[ + Optional[ToolResources2], + Field( + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - metadata: Optional[Metadata] = None temperature: Annotated[ Optional[float], Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", examples=[1], ge=0.0, le=2.0, @@ -19259,1848 +4503,1462 @@ class CreateRunRequest(BaseModel): top_p: Annotated[ Optional[float], Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", examples=[1], ge=0.0, le=1.0, ), ] = 1 - stream: Annotated[ - Optional[bool], - Field( - description='If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n' - ), - ] = None - max_prompt_tokens: Annotated[ - Optional[int], - Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, - ), - ] = None - max_completion_tokens: Annotated[ - Optional[int], + response_format: Optional[AssistantsApiResponseFormatOption] = None + + +class ListAssistantsResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[AssistantObject] + first_id: Annotated[str, Field(examples=["asst_abc123"])] + last_id: Annotated[str, Field(examples=["asst_abc456"])] + has_more: Annotated[bool, Field(examples=[False])] + + +class AssistantsApiToolChoiceOption( + RootModel[Union[Literal["none", "auto", "required"], AssistantsNamedToolChoice]] +): + root: Annotated[ + Union[Literal["none", "auto", "required"], AssistantsNamedToolChoice], Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', - ge=256, + description='Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.\n' ), - ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None + ] -class CreateThreadAndRunRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) +class SubmitToolOutputs(BaseModel): + tool_calls: Annotated[ + List[RunToolCallObject], Field(description="A list of the relevant tool calls.") + ] + + +class RequiredAction(BaseModel): + type: Annotated[ + Literal["submit_tool_outputs"], + Field(description="For now, this is always `submit_tool_outputs`."), + ] + submit_tool_outputs: Annotated[ + SubmitToolOutputs, + Field(description="Details on the tool outputs needed for this run to continue."), + ] + + +class RunObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), + ] + object: Annotated[ + Literal["thread.run"], + Field(description="The object type, which is always `thread.run`."), + ] + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the run was created."), + ] + thread_id: Annotated[ + str, + Field( + description="The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run." + ), + ] assistant_id: Annotated[ str, Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.' + description="The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run." ), ] - thread: Optional[CreateThreadRequest] = None - model: Annotated[ - Optional[ - Union[ - Optional[str], - Literal[ - 'gpt-5', - 'gpt-5-mini', - 'gpt-5-nano', - 'gpt-5-2025-08-07', - 'gpt-5-mini-2025-08-07', - 'gpt-5-nano-2025-08-07', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', - 'gpt-4.1-2025-04-14', - 'gpt-4.1-mini-2025-04-14', - 'gpt-4.1-nano-2025-04-14', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-2024-08-06', - 'gpt-4o-2024-05-13', - 'gpt-4o-mini', - 'gpt-4o-mini-2024-07-18', - 'gpt-4.5-preview', - 'gpt-4.5-preview-2025-02-27', - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4-0125-preview', - 'gpt-4-turbo-preview', - 'gpt-4-1106-preview', - 'gpt-4-vision-preview', - 'gpt-4', - 'gpt-4-0314', - 'gpt-4-0613', - 'gpt-4-32k', - 'gpt-4-32k-0314', - 'gpt-4-32k-0613', - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-0613', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0125', - 'gpt-3.5-turbo-16k-0613', - ], - ] + status: Annotated[ + Literal[ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired", ], Field( - description='The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.' + description="The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`." + ), + ] + required_action: Annotated[ + Optional[RequiredAction], + Field( + description="Details on the action required to continue the run. Will be `null` if no action is required." + ), + ] + last_error: Annotated[ + Optional[LastError], + Field( + description="The last error associated with this run. Will be `null` if there are no errors." ), + ] + expires_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run will expire."), + ] = None + started_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run was started."), + ] = None + cancelled_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run was cancelled."), + ] = None + failed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run failed."), ] = None + completed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run was completed."), + ] = None + incomplete_details: Annotated[ + Optional[IncompleteDetails], + Field( + description="Details on why the run is incomplete. Will be `null` if the run is not incomplete." + ), + ] + model: Annotated[ + str, + Field( + description="The model that the [assistant](/docs/api-reference/assistants) used for this run." + ), + ] instructions: Annotated[ - Optional[str], + str, Field( - description='Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.' + description="The instructions that the [assistant](/docs/api-reference/assistants) used for this run." ), - ] = None + ] tools: Annotated[ - Optional[List[AssistantTool]], + List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]], Field( - description='Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.', + description="The list of tools that the [assistant](/docs/api-reference/assistants) used for this run.", max_length=20, ), - ] = None - tool_resources: Annotated[ - Optional[ToolResources2], + ] + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] = None - metadata: Optional[Metadata] = None + ] + usage: RunCompletionUsage temperature: Annotated[ Optional[float], - Field( - description='What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n', - examples=[1], - ge=0.0, - le=2.0, - ), - ] = 1 + Field(description="The sampling temperature used for this run. If not set, defaults to 1."), + ] = None top_p: Annotated[ Optional[float], Field( - description='An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n', - examples=[1], - ge=0.0, - le=1.0, - ), - ] = 1 - stream: Annotated[ - Optional[bool], - Field( - description='If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n' + description="The nucleus sampling value used for this run. If not set, defaults to 1." ), ] = None max_prompt_tokens: Annotated[ Optional[int], Field( - description='The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', + description="The maximum number of prompt tokens specified to have been used over the course of the run.\n", ge=256, ), ] = None max_completion_tokens: Annotated[ Optional[int], Field( - description='The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n', + description="The maximum number of completion tokens specified to have been used over the course of the run.\n", ge=256, ), ] = None - truncation_strategy: Optional[TruncationObject] = None - tool_choice: Optional[AssistantsApiToolChoiceOption] = None - parallel_tool_calls: Annotated[Optional[ParallelToolCalls], Field()] = True - response_format: Optional[AssistantsApiResponseFormatOption] = None + truncation_strategy: Annotated[Optional[TruncationObject], Field(...)] + tool_choice: Annotated[Optional[AssistantsApiToolChoiceOption], Field(...)] + parallel_tool_calls: ParallelToolCalls + response_format: Annotated[Optional[AssistantsApiResponseFormatOption], Field(...)] -class Eval(BaseModel): - object: Annotated[Literal['eval'], Field(description='The object type.')] - id: Annotated[str, Field(description='Unique identifier for the evaluation.')] - name: Annotated[ - str, - Field( - description='The name of the evaluation.', - examples=['Chatbot effectiveness Evaluation'], - ), - ] - data_source_config: Annotated[ - Union[ - EvalCustomDataSourceConfig, - EvalLogsDataSourceConfig, - EvalStoredCompletionsDataSourceConfig, - ], - Field( - description='Configuration of data sources used in runs of the evaluation.', - discriminator='type', - ), +class ListRunsResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[RunObject] + first_id: Annotated[str, Field(examples=["run_abc123"])] + last_id: Annotated[str, Field(examples=["run_abc456"])] + has_more: Annotated[bool, Field(examples=[False])] + + +class Content4( + RootModel[ + List[ + Union[ + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageRequestContentTextObject, + ] + ] ] - testing_criteria: Annotated[ +): + root: Annotated[ List[ Union[ - EvalGraderLabelModel, - EvalGraderStringCheck, - EvalGraderTextSimilarity, - EvalGraderPython, - EvalGraderScoreModel, + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageRequestContentTextObject, ] ], - Field(description='A list of testing criteria.'), - ] - created_at: Annotated[ - int, Field( - description='The Unix timestamp (in seconds) for when the eval was created.' + description="An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models/overview).", + min_length=1, + title="Array of content parts", ), ] - metadata: Metadata - - -class EvalList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[List[Eval], Field(description='An array of eval objects.\n')] - first_id: Annotated[ - str, Field(description='The identifier of the first eval in the data array.') - ] - last_id: Annotated[ - str, Field(description='The identifier of the last eval in the data array.') - ] - has_more: Annotated[ - bool, Field(description='Indicates whether there are more evals available.') - ] -class EvalRun(BaseModel): - object: Annotated[ - Literal['eval.run'], - Field(description='The type of the object. Always "eval.run".'), - ] - id: Annotated[str, Field(description='Unique identifier for the evaluation run.')] - eval_id: Annotated[ - str, Field(description='The identifier of the associated evaluation.') - ] - status: Annotated[str, Field(description='The status of the evaluation run.')] - model: Annotated[ - str, Field(description='The model that is evaluated, if applicable.') - ] - name: Annotated[str, Field(description='The name of the evaluation run.')] - created_at: Annotated[ - int, +class CreateMessageRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + role: Annotated[ + Literal["user", "assistant"], Field( - description='Unix timestamp (in seconds) when the evaluation run was created.' + description="The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n" ), ] - report_url: Annotated[ - str, + content: Union[str, Content4] + attachments: Annotated[ + Optional[List[Attachment]], Field( - description='The URL to the rendered evaluation run report on the UI dashboard.' + description="A list of files attached to the message, and the tools they should be added to." ), - ] - result_counts: Annotated[ - ResultCounts, - Field(description='Counters summarizing the outcomes of the evaluation run.'), - ] - per_model_usage: Annotated[ - List[PerModelUsageItem], - Field(description='Usage statistics for each model during the evaluation run.'), - ] - per_testing_criteria_results: Annotated[ - List[PerTestingCriteriaResult], + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Results per testing criteria applied during the evaluation run.' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), - ] - data_source: Annotated[ + ] = None + + +class Text(BaseModel): + value: Annotated[str, Field(description="The data that makes up the text.")] + annotations: List[ Union[ - CreateEvalJsonlRunDataSource, - CreateEvalCompletionsRunDataSource, - CreateEvalResponsesRunDataSource, + MessageContentTextAnnotationsFileCitationObject, + MessageContentTextAnnotationsFilePathObject, + ] + ] + + +class MessageContentTextObject(BaseModel): + type: Annotated[Literal["text"], Field(description="Always `text`.")] + text: Text + + +class Text1(BaseModel): + value: Annotated[Optional[str], Field(description="The data that makes up the text.")] = None + annotations: Optional[ + List[ + Union[ + MessageDeltaContentTextAnnotationsFileCitationObject, + MessageDeltaContentTextAnnotationsFilePathObject, + ] + ] + ] = None + + +class MessageDeltaContentTextObject(BaseModel): + index: Annotated[int, Field(description="The index of the content part in the message.")] + type: Annotated[Literal["text"], Field(description="Always `text`.")] + text: Optional[Text1] = None + + +class CodeInterpreter7(BaseModel): + input: Annotated[str, Field(description="The input to the Code Interpreter tool call.")] + outputs: Annotated[ + List[ + Union[ + RunStepDetailsToolCallsCodeOutputLogsObject, + RunStepDetailsToolCallsCodeOutputImageObject, + ] ], Field( - description="Information about the run's data source.", discriminator='type' + description="The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type." ), ] - metadata: Metadata - error: EvalApiError -class EvalRunList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of this object. It is always set to "list".\n'), - ] - data: Annotated[List[EvalRun], Field(description='An array of eval run objects.\n')] - first_id: Annotated[ - str, - Field(description='The identifier of the first eval run in the data array.'), - ] - last_id: Annotated[ - str, Field(description='The identifier of the last eval run in the data array.') +class RunStepDetailsToolCallsCodeObject(BaseModel): + id: Annotated[str, Field(description="The ID of the tool call.")] + type: Annotated[ + Literal["code_interpreter"], + Field( + description="The type of tool call. This is always going to be `code_interpreter` for this type of tool call." + ), ] - has_more: Annotated[ - bool, Field(description='Indicates whether there are more evals available.') + code_interpreter: Annotated[ + CodeInterpreter7, + Field(description="The Code Interpreter tool call definition."), ] -class FineTuneReinforcementMethod(BaseModel): - grader: Annotated[ - Union[ - GraderStringCheck, - GraderTextSimilarity, - GraderPython, - GraderScoreModel, - GraderMulti, +class CodeInterpreter8(BaseModel): + input: Annotated[ + Optional[str], Field(description="The input to the Code Interpreter tool call.") + ] = None + outputs: Annotated[ + Optional[ + List[ + Union[ + RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, + RunStepDeltaStepDetailsToolCallsCodeOutputImageObject, + ] + ] ], - Field(description='The grader used for the fine-tuning job.'), - ] - hyperparameters: Optional[FineTuneReinforcementHyperparameters] = None + Field( + description="The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type." + ), + ] = None -class Item( - RootModel[ - Union[ - InputMessage, - OutputMessage, - FileSearchToolCall, - ComputerToolCall, - ComputerCallOutputItemParam, - WebSearchToolCall, - FunctionToolCall, - FunctionCallOutputItemParam, - ReasoningItem, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCallItemParam, - FunctionShellCallOutputItemParam, - ApplyPatchToolCallItemParam, - ApplyPatchToolCallOutputItemParam, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponse, - MCPToolCall, - CustomToolCallOutput, - CustomToolCall, - ] - ] -): - root: Annotated[ - Union[ - InputMessage, - OutputMessage, - FileSearchToolCall, - ComputerToolCall, - ComputerCallOutputItemParam, - WebSearchToolCall, - FunctionToolCall, - FunctionCallOutputItemParam, - ReasoningItem, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCallItemParam, - FunctionShellCallOutputItemParam, - ApplyPatchToolCallItemParam, - ApplyPatchToolCallOutputItemParam, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponse, - MCPToolCall, - CustomToolCallOutput, - CustomToolCall, - ], +class RunStepDeltaStepDetailsToolCallsCodeObject(BaseModel): + index: Annotated[int, Field(description="The index of the tool call in the tool calls array.")] + id: Annotated[Optional[str], Field(description="The ID of the tool call.")] = None + type: Annotated[ + Literal["code_interpreter"], Field( - description='Content item used to generate a response.\n', - discriminator='type', + description="The type of tool call. This is always going to be `code_interpreter` for this type of tool call." ), ] + code_interpreter: Annotated[ + Optional[CodeInterpreter8], + Field(description="The Code Interpreter tool call definition."), + ] = None -class ItemResource( - RootModel[ - Union[ - InputMessageResource, - OutputMessage, - FileSearchToolCall, - ComputerToolCall, - ComputerToolCallOutputResource, - WebSearchToolCall, - FunctionToolCallResource, - FunctionToolCallOutputResource, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponseResource, - MCPToolCall, - ] - ] -): - root: Annotated[ - Union[ - InputMessageResource, - OutputMessage, - FileSearchToolCall, - ComputerToolCall, - ComputerToolCallOutputResource, - WebSearchToolCall, - FunctionToolCallResource, - FunctionToolCallOutputResource, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - LocalShellToolCallOutput, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPListTools, - MCPApprovalRequest, - MCPApprovalResponseResource, - MCPToolCall, - ], +class CreateVectorStoreRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + file_ids: Annotated[ + Optional[List[str]], Field( - description='Content item used to generate a response.\n', - discriminator='type', + description="A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.", + max_length=500, ), - ] + ] = None + name: Annotated[Optional[str], Field(description="The name of the vector store.")] = None + expires_after: Optional[VectorStoreExpirationAfter] = None + chunking_strategy: Annotated[ + Optional[Union[AutoChunkingStrategyRequestParam, StaticChunkingStrategyRequestParam]], + Field( + description="The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty." + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None -class ListAssistantsResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[AssistantObject] - first_id: Annotated[str, Field(examples=['asst_abc123'])] - last_id: Annotated[str, Field(examples=['asst_abc456'])] - has_more: Annotated[bool, Field(examples=[False])] +class StaticChunkingStrategyResponseParam(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[Literal["static"], Field(description="Always `static`.")] + static: StaticChunkingStrategy -class ListAuditLogsResponse(BaseModel): - object: Literal['list'] - data: List[AuditLog] - first_id: Annotated[str, Field(examples=['audit_log-defb456h8dks'])] - last_id: Annotated[str, Field(examples=['audit_log-hnbkd8s93s'])] - has_more: bool +class RunStreamEvent1(BaseModel): + event: Literal["thread.run.created"] + data: RunObject -class ListMessagesResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[MessageObject] - first_id: Annotated[str, Field(examples=['msg_abc123'])] - last_id: Annotated[str, Field(examples=['msg_abc123'])] - has_more: Annotated[bool, Field(examples=[False])] +class RunStreamEvent2(BaseModel): + event: Literal["thread.run.queued"] + data: RunObject -class ListRunStepsResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[RunStepObject] - first_id: Annotated[str, Field(examples=['step_abc123'])] - last_id: Annotated[str, Field(examples=['step_abc456'])] - has_more: Annotated[bool, Field(examples=[False])] +class RunStreamEvent3(BaseModel): + event: Literal["thread.run.in_progress"] + data: RunObject -class ModelIds(RootModel[Union[ModelIdsShared, ModelIdsResponses]]): - root: Union[ModelIdsShared, ModelIdsResponses] +class RunStreamEvent4(BaseModel): + event: Literal["thread.run.requires_action"] + data: RunObject -class ModifyAssistantRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - model: Annotated[ - Optional[Union[str, AssistantSupportedModels]], - Field( - description='ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n' - ), - ] = None - reasoning_effort: Optional[ReasoningEffort] = None - name: Optional[Name] = None - description: Optional[Description] = None - instructions: Optional[Instructions] = None - tools: Annotated[ - List[AssistantTool], - Field( - description='A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n', - max_length=128, - ), - ] = [] - tool_resources: Optional[ToolResources4] = None - metadata: Optional[Metadata] = None - temperature: Optional[Temperature3] = None - top_p: Optional[TopP3] = None - response_format: Optional[AssistantsApiResponseFormatOption] = None +class RunStreamEvent5(BaseModel): + event: Literal["thread.run.completed"] + data: RunObject + + +class RunStreamEvent6(BaseModel): + event: Literal["thread.run.incomplete"] + data: RunObject + + +class RunStreamEvent7(BaseModel): + event: Literal["thread.run.failed"] + data: RunObject + + +class RunStreamEvent8(BaseModel): + event: Literal["thread.run.cancelling"] + data: RunObject + + +class RunStreamEvent9(BaseModel): + event: Literal["thread.run.cancelled"] + data: RunObject + + +class RunStreamEvent10(BaseModel): + event: Literal["thread.run.expired"] + data: RunObject -class OutputItem1( +class RunStreamEvent( RootModel[ Union[ - OutputMessage, - FileSearchToolCall, - FunctionToolCall, - WebSearchToolCall, - ComputerToolCall, - ReasoningItem, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPToolCall, - MCPListTools, - MCPApprovalRequest, - CustomToolCall, + RunStreamEvent1, + RunStreamEvent2, + RunStreamEvent3, + RunStreamEvent4, + RunStreamEvent5, + RunStreamEvent6, + RunStreamEvent7, + RunStreamEvent8, + RunStreamEvent9, + RunStreamEvent10, ] ] ): - root: Annotated[ - Union[ - OutputMessage, - FileSearchToolCall, - FunctionToolCall, - WebSearchToolCall, - ComputerToolCall, - ReasoningItem, - ImageGenToolCall, - CodeInterpreterToolCall, - LocalShellToolCall, - FunctionShellCall, - FunctionShellCallOutput, - ApplyPatchToolCall, - ApplyPatchToolCallOutput, - MCPToolCall, - MCPListTools, - MCPApprovalRequest, - CustomToolCall, - ], - Field(discriminator='type'), + root: Union[ + RunStreamEvent1, + RunStreamEvent2, + RunStreamEvent3, + RunStreamEvent4, + RunStreamEvent5, + RunStreamEvent6, + RunStreamEvent7, + RunStreamEvent8, + RunStreamEvent9, + RunStreamEvent10, ] -class RealtimeBetaClientEventConversationItemCreate(BaseModel): - event_id: Annotated[ - Optional[str], +class ProjectServiceAccountCreateResponse(BaseModel): + object: Literal["organization.project.service_account"] + id: str + name: str + role: Annotated[ + Literal["member"], + Field(description="Service accounts can only have one role of type `member`"), + ] + created_at: int + api_key: ProjectServiceAccountApiKey + + +class ChatCompletionRequestAssistantMessage(BaseModel): + content: Annotated[ + Optional[Union[Optional[str], Content2]], Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, + description="The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.\n" ), ] = None - type: Annotated[ - Literal['conversation.item.create'], - Field(description='The event type, must be `conversation.item.create`.'), + refusal: Annotated[ + Optional[str], Field(description="The refusal message by the assistant.") + ] = None + role: Annotated[ + Literal["assistant"], + Field(description="The role of the messages author, in this case `assistant`."), ] - previous_item_id: Annotated[ + name: Annotated[ Optional[str], Field( - description='The ID of the preceding item after which the new item will be inserted. \nIf not set, the new item will be appended to the end of the conversation.\nIf set to `root`, the new item will be added to the beginning of the conversation.\nIf set to an existing ID, it allows an item to be inserted mid-conversation. If the\nID cannot be found, an error will be returned and the item will not be added.\n' + description="An optional name for the participant. Provides the model information to differentiate between participants of the same role." + ), + ] = None + tool_calls: Optional[ChatCompletionMessageToolCalls] = None + function_call: Annotated[ + Optional[FunctionCall], + Field( + description="Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." ), ] = None - item: RealtimeConversationItem -class RealtimeBetaClientEventSessionUpdate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), +class FineTuneChatCompletionRequestAssistantMessage(ChatCompletionRequestAssistantMessage): + weight: Annotated[ + Optional[Literal[0, 1]], + Field(description="Controls whether the assistant message is trained against (0 or 1)"), ] = None - type: Annotated[ - Literal['session.update'], - Field(description='The event type, must be `session.update`.'), + role: Annotated[ + Literal["assistant"], + Field(description="The role of the messages author, in this case `assistant`."), ] - session: RealtimeSessionCreateRequest -class RealtimeBetaResponse(BaseModel): - id: Annotated[ - Optional[str], Field(description='The unique ID of the response.') - ] = None - object: Annotated[ - Literal['realtime.response'], - Field(description='The object type, must be `realtime.response`.'), - ] = 'realtime.response' - status: Annotated[ +class ListPaginatedFineTuningJobsResponse(BaseModel): + data: List[FineTuningJob] + has_more: bool + object: Literal["list"] + + +class FinetuneChatRequestInput(BaseModel): + messages: Annotated[ Optional[ - Literal['completed', 'cancelled', 'failed', 'incomplete', 'in_progress'] + List[ + Union[ + ChatCompletionRequestSystemMessage, + ChatCompletionRequestUserMessage, + FineTuneChatCompletionRequestAssistantMessage, + ChatCompletionRequestToolMessage, + ChatCompletionRequestFunctionMessage, + ] + ] ], - Field( - description='The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n' - ), - ] = None - status_details: Annotated[ - Optional[StatusDetails], - Field(description='Additional details about the status.'), + Field(min_length=1), ] = None - output: Annotated[ - Optional[List[RealtimeConversationItem]], - Field(description='The list of output items generated by the response.'), + tools: Annotated[ + Optional[List[ChatCompletionTool]], + Field(description="A list of tools the model may generate JSON inputs for."), ] = None - metadata: Optional[Metadata] = None - usage: Annotated[ - Optional[Usage3], + parallel_tool_calls: Optional[ParallelToolCalls] = None + functions: Annotated[ + Optional[List[ChatCompletionFunctions]], Field( - description='Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n' + description="A list of functions the model may generate JSON inputs for.", + max_length=128, + min_length=1, ), ] = None - conversation_id: Annotated[ - Optional[str], + + +class CreateRunRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + assistant_id: Annotated[ + str, Field( - description='Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nby server VAD, the response will be added to the default conversation, thus\nthe `conversation_id` will be an id like `conv_1234`.\n' + description="The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run." ), - ] = None - voice: Annotated[ - Optional[VoiceIdsShared], + ] + model: Annotated[ + Optional[ + Union[ + Optional[str], + Literal[ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] + ], Field( - description='The voice the model used to respond.\nCurrent voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' + description="The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + examples=["gpt-4o"], ), ] = None - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], + instructions: Annotated[ + Optional[str], Field( - description='The set of modalities the model used to respond. If there are multiple modalities,\nthe model will pick one, for example if `modalities` is `["text", "audio"]`, the model\ncould be responding in either text or audio.\n' + description="Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis." ), ] = None - output_audio_format: Annotated[ - Optional[Literal['pcm16', 'g711_ulaw', 'g711_alaw']], + additional_instructions: Annotated[ + Optional[str], Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' + description="Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions." ), ] = None - temperature: Annotated[ - Optional[float], - Field( - description='Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n' - ), + additional_messages: Annotated[ + Optional[List[CreateMessageRequest]], + Field(description="Adds additional messages to the thread before creating the run."), ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + tools: Annotated[ + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n' + description="Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + max_length=20, ), ] = None - - -class RealtimeBetaResponseCreateParams(BaseModel): - modalities: Annotated[ - Optional[List[Literal['text', 'audio']]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The set of modalities the model can respond with. To disable audio,\nset this to ["text"].\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None - instructions: Annotated[ - Optional[str], + temperature: Annotated[ + Optional[float], Field( - description='The default system instructions (i.e. system message) prepended to model \ncalls. This field allows the client to guide the model on desired \nresponses. The model can be instructed on response content and format, \n(e.g. "be extremely succinct", "act friendly", "here are examples of good \nresponses") and on audio behavior (e.g. "talk quickly", "inject emotion \ninto your voice", "laugh frequently"). The instructions are not guaranteed \nto be followed by the model, but they provide guidance to the model on the \ndesired behavior.\n\nNote that the server sets default instructions which will be used if this \nfield is not set and are visible in the `session.created` event at the \nstart of the session.\n' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + examples=[1], + ge=0.0, + le=2.0, ), - ] = None - voice: Annotated[ - Optional[VoiceIdsShared], + ] = 1 + top_p: Annotated[ + Optional[float], Field( - description='The voice the model uses to respond. Voice cannot be changed during the \nsession once the model has responded with audio at least once. Current \nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n' + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + examples=[1], + ge=0.0, + le=1.0, ), - ] = None - output_audio_format: Annotated[ - Optional[Literal['pcm16', 'g711_ulaw', 'g711_alaw']], + ] = 1 + stream: Annotated[ + Optional[bool], Field( - description='The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n' + description="If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" ), ] = None - tools: Annotated[ - Optional[List[Tool1]], - Field(description='Tools (functions) available to the model.'), - ] = None - tool_choice: Annotated[ - Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], + max_prompt_tokens: Annotated[ + Optional[int], Field( - description='How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n' + description="The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, ), - ] = 'auto' - temperature: Annotated[ - Optional[float], + ] = None + max_completion_tokens: Annotated[ + Optional[int], Field( - description='Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n' + description="The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, ), ] = None - max_output_tokens: Annotated[ - Optional[Union[int, Literal['inf']]], + truncation_strategy: Optional[TruncationObject] = None + tool_choice: Optional[AssistantsApiToolChoiceOption] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + response_format: Optional[AssistantsApiResponseFormatOption] = None + + +class CreateThreadRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + messages: Annotated[ + Optional[List[CreateMessageRequest]], Field( - description='Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n' + description="A list of [messages](/docs/api-reference/messages) to start the thread with." ), ] = None - conversation: Annotated[ - Optional[Union[str, Literal['auto', 'none']]], + tool_resources: Annotated[ + Optional[ToolResources5], Field( - description='Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which \nwill not add items to default conversation.\n' + description="A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" ), ] = None - metadata: Optional[Metadata] = None - prompt: Optional[Prompt2] = None - input: Annotated[ - Optional[List[RealtimeConversationItem]], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items from the default conversation.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] = None -class RealtimeBetaServerEventConversationItemCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.created'], - Field(description='The event type, must be `conversation.item.created`.'), - ] - previous_item_id: Optional[str] = None - item: RealtimeConversationItem - - -class RealtimeBetaServerEventConversationItemRetrieved(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['conversation.item.retrieved'], - Field(description='The event type, must be `conversation.item.retrieved`.'), - ] - item: RealtimeConversationItem - - -class RealtimeBetaServerEventResponseCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.created'], - Field(description='The event type, must be `response.created`.'), - ] - response: RealtimeBetaResponse - - -class RealtimeBetaServerEventResponseDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.done'], - Field(description='The event type, must be `response.done`.'), - ] - response: RealtimeBetaResponse - - -class RealtimeBetaServerEventResponseOutputItemAdded(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_item.added'], - Field(description='The event type, must be `response.output_item.added`.'), - ] - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') - ] - item: RealtimeConversationItem - - -class RealtimeBetaServerEventResponseOutputItemDone(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['response.output_item.done'], - Field(description='The event type, must be `response.output_item.done`.'), - ] - response_id: Annotated[ - str, Field(description='The ID of the Response to which the item belongs.') - ] - output_index: Annotated[ - int, Field(description='The index of the output item in the Response.') +class MessageObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), ] - item: RealtimeConversationItem - - -class RealtimeBetaServerEventSessionCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['session.created'], - Field(description='The event type, must be `session.created`.'), + object: Annotated[ + Literal["thread.message"], + Field(description="The object type, which is always `thread.message`."), ] - session: RealtimeSession - - -class RealtimeBetaServerEventSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['session.updated'], - Field(description='The event type, must be `session.updated`.'), + created_at: Annotated[ + int, + Field(description="The Unix timestamp (in seconds) for when the message was created."), ] - session: RealtimeSession - - -class RealtimeCallCreateRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - sdp: Annotated[ + thread_id: Annotated[ str, Field( - description='WebRTC Session Description Protocol (SDP) offer generated by the caller.' + description="The [thread](/docs/api-reference/threads) ID that this message belongs to." ), ] - session: Annotated[ - Optional[RealtimeSessionCreateRequestGA], + status: Annotated[ + Literal["in_progress", "incomplete", "completed"], Field( - description='Optional session configuration to apply before the realtime session is\ncreated. Use the same parameters you would send in a [`create client secret`](https://platform.openai.com/docs/api-reference/realtime-sessions/create-realtime-client-secret)\nrequest.', - title='Session configuration', + description="The status of the message, which can be either `in_progress`, `incomplete`, or `completed`." ), + ] + incomplete_details: Annotated[ + Optional[IncompleteDetails1], + Field(description="On an incomplete message, details about why the message is incomplete."), + ] + completed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the message was completed."), ] = None - - -class RealtimeClientEventConversationItemCreate(BaseModel): - event_id: Annotated[ - Optional[str], + incomplete_at: Annotated[ + Optional[int], Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, + description="The Unix timestamp (in seconds) for when the message was marked as incomplete." ), ] = None - type: Annotated[ - Literal['conversation.item.create'], - Field(description='The event type, must be `conversation.item.create`.'), + role: Annotated[ + Literal["user", "assistant"], + Field(description="The entity that produced the message. One of `user` or `assistant`."), + ] + content: Annotated[ + List[ + Union[ + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageContentTextObject, + MessageContentRefusalObject, + ] + ], + Field(description="The content of the message in array of text and/or images."), ] - previous_item_id: Annotated[ + assistant_id: Annotated[ Optional[str], Field( - description='The ID of the preceding item after which the new item will be inserted. \nIf not set, the new item will be appended to the end of the conversation.\nIf set to `root`, the new item will be added to the beginning of the conversation.\nIf set to an existing ID, it allows an item to be inserted mid-conversation. If the\nID cannot be found, an error will be returned and the item will not be added.\n' + description="If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message." ), ] = None - item: RealtimeConversationItem - - -class RealtimeClientEventResponseCreate(BaseModel): - event_id: Annotated[ + run_id: Annotated[ Optional[str], Field( - description='Optional client-generated ID used to identify this event.', - max_length=512, + description="The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints." ), ] = None - type: Annotated[ - Literal['response.create'], - Field(description='The event type, must be `response.create`.'), - ] - response: Optional[RealtimeResponseCreateParams] = None - - -class RealtimeClientEventSessionUpdate(BaseModel): - event_id: Annotated[ - Optional[str], + attachments: Annotated[ + Optional[List[Attachment]], Field( - description='Optional client-generated ID used to identify this event. This is an arbitrary string that a client may assign. It will be passed back if there is an error with the event, but the corresponding `session.updated` event will not include it.', - max_length=512, + description="A list of files attached to the message, and the tools they were added to." ), - ] = None - type: Annotated[ - Literal['session.update'], - Field(description='The event type, must be `session.update`.'), ] - session: Annotated[ - Union[ - RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA - ], + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='Update the Realtime session. Choose either a realtime\nsession or a transcription session.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] -class RealtimeCreateClientSecretRequest(BaseModel): - expires_after: Annotated[ - Optional[ExpiresAfter2], - Field( - description='Configuration for the client secret expiration. Expiration refers to the time after which\na client secret will no longer be valid for creating sessions. The session itself may\ncontinue after that time once started. A secret can be used to create multiple sessions\nuntil it expires.\n', - title='Client secret expiration', - ), +class Delta(BaseModel): + role: Annotated[ + Optional[Literal["user", "assistant"]], + Field(description="The entity that produced the message. One of `user` or `assistant`."), ] = None - session: Annotated[ + content: Annotated[ Optional[ - Union[ - RealtimeSessionCreateRequestGA, - RealtimeTranscriptionSessionCreateRequestGA, + List[ + Union[ + MessageDeltaContentImageFileObject, + MessageDeltaContentTextObject, + MessageDeltaContentRefusalObject, + MessageDeltaContentImageUrlObject, + ] ] ], - Field( - description='Session configuration to use for the client secret. Choose either a realtime\nsession or a transcription session.\n', - discriminator='type', - title='Session configuration', - ), + Field(description="The content of the message in array of text and/or images."), ] = None -class RealtimeCreateClientSecretResponse(BaseModel): - value: Annotated[str, Field(description='The generated client secret value.')] - expires_at: Annotated[ - int, +class MessageDeltaObject(BaseModel): + id: Annotated[ + str, Field( - description='Expiration timestamp for the client secret, in seconds since epoch.' + description="The identifier of the message, which can be referenced in API endpoints." ), ] - session: Annotated[ - Union[ - RealtimeSessionCreateResponseGA, - RealtimeTranscriptionSessionCreateResponseGA, - ], - Field( - description='The session configuration for either a realtime or transcription session.\n', - discriminator='type', - title='Session configuration', - ), + object: Annotated[ + Literal["thread.message.delta"], + Field(description="The object type, which is always `thread.message.delta`."), + ] + delta: Annotated[ + Delta, + Field(description="The delta containing the fields that have changed on the Message."), ] -class RealtimeServerEventSessionCreated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['session.created'], - Field(description='The event type, must be `session.created`.'), - ] - session: Annotated[ - Union[ - RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA +class ListMessagesResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[MessageObject] + first_id: Annotated[str, Field(examples=["msg_abc123"])] + last_id: Annotated[str, Field(examples=["msg_abc123"])] + has_more: Annotated[bool, Field(examples=[False])] + + +class RunStepDetailsToolCallsObject(BaseModel): + type: Annotated[Literal["tool_calls"], Field(description="Always `tool_calls`.")] + tool_calls: Annotated[ + List[ + Union[ + RunStepDetailsToolCallsCodeObject, + RunStepDetailsToolCallsFileSearchObject, + RunStepDetailsToolCallsFunctionObject, + ] ], - Field(description='The session configuration.'), + Field( + description="An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n" + ), ] -class RealtimeServerEventSessionUpdated(BaseModel): - event_id: Annotated[str, Field(description='The unique ID of the server event.')] - type: Annotated[ - Literal['session.updated'], - Field(description='The event type, must be `session.updated`.'), - ] - session: Annotated[ - Union[ - RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA +class RunStepDeltaStepDetailsToolCallsObject(BaseModel): + type: Annotated[Literal["tool_calls"], Field(description="Always `tool_calls`.")] + tool_calls: Annotated[ + Optional[ + List[ + Union[ + RunStepDeltaStepDetailsToolCallsCodeObject, + RunStepDeltaStepDetailsToolCallsFileSearchObject, + RunStepDeltaStepDetailsToolCallsFunctionObject, + ] + ] ], - Field(description='The session configuration.'), - ] + Field( + description="An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n" + ), + ] = None -class ResponseItemList(BaseModel): - object: Annotated[ - Literal['list'], - Field(description='The type of object returned, must be `list`.'), - ] - data: Annotated[ - List[ItemResource], - Field(description='A list of items used to generate this response.'), +class VectorStoreFileObject(BaseModel): + id: Annotated[ + str, + Field(description="The identifier, which can be referenced in API endpoints."), ] - has_more: Annotated[ - bool, Field(description='Whether there are more items available.') + object: Annotated[ + Literal["vector_store.file"], + Field(description="The object type, which is always `vector_store.file`."), ] - first_id: Annotated[str, Field(description='The ID of the first item in the list.')] - last_id: Annotated[str, Field(description='The ID of the last item in the list.')] - - -class ResponseOutputItemAddedEvent(BaseModel): - type: Annotated[ - Literal['ResponseOutputItemAddedEvent'], + usage_bytes: Annotated[ + int, Field( - description='The type of the event. Always `response.output_item.added`.\n' + description="The total vector store usage in bytes. Note that this may be different from the original file size." ), ] - output_index: Annotated[ - int, Field(description='The index of the output item that was added.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') - ] - item: Annotated[OutputItem1, Field(description='The output item that was added.\n')] - - -class ResponseOutputItemDoneEvent(BaseModel): - type: Annotated[ - Literal['ResponseOutputItemDoneEvent'], + created_at: Annotated[ + int, Field( - description='The type of the event. Always `response.output_item.done`.\n' + description="The Unix timestamp (in seconds) for when the vector store file was created." ), ] - output_index: Annotated[ - int, Field(description='The index of the output item that was marked done.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.\n') + vector_store_id: Annotated[ + str, + Field( + description="The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to." + ), ] - item: Annotated[ - OutputItem1, Field(description='The output item that was marked done.\n') + status: Annotated[ + Literal["in_progress", "completed", "cancelled", "failed"], + Field( + description="The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use." + ), ] - - -class ResponseProperties(BaseModel): - previous_response_id: Optional[str] = None - model: Annotated[ - Optional[ModelIdsResponses], + last_error: Annotated[ + Optional[LastError2], Field( - description='Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\nto browse and compare available models.\n' + description="The last error associated with this vector store file. Will be `null` if there are no errors." ), + ] + chunking_strategy: Annotated[ + Optional[Union[StaticChunkingStrategyResponseParam, OtherChunkingStrategyResponseParam]], + Field(description="The strategy used to chunk the file."), ] = None - reasoning: Optional[Reasoning] = None - background: Optional[bool] = None - max_output_tokens: Optional[int] = None - max_tool_calls: Optional[int] = None - text: Optional[ResponseTextParam] = None - tools: Optional[ToolsArray] = None - prompt: Optional[Prompt2] = None - truncation: Optional[Literal['auto', 'disabled']] = None -class RunObject(BaseModel): - id: Annotated[ - str, - Field(description='The identifier, which can be referenced in API endpoints.'), +class ListVectorStoreFilesResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[VectorStoreFileObject] + first_id: Annotated[str, Field(examples=["file-abc123"])] + last_id: Annotated[str, Field(examples=["file-abc456"])] + has_more: Annotated[bool, Field(examples=[False])] + + +class MessageStreamEvent1(BaseModel): + event: Literal["thread.message.created"] + data: MessageObject + + +class MessageStreamEvent2(BaseModel): + event: Literal["thread.message.in_progress"] + data: MessageObject + + +class MessageStreamEvent3(BaseModel): + event: Literal["thread.message.delta"] + data: MessageDeltaObject + + +class MessageStreamEvent4(BaseModel): + event: Literal["thread.message.completed"] + data: MessageObject + + +class MessageStreamEvent5(BaseModel): + event: Literal["thread.message.incomplete"] + data: MessageObject + + +class MessageStreamEvent( + RootModel[ + Union[ + MessageStreamEvent1, + MessageStreamEvent2, + MessageStreamEvent3, + MessageStreamEvent4, + MessageStreamEvent5, + ] ] - object: Annotated[ - Literal['thread.run'], - Field(description='The object type, which is always `thread.run`.'), +): + root: Union[ + MessageStreamEvent1, + MessageStreamEvent2, + MessageStreamEvent3, + MessageStreamEvent4, + MessageStreamEvent5, ] - created_at: Annotated[ - int, + + +class ChatCompletionRequestMessage( + RootModel[ + Union[ + ChatCompletionRequestSystemMessage, + ChatCompletionRequestUserMessage, + ChatCompletionRequestAssistantMessage, + ChatCompletionRequestToolMessage, + ChatCompletionRequestFunctionMessage, + ] + ] +): + root: Annotated[ + Union[ + ChatCompletionRequestSystemMessage, + ChatCompletionRequestUserMessage, + ChatCompletionRequestAssistantMessage, + ChatCompletionRequestToolMessage, + ChatCompletionRequestFunctionMessage, + ], + Field(discriminator="role"), + ] + + +class CreateChatCompletionRequest(BaseModel): + messages: Annotated[ + List[ChatCompletionRequestMessage], Field( - description='The Unix timestamp (in seconds) for when the run was created.' + description="A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models).", + min_length=1, ), ] - thread_id: Annotated[ - str, + model: Annotated[ + Union[ + str, + Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "chatgpt-4o-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ], Field( - description='The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed on as a part of this run.' + description="ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API.", + examples=["gpt-4o"], ), ] - assistant_id: Annotated[ - str, + frequency_penalty: Annotated[ + Optional[float], Field( - description='The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for execution of this run.' + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] - status: RunStatus - required_action: Annotated[ - Optional[RequiredAction], + ] = 0 + logit_bias: Annotated[ + Optional[Dict[str, int]], Field( - description='Details on the action required to continue the run. Will be `null` if no action is required.' + description="Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n" ), - ] - last_error: Annotated[ - Optional[LastError], + ] = None + logprobs: Annotated[ + Optional[bool], Field( - description='The last error associated with this run. Will be `null` if there are no errors.' + description="Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`." ), - ] - expires_at: Annotated[ + ] = False + top_logprobs: Annotated[ Optional[int], Field( - description='The Unix timestamp (in seconds) for when the run will expire.' + description="An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used.", + ge=0, + le=20, ), ] = None - started_at: Annotated[ + max_tokens: Annotated[ Optional[int], Field( - description='The Unix timestamp (in seconds) for when the run was started.' + description="The maximum number of [tokens](/tokenizer) that can be generated in the chat completion.\n\nThe total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n" ), ] = None - cancelled_at: Annotated[ + n: Annotated[ Optional[int], Field( - description='The Unix timestamp (in seconds) for when the run was cancelled.' + description="How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs.", + examples=[1], + ge=1, + le=128, ), - ] = None - failed_at: Annotated[ - Optional[int], - Field(description='The Unix timestamp (in seconds) for when the run failed.'), - ] = None - completed_at: Annotated[ - Optional[int], + ] = 1 + presence_penalty: Annotated[ + Optional[float], Field( - description='The Unix timestamp (in seconds) for when the run was completed.' + description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)\n", + ge=-2.0, + le=2.0, ), - ] = None - incomplete_details: Annotated[ - Optional[IncompleteDetails2], + ] = 0 + response_format: Annotated[ + Optional[Union[ResponseFormatText, ResponseFormatJsonObject, ResponseFormatJsonSchema]], Field( - description='Details on why the run is incomplete. Will be `null` if the run is not incomplete.' + description='An object specifying the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4o mini](/docs/models/gpt-4o-mini), [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`.\n\nSetting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs).\n\nSetting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n' ), - ] - model: Annotated[ - str, + ] = None + seed: Annotated[ + Optional[int], Field( - description='The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.' + description="This feature is in Beta.\nIf specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n", + ge=-9223372036854775808, + le=9223372036854775807, ), - ] - instructions: Annotated[ - str, + ] = None + service_tier: Annotated[ + Optional[Literal["auto", "default"]], Field( - description='The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.' + description="Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:\n - If set to 'auto', the system will utilize scale tier credits until they are exhausted.\n - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee.\n - When not set, the default behavior is 'auto'.\n\n When this parameter is set, the response body will include the `service_tier` utilized.\n" ), - ] - tools: Annotated[ - List[AssistantTool], + ] = None + stop: Annotated[ + Union[Optional[str], Stop1], + Field(description="Up to 4 sequences where the API will stop generating further tokens.\n"), + ] = None + stream: Annotated[ + Optional[bool], Field( - description='The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.', - max_length=20, + description="If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n" ), - ] - metadata: Metadata - usage: RunCompletionUsage + ] = False + stream_options: Optional[ChatCompletionStreamOptions] = None temperature: Annotated[ Optional[float], Field( - description='The sampling temperature used for this run. If not set, defaults to 1.' + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n", + examples=[1], + ge=0.0, + le=2.0, ), - ] = None + ] = 1 top_p: Annotated[ Optional[float], Field( - description='The nucleus sampling value used for this run. If not set, defaults to 1.' + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n", + examples=[1], + ge=0.0, + le=1.0, + ), + ] = 1 + tools: Annotated[ + Optional[List[ChatCompletionTool]], + Field( + description="A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n" ), ] = None - max_prompt_tokens: Annotated[ - Optional[int], + tool_choice: Optional[ChatCompletionToolChoiceOption] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + user: Annotated[ + Optional[str], Field( - description='The maximum number of prompt tokens specified to have been used over the course of the run.\n', - ge=256, + description="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).\n", + examples=["user-1234"], ), ] = None - max_completion_tokens: Annotated[ - Optional[int], + function_call: Annotated[ + Optional[Union[Literal["none", "auto"], ChatCompletionFunctionCallOption]], Field( - description='The maximum number of completion tokens specified to have been used over the course of the run.\n', - ge=256, + description='Deprecated in favor of `tool_choice`.\n\nControls which (if any) function is called by the model.\n`none` means the model will not call a function and instead generates a message.\n`auto` means the model can pick between generating a message or calling a function.\nSpecifying a particular function via `{"name": "my_function"}` forces the model to call that function.\n\n`none` is the default when no functions are present. `auto` is the default if functions are present.\n' + ), + ] = None + functions: Annotated[ + Optional[List[ChatCompletionFunctions]], + Field( + description="Deprecated in favor of `tools`.\n\nA list of functions the model may generate JSON inputs for.\n", + max_length=128, + min_length=1, ), ] = None - truncation_strategy: TruncationObject - tool_choice: AssistantsApiToolChoiceOption - parallel_tool_calls: ParallelToolCalls - response_format: Annotated[Optional[AssistantsApiResponseFormatOption], Field(...)] -class RunStepDeltaObject(BaseModel): - id: Annotated[ +class CreateThreadAndRunRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + assistant_id: Annotated[ str, Field( - description='The identifier of the run step, which can be referenced in API endpoints.' + description="The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run." ), ] - object: Annotated[ - Literal['thread.run.step.delta'], - Field(description='The object type, which is always `thread.run.step.delta`.'), - ] - delta: RunStepDeltaObjectDelta - - -class RunStepStreamEvent3(BaseModel): - event: Literal['2#-datamodel-code-generator-#-object-#-special-#'] - data: RunStepDeltaObject - - -class RunStepStreamEvent( - RootModel[ - Union[ - RunStepStreamEvent1, - RunStepStreamEvent2, - RunStepStreamEvent3, - RunStepStreamEvent4, - RunStepStreamEvent5, - RunStepStreamEvent6, - RunStepStreamEvent7, - ] - ] -): - root: Annotated[ - Union[ - RunStepStreamEvent1, - RunStepStreamEvent2, - RunStepStreamEvent3, - RunStepStreamEvent4, - RunStepStreamEvent5, - RunStepStreamEvent6, - RunStepStreamEvent7, - ], - Field(discriminator='event'), - ] - - -class RunStreamEvent1(BaseModel): - event: Literal['0#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent2(BaseModel): - event: Literal['1#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent3(BaseModel): - event: Literal['2#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent4(BaseModel): - event: Literal['3#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent5(BaseModel): - event: Literal['4#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent6(BaseModel): - event: Literal['5#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent7(BaseModel): - event: Literal['6#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent8(BaseModel): - event: Literal['7#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent9(BaseModel): - event: Literal['8#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent10(BaseModel): - event: Literal['9#-datamodel-code-generator-#-object-#-special-#'] - data: RunObject - - -class RunStreamEvent( - RootModel[ - Union[ - RunStreamEvent1, - RunStreamEvent2, - RunStreamEvent3, - RunStreamEvent4, - RunStreamEvent5, - RunStreamEvent6, - RunStreamEvent7, - RunStreamEvent8, - RunStreamEvent9, - RunStreamEvent10, - ] - ] -): - root: Annotated[ - Union[ - RunStreamEvent1, - RunStreamEvent2, - RunStreamEvent3, - RunStreamEvent4, - RunStreamEvent5, - RunStreamEvent6, - RunStreamEvent7, - RunStreamEvent8, - RunStreamEvent9, - RunStreamEvent10, + thread: Annotated[ + Optional[CreateThreadRequest], + Field(description="If no thread is provided, an empty thread will be created."), + ] = None + model: Annotated[ + Optional[ + Union[ + Optional[str], + Literal[ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] ], - Field(discriminator='event'), - ] - - -class FineTuneMethod(BaseModel): - type: Annotated[ - Literal['supervised', 'dpo', 'reinforcement'], Field( - description='The type of method. Is either `supervised`, `dpo`, or `reinforcement`.' + description="The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + examples=["gpt-4o"], + ), + ] = None + instructions: Annotated[ + Optional[str], + Field( + description="Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis." + ), + ] = None + tools: Annotated[ + Optional[List[Union[AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction]]], + Field( + description="Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + max_length=20, + ), + ] = None + tool_resources: Annotated[ + Optional[ToolResources3], + Field( + description="A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + ), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], + Field( + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" + ), + ] = None + temperature: Annotated[ + Optional[float], + Field( + description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + examples=[1], + ge=0.0, + le=2.0, + ), + ] = 1 + top_p: Annotated[ + Optional[float], + Field( + description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n", + examples=[1], + ge=0.0, + le=1.0, + ), + ] = 1 + stream: Annotated[ + Optional[bool], + Field( + description="If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" ), - ] - supervised: Optional[FineTuneSupervisedMethod] = None - dpo: Optional[FineTuneDPOMethod] = None - reinforcement: Optional[FineTuneReinforcementMethod] = None + ] = None + max_prompt_tokens: Annotated[ + Optional[int], + Field( + description="The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, + ), + ] = None + max_completion_tokens: Annotated[ + Optional[int], + Field( + description="The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + ge=256, + ), + ] = None + truncation_strategy: Optional[TruncationObject] = None + tool_choice: Optional[AssistantsApiToolChoiceOption] = None + parallel_tool_calls: Optional[ParallelToolCalls] = None + response_format: Optional[AssistantsApiResponseFormatOption] = None -class FineTuningJob(BaseModel): +class RunStepObject(BaseModel): id: Annotated[ str, Field( - description='The object identifier, which can be referenced in the API endpoints.' + description="The identifier of the run step, which can be referenced in API endpoints." ), ] + object: Annotated[ + Literal["thread.run.step"], + Field(description="The object type, which is always `thread.run.step`."), + ] created_at: Annotated[ int, - Field( - description='The Unix timestamp (in seconds) for when the fine-tuning job was created.' - ), + Field(description="The Unix timestamp (in seconds) for when the run step was created."), ] - error: Optional[Error2] = None - fine_tuned_model: Optional[str] = None - finished_at: Optional[int] = None - hyperparameters: Annotated[ - Hyperparameters1, + assistant_id: Annotated[ + str, Field( - description='The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs.' + description="The ID of the [assistant](/docs/api-reference/assistants) associated with the run step." ), ] - model: Annotated[str, Field(description='The base model that is being fine-tuned.')] - object: Annotated[ - Literal['fine_tuning.job'], - Field(description='The object type, which is always "fine_tuning.job".'), - ] - organization_id: Annotated[ - str, Field(description='The organization that owns the fine-tuning job.') + thread_id: Annotated[ + str, + Field(description="The ID of the [thread](/docs/api-reference/threads) that was run."), ] - result_files: Annotated[ - List[str], + run_id: Annotated[ + str, Field( - description='The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).' + description="The ID of the [run](/docs/api-reference/runs) that this run step is a part of." ), ] - status: Annotated[ - Literal[ - 'validating_files', 'queued', 'running', 'succeeded', 'failed', 'cancelled' - ], + type: Annotated[ + Literal["message_creation", "tool_calls"], Field( - description='The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.' + description="The type of run step, which can be either `message_creation` or `tool_calls`." ), ] - trained_tokens: Optional[int] = None - training_file: Annotated[ - str, + status: Annotated[ + Literal["in_progress", "cancelled", "failed", "completed", "expired"], Field( - description='The file ID used for training. You can retrieve the training data with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).' + description="The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`." ), ] - validation_file: Optional[str] = None - integrations: Optional[Integrations] = None - seed: Annotated[int, Field(description='The seed used for the fine-tuning job.')] - estimated_finish: Optional[int] = None - method: Optional[FineTuneMethod] = None - metadata: Optional[Metadata] = None - - -class InputItem1(RootModel[Union[EasyInputMessage, Item, ItemReferenceParam]]): - root: Annotated[ - Union[EasyInputMessage, Item, ItemReferenceParam], Field(discriminator='type') + step_details: Annotated[ + Union[RunStepDetailsMessageCreationObject, RunStepDetailsToolCallsObject], + Field(description="The details of the run step."), ] - - -class InputParam(RootModel[Union[str, List[InputItem1]]]): - root: Annotated[ - Union[str, List[InputItem1]], + last_error: Annotated[ + Optional[LastError1], Field( - description='Text, image, or file inputs to the model, used to generate a response.\n\nLearn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Image inputs](https://platform.openai.com/docs/guides/images)\n- [File inputs](https://platform.openai.com/docs/guides/pdf-files)\n- [Conversation state](https://platform.openai.com/docs/guides/conversation-state)\n- [Function calling](https://platform.openai.com/docs/guides/function-calling)\n' + description="The last error associated with this run step. Will be `null` if there are no errors." ), ] - - -class ListPaginatedFineTuningJobsResponse(BaseModel): - data: List[FineTuningJob] - has_more: bool - object: Literal['list'] - - -class ListRunsResponse(BaseModel): - object: Annotated[str, Field(examples=['list'])] - data: List[RunObject] - first_id: Annotated[str, Field(examples=['run_abc123'])] - last_id: Annotated[str, Field(examples=['run_abc456'])] - has_more: Annotated[bool, Field(examples=[False])] - - -class RealtimeBetaClientEventResponseCreate(BaseModel): - event_id: Annotated[ - Optional[str], - Field(description='Optional client-generated ID used to identify this event.'), + expired_at: Annotated[ + Optional[int], + Field( + description="The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired." + ), ] = None - type: Annotated[ - Literal['response.create'], - Field(description='The event type, must be `response.create`.'), - ] - response: Optional[RealtimeBetaResponseCreateParams] = None - - -class RealtimeClientEvent( - RootModel[ - Union[ - RealtimeClientEventConversationItemCreate, - RealtimeClientEventConversationItemDelete, - RealtimeClientEventConversationItemRetrieve, - RealtimeClientEventConversationItemTruncate, - RealtimeClientEventInputAudioBufferAppend, - RealtimeClientEventInputAudioBufferClear, - RealtimeClientEventOutputAudioBufferClear, - RealtimeClientEventInputAudioBufferCommit, - RealtimeClientEventResponseCancel, - RealtimeClientEventResponseCreate, - RealtimeClientEventSessionUpdate, - ] - ] -): - root: Annotated[ - Union[ - RealtimeClientEventConversationItemCreate, - RealtimeClientEventConversationItemDelete, - RealtimeClientEventConversationItemRetrieve, - RealtimeClientEventConversationItemTruncate, - RealtimeClientEventInputAudioBufferAppend, - RealtimeClientEventInputAudioBufferClear, - RealtimeClientEventOutputAudioBufferClear, - RealtimeClientEventInputAudioBufferCommit, - RealtimeClientEventResponseCancel, - RealtimeClientEventResponseCreate, - RealtimeClientEventSessionUpdate, - ], - Field(description='A realtime client event.\n', discriminator='type'), - ] - - -class RealtimeServerEvent( - RootModel[ - Union[ - RealtimeServerEventConversationCreated, - RealtimeServerEventConversationItemCreated, - RealtimeServerEventConversationItemDeleted, - RealtimeServerEventConversationItemInputAudioTranscriptionCompleted, - RealtimeServerEventConversationItemInputAudioTranscriptionDelta, - RealtimeServerEventConversationItemInputAudioTranscriptionFailed, - RealtimeServerEventConversationItemRetrieved, - RealtimeServerEventConversationItemTruncated, - RealtimeServerEventError, - RealtimeServerEventInputAudioBufferCleared, - RealtimeServerEventInputAudioBufferCommitted, - RealtimeServerEventInputAudioBufferSpeechStarted, - RealtimeServerEventInputAudioBufferSpeechStopped, - RealtimeServerEventRateLimitsUpdated, - RealtimeServerEventResponseAudioDelta, - RealtimeServerEventResponseAudioDone, - RealtimeServerEventResponseAudioTranscriptDelta, - RealtimeServerEventResponseAudioTranscriptDone, - RealtimeServerEventResponseContentPartAdded, - RealtimeServerEventResponseContentPartDone, - RealtimeServerEventResponseCreated, - RealtimeServerEventResponseDone, - RealtimeServerEventResponseFunctionCallArgumentsDelta, - RealtimeServerEventResponseFunctionCallArgumentsDone, - RealtimeServerEventResponseOutputItemAdded, - RealtimeServerEventResponseOutputItemDone, - RealtimeServerEventResponseTextDelta, - RealtimeServerEventResponseTextDone, - RealtimeServerEventSessionCreated, - RealtimeServerEventSessionUpdated, - RealtimeServerEventOutputAudioBufferStarted, - RealtimeServerEventOutputAudioBufferStopped, - RealtimeServerEventOutputAudioBufferCleared, - RealtimeServerEventConversationItemAdded, - RealtimeServerEventConversationItemDone, - RealtimeServerEventInputAudioBufferTimeoutTriggered, - RealtimeServerEventConversationItemInputAudioTranscriptionSegment, - RealtimeServerEventMCPListToolsInProgress, - RealtimeServerEventMCPListToolsCompleted, - RealtimeServerEventMCPListToolsFailed, - RealtimeServerEventResponseMCPCallArgumentsDelta, - RealtimeServerEventResponseMCPCallArgumentsDone, - RealtimeServerEventResponseMCPCallInProgress, - RealtimeServerEventResponseMCPCallCompleted, - RealtimeServerEventResponseMCPCallFailed, - ] - ] -): - root: Annotated[ - Union[ - RealtimeServerEventConversationCreated, - RealtimeServerEventConversationItemCreated, - RealtimeServerEventConversationItemDeleted, - RealtimeServerEventConversationItemInputAudioTranscriptionCompleted, - RealtimeServerEventConversationItemInputAudioTranscriptionDelta, - RealtimeServerEventConversationItemInputAudioTranscriptionFailed, - RealtimeServerEventConversationItemRetrieved, - RealtimeServerEventConversationItemTruncated, - RealtimeServerEventError, - RealtimeServerEventInputAudioBufferCleared, - RealtimeServerEventInputAudioBufferCommitted, - RealtimeServerEventInputAudioBufferSpeechStarted, - RealtimeServerEventInputAudioBufferSpeechStopped, - RealtimeServerEventRateLimitsUpdated, - RealtimeServerEventResponseAudioDelta, - RealtimeServerEventResponseAudioDone, - RealtimeServerEventResponseAudioTranscriptDelta, - RealtimeServerEventResponseAudioTranscriptDone, - RealtimeServerEventResponseContentPartAdded, - RealtimeServerEventResponseContentPartDone, - RealtimeServerEventResponseCreated, - RealtimeServerEventResponseDone, - RealtimeServerEventResponseFunctionCallArgumentsDelta, - RealtimeServerEventResponseFunctionCallArgumentsDone, - RealtimeServerEventResponseOutputItemAdded, - RealtimeServerEventResponseOutputItemDone, - RealtimeServerEventResponseTextDelta, - RealtimeServerEventResponseTextDone, - RealtimeServerEventSessionCreated, - RealtimeServerEventSessionUpdated, - RealtimeServerEventOutputAudioBufferStarted, - RealtimeServerEventOutputAudioBufferStopped, - RealtimeServerEventOutputAudioBufferCleared, - RealtimeServerEventConversationItemAdded, - RealtimeServerEventConversationItemDone, - RealtimeServerEventInputAudioBufferTimeoutTriggered, - RealtimeServerEventConversationItemInputAudioTranscriptionSegment, - RealtimeServerEventMCPListToolsInProgress, - RealtimeServerEventMCPListToolsCompleted, - RealtimeServerEventMCPListToolsFailed, - RealtimeServerEventResponseMCPCallArgumentsDelta, - RealtimeServerEventResponseMCPCallArgumentsDone, - RealtimeServerEventResponseMCPCallInProgress, - RealtimeServerEventResponseMCPCallCompleted, - RealtimeServerEventResponseMCPCallFailed, - ], - Field(description='A realtime server event.\n', discriminator='type'), - ] - - -class Response1(ModelResponseProperties, ResponseProperties): - id: Annotated[str, Field(description='Unique identifier for this Response.\n')] - object: Annotated[ - Literal['response'], + cancelled_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run step was cancelled."), + ] = None + failed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run step failed."), + ] = None + completed_at: Annotated[ + Optional[int], + Field(description="The Unix timestamp (in seconds) for when the run step completed."), + ] = None + metadata: Annotated[ + Optional[Dict[str, Any]], Field( - description='The object type of this resource - always set to `response`.\n' + description="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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.\n" ), ] - status: Annotated[ + usage: RunStepCompletionUsage + + +class Delta1(BaseModel): + step_details: Annotated[ Optional[ - Literal[ - 'completed', - 'failed', - 'in_progress', - 'cancelled', - 'queued', - 'incomplete', + Union[ + RunStepDeltaStepDetailsMessageCreationObject, + RunStepDeltaStepDetailsToolCallsObject, ] ], - Field( - description='The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n' - ), + Field(description="The details of the run step."), ] = None - created_at: Annotated[ - float, + + +class RunStepDeltaObject(BaseModel): + id: Annotated[ + str, Field( - description='Unix timestamp (in seconds) of when this Response was created.\n' + description="The identifier of the run step, which can be referenced in API endpoints." ), ] - error: ResponseError - incomplete_details: Optional[IncompleteDetails1] = None - output: Annotated[ - List[OutputItem1], - Field( - description="An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" - ), + object: Annotated[ + Literal["thread.run.step.delta"], + Field(description="The object type, which is always `thread.run.step.delta`."), ] - instructions: Optional[Union[str, List[InputItem1]]] = None - output_text: Optional[str] = None - usage: Optional[ResponseUsage] = None - parallel_tool_calls: Annotated[ - bool, - Field( - description='Whether to allow the model to run tool calls in parallel.\n' - ), + delta: Annotated[ + Delta1, + Field(description="The delta containing the fields that have changed on the run step."), ] - conversation: Optional[Conversation2] = None -class ResponseCompletedEvent(BaseModel): - type: Annotated[ - Literal['ResponseCompletedEvent'], - Field(description='The type of the event. Always `response.completed`.\n'), - ] - response: Annotated[ - Response1, Field(description='Properties of the completed response.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] +class ListRunStepsResponse(BaseModel): + object: Annotated[str, Field(examples=["list"])] + data: List[RunStepObject] + first_id: Annotated[str, Field(examples=["step_abc123"])] + last_id: Annotated[str, Field(examples=["step_abc456"])] + has_more: Annotated[bool, Field(examples=[False])] -class ResponseCreatedEvent(BaseModel): - type: Annotated[ - Literal['ResponseCreatedEvent'], - Field(description='The type of the event. Always `response.created`.\n'), - ] - response: Annotated[ - Response1, Field(description='The response that was created.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] +class RunStepStreamEvent1(BaseModel): + event: Literal["thread.run.step.created"] + data: RunStepObject -class ResponseFailedEvent(BaseModel): - type: Annotated[ - Literal['ResponseFailedEvent'], - Field(description='The type of the event. Always `response.failed`.\n'), - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] - response: Annotated[Response1, Field(description='The response that failed.\n')] +class RunStepStreamEvent2(BaseModel): + event: Literal["thread.run.step.in_progress"] + data: RunStepObject -class ResponseInProgressEvent(BaseModel): - type: Annotated[ - Literal['ResponseInProgressEvent'], - Field(description='The type of the event. Always `response.in_progress`.\n'), - ] - response: Annotated[ - Response1, Field(description='The response that is in progress.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] +class RunStepStreamEvent3(BaseModel): + event: Literal["thread.run.step.delta"] + data: RunStepDeltaObject -class ResponseIncompleteEvent(BaseModel): - type: Annotated[ - Literal['ResponseIncompleteEvent'], - Field(description='The type of the event. Always `response.incomplete`.\n'), - ] - response: Annotated[ - Response1, Field(description='The response that was incomplete.\n') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number of this event.') - ] +class RunStepStreamEvent4(BaseModel): + event: Literal["thread.run.step.completed"] + data: RunStepObject -class ResponseQueuedEvent(BaseModel): - type: Annotated[ - Literal['ResponseQueuedEvent'], - Field(description="The type of the event. Always 'response.queued'."), - ] - response: Annotated[ - Response1, Field(description='The full response object that is queued.') - ] - sequence_number: Annotated[ - int, Field(description='The sequence number for this event.') - ] +class RunStepStreamEvent5(BaseModel): + event: Literal["thread.run.step.failed"] + data: RunStepObject + +class RunStepStreamEvent6(BaseModel): + event: Literal["thread.run.step.cancelled"] + data: RunStepObject + + +class RunStepStreamEvent7(BaseModel): + event: Literal["thread.run.step.expired"] + data: RunStepObject -class ResponseStreamEvent( + +class RunStepStreamEvent( RootModel[ Union[ - ResponseAudioDeltaEvent, - ResponseAudioDoneEvent, - ResponseAudioTranscriptDeltaEvent, - ResponseAudioTranscriptDoneEvent, - ResponseCodeInterpreterCallCodeDeltaEvent, - ResponseCodeInterpreterCallCodeDoneEvent, - ResponseCodeInterpreterCallCompletedEvent, - ResponseCodeInterpreterCallInProgressEvent, - ResponseCodeInterpreterCallInterpretingEvent, - ResponseCompletedEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, - ResponseCreatedEvent, - ResponseErrorEvent, - ResponseFileSearchCallCompletedEvent, - ResponseFileSearchCallInProgressEvent, - ResponseFileSearchCallSearchingEvent, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - ResponseInProgressEvent, - ResponseFailedEvent, - ResponseIncompleteEvent, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseReasoningSummaryPartAddedEvent, - ResponseReasoningSummaryPartDoneEvent, - ResponseReasoningSummaryTextDeltaEvent, - ResponseReasoningSummaryTextDoneEvent, - ResponseReasoningTextDeltaEvent, - ResponseReasoningTextDoneEvent, - ResponseRefusalDeltaEvent, - ResponseRefusalDoneEvent, - ResponseTextDeltaEvent, - ResponseTextDoneEvent, - ResponseWebSearchCallCompletedEvent, - ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent, - ResponseImageGenCallCompletedEvent, - ResponseImageGenCallGeneratingEvent, - ResponseImageGenCallInProgressEvent, - ResponseImageGenCallPartialImageEvent, - ResponseMCPCallArgumentsDeltaEvent, - ResponseMCPCallArgumentsDoneEvent, - ResponseMCPCallCompletedEvent, - ResponseMCPCallFailedEvent, - ResponseMCPCallInProgressEvent, - ResponseMCPListToolsCompletedEvent, - ResponseMCPListToolsFailedEvent, - ResponseMCPListToolsInProgressEvent, - ResponseOutputTextAnnotationAddedEvent, - ResponseQueuedEvent, - ResponseCustomToolCallInputDeltaEvent, - ResponseCustomToolCallInputDoneEvent, + RunStepStreamEvent1, + RunStepStreamEvent2, + RunStepStreamEvent3, + RunStepStreamEvent4, + RunStepStreamEvent5, + RunStepStreamEvent6, + RunStepStreamEvent7, ] ] ): - root: Annotated[ - Union[ - ResponseAudioDeltaEvent, - ResponseAudioDoneEvent, - ResponseAudioTranscriptDeltaEvent, - ResponseAudioTranscriptDoneEvent, - ResponseCodeInterpreterCallCodeDeltaEvent, - ResponseCodeInterpreterCallCodeDoneEvent, - ResponseCodeInterpreterCallCompletedEvent, - ResponseCodeInterpreterCallInProgressEvent, - ResponseCodeInterpreterCallInterpretingEvent, - ResponseCompletedEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, - ResponseCreatedEvent, - ResponseErrorEvent, - ResponseFileSearchCallCompletedEvent, - ResponseFileSearchCallInProgressEvent, - ResponseFileSearchCallSearchingEvent, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - ResponseInProgressEvent, - ResponseFailedEvent, - ResponseIncompleteEvent, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseReasoningSummaryPartAddedEvent, - ResponseReasoningSummaryPartDoneEvent, - ResponseReasoningSummaryTextDeltaEvent, - ResponseReasoningSummaryTextDoneEvent, - ResponseReasoningTextDeltaEvent, - ResponseReasoningTextDoneEvent, - ResponseRefusalDeltaEvent, - ResponseRefusalDoneEvent, - ResponseTextDeltaEvent, - ResponseTextDoneEvent, - ResponseWebSearchCallCompletedEvent, - ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent, - ResponseImageGenCallCompletedEvent, - ResponseImageGenCallGeneratingEvent, - ResponseImageGenCallInProgressEvent, - ResponseImageGenCallPartialImageEvent, - ResponseMCPCallArgumentsDeltaEvent, - ResponseMCPCallArgumentsDoneEvent, - ResponseMCPCallCompletedEvent, - ResponseMCPCallFailedEvent, - ResponseMCPCallInProgressEvent, - ResponseMCPListToolsCompletedEvent, - ResponseMCPListToolsFailedEvent, - ResponseMCPListToolsInProgressEvent, - ResponseOutputTextAnnotationAddedEvent, - ResponseQueuedEvent, - ResponseCustomToolCallInputDeltaEvent, - ResponseCustomToolCallInputDoneEvent, - ], - Field(discriminator='type'), + root: Union[ + RunStepStreamEvent1, + RunStepStreamEvent2, + RunStepStreamEvent3, + RunStepStreamEvent4, + RunStepStreamEvent5, + RunStepStreamEvent6, + RunStepStreamEvent7, ] -class Items(RootModel[List[InputItem1]]): - root: Annotated[ - List[InputItem1], - Field( - description='Initial items to include in the conversation context. You may add up to 20 items at a time.', - max_length=20, - ), +class AssistantStreamEvent( + RootModel[ + Union[ + ThreadStreamEvent, + RunStreamEvent, + RunStepStreamEvent, + MessageStreamEvent, + ErrorEvent, + DoneEvent, + ] ] - - -class CreateConversationBody(BaseModel): - metadata: Optional[Metadata] = None - items: Optional[Items] = None - - -class TokenCountsBody(BaseModel): - model: Optional[str] = None - input: Optional[Union[Input10, List[InputItem1]]] = None - previous_response_id: Optional[str] = None - tools: Optional[List[Tool]] = None - text: Optional[ResponseTextParam] = None - reasoning: Optional[Reasoning] = None - truncation: Annotated[ - Optional[TruncationEnum], - Field( - description="The truncation strategy to use for the model response. - `auto`: If the input to this Response exceeds the model's context window size, the model will truncate the response to fit the context window by dropping items from the beginning of the conversation. - `disabled` (default): If the input size will exceed the context window size for a model, the request will fail with a 400 error." - ), - ] = None - instructions: Optional[str] = None - conversation: Optional[ConversationParam] = None - parallel_tool_calls: Optional[bool] = None - - -class CreateFineTuningJobRequest(BaseModel): - model: Annotated[ +): + root: Annotated[ Union[ - str, Literal['babbage-002', 'davinci-002', 'gpt-3.5-turbo', 'gpt-4o-mini'] + ThreadStreamEvent, + RunStreamEvent, + RunStepStreamEvent, + MessageStreamEvent, + ErrorEvent, + DoneEvent, ], Field( - description='The name of the model to fine-tune. You can select one of the\n[supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned).\n', - examples=['gpt-4o-mini'], - ), - ] - training_file: Annotated[ - str, - Field( - description='The ID of an uploaded file that contains training data.\n\nSee [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.\n\nYour dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n\nThe contents of the file should differ depending on if the model uses the [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format.\n\nSee the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n', - examples=['file-abc123'], + description='Represents an event emitted when streaming a Run.\n\nEach event in a server-sent events stream has an `event` and `data` property:\n\n```\nevent: thread.created\ndata: {"id": "thread_123", "object": "thread", ...}\n```\n\nWe emit events whenever a new object is created, transitions to a new state, or is being\nstreamed in parts (deltas). For example, we emit `thread.run.created` when a new run\nis created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses\nto create a message during a run, we emit a `thread.message.created event`, a\n`thread.message.in_progress` event, many `thread.message.delta` events, and finally a\n`thread.message.completed` event.\n\nWe may add additional events over time, so we recommend handling unknown events gracefully\nin your code. See the [Assistants API quickstart](/docs/assistants/overview) to learn how to\nintegrate the Assistants API with streaming.\n' ), ] - hyperparameters: Annotated[ - Optional[Hyperparameters], - Field( - description='The hyperparameters used for the fine-tuning job.\nThis value is now deprecated in favor of `method`, and should be passed in under the `method` parameter.\n' - ), - ] = None - suffix: Annotated[ - Optional[str], - Field( - description='A string of up to 64 characters that will be added to your fine-tuned model name.\n\nFor example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n', - max_length=64, - min_length=1, - ), - ] = None - validation_file: Annotated[ - Optional[str], - Field( - description='The ID of an uploaded file that contains validation data.\n\nIf you provide this file, the data is used to generate validation\nmetrics periodically during fine-tuning. These metrics can be viewed in\nthe fine-tuning results file.\nThe same data should not be present in both train and validation files.\n\nYour dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n\nSee the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n', - examples=['file-abc123'], - ), - ] = None - integrations: Annotated[ - Optional[List[Integration]], - Field(description='A list of integrations to enable for your fine-tuning job.'), - ] = None - seed: Annotated[ - Optional[int], - Field( - description='The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\nIf a seed is not specified, one will be generated for you.\n', - examples=[42], - ge=0, - le=2147483647, - ), - ] = None - method: Optional[FineTuneMethod] = None - metadata: Optional[Metadata] = None - - -class CreateResponse(CreateModelResponseProperties, ResponseProperties): - input: Optional[InputParam] = None - include: Optional[List[IncludeEnum]] = None - parallel_tool_calls: Optional[bool] = None - store: Optional[bool] = None - instructions: Optional[str] = None - stream: Optional[bool] = None - stream_options: Optional[ResponseStreamOptions] = None - conversation: Optional[ConversationParam] = None diff --git a/scripts/openai-spec.yaml b/scripts/openai-spec.yaml index 224dff30e..71a19b9da 100644 --- a/scripts/openai-spec.yaml +++ b/scripts/openai-spec.yaml @@ -1,9 +1,9 @@ -# https://github.com/openai/openai-openapi/blob/e1cb7a86ad53bb818c106ac7875e2a78182bb120/README.md -openapi: 3.1.0 +# https://github.com/openai/openai-openapi/blob/423e672461b3d17f9829711e4a858e777252f077/openapi.yaml +openapi: 3.0.0 info: title: OpenAI API description: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. - version: 2.3.0 + version: "2.3.0" termsOfService: https://openai.com/policies/terms-of-use contact: name: OpenAI Support @@ -13,8 +13,6 @@ info: url: https://github.com/openai/openai-openapi/blob/master/LICENSE servers: - url: https://api.openai.com/v1 -security: - - ApiKeyAuth: [] tags: - name: Assistants description: Build Assistants that can call models and use tools. @@ -22,22 +20,12 @@ tags: description: Turn audio into text or text into audio. - name: Chat description: Given a list of messages comprising a conversation, the model will return a response. - - name: Conversations - description: Manage conversations and conversation items. - name: Completions - description: >- - Given a prompt, the model will return one or more predicted completions, and can also return the - probabilities of alternative tokens at each position. + description: Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. - name: Embeddings - description: >- - Get a vector representation of a given input that can be easily consumed by machine learning models and - algorithms. - - name: Evals - description: Manage and run evals in the OpenAI platform. + description: Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. - name: Fine-tuning description: Manage fine-tuning jobs to tailor a model to your specific training data. - - name: Graders - description: Manage and run graders in the OpenAI platform. - name: Batch description: Create large batches of API requests to run asynchronously. - name: Files @@ -49,1688 +37,1197 @@ tags: - name: Models description: List and describe the various models available in the API. - name: Moderations - description: Given text and/or image inputs, classifies if those inputs are potentially harmful. + description: Given a input text, outputs if the model classifies it as potentially harmful. - name: Audit Logs description: List user actions and configuration changes within this organization. paths: - /assistants: - get: - operationId: listAssistants - tags: - - Assistants - summary: List assistants - parameters: - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListAssistantsResponse' - x-oaiMeta: - name: List assistants - group: assistants - beta: true - returns: A list of [assistant](https://platform.openai.com/docs/api-reference/assistants/object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "asst_abc123", - "object": "assistant", - "created_at": 1698982736, - "name": "Coding Tutor", - "description": null, - "model": "gpt-4o", - "instructions": "You are a helpful assistant designed to make me better at coding!", - "tools": [], - "tool_resources": {}, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - }, - { - "id": "asst_abc456", - "object": "assistant", - "created_at": 1698982718, - "name": "My Assistant", - "description": null, - "model": "gpt-4o", - "instructions": "You are a helpful assistant designed to make me better at coding!", - "tools": [], - "tool_resources": {}, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - }, - { - "id": "asst_abc789", - "object": "assistant", - "created_at": 1698982643, - "name": null, - "description": null, - "model": "gpt-4o", - "instructions": null, - "tools": [], - "tool_resources": {}, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - } - ], - "first_id": "asst_abc123", - "last_id": "asst_abc789", - "has_more": false - } - request: - curl: | - curl "https://api.openai.com/v1/assistants?order=desc&limit=20" \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.beta.assistants.list() - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const assistant of client.beta.assistants.list()) { - console.log(assistant.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Beta.Assistants.List(context.TODO(), openai.BetaAssistantListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.assistants.AssistantListPage; - import com.openai.models.beta.assistants.AssistantListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - AssistantListPage page = client.beta().assistants().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.beta.assistants.list - - puts(page) - description: Returns a list of assistants. + # Note: When adding an endpoint, make sure you also add it in the `groups` section, in the end of this file, + # under the appropriate group + /chat/completions: post: - operationId: createAssistant + operationId: createChatCompletion tags: - - Assistants - summary: Create assistant + - Chat + summary: Creates a model response for the given chat conversation. requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/CreateAssistantRequest' + $ref: "#/components/schemas/CreateChatCompletionRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/AssistantObject' + $ref: "#/components/schemas/CreateChatCompletionResponse" + x-oaiMeta: - name: Create assistant - group: assistants - beta: true - returns: An [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object. + name: Create chat completion + group: chat + returns: | + Returns a [chat completion](/docs/api-reference/chat/object) object, or a streamed sequence of [chat completion chunk](/docs/api-reference/chat/streaming) objects if the request is streamed. + path: create examples: - - title: Code Interpreter + - title: Default request: curl: | - curl "https://api.openai.com/v1/assistants" \ + curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ -d '{ - "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", - "name": "Math Tutor", - "tools": [{"type": "code_interpreter"}], - "model": "gpt-4o" + "model": "VAR_model_id", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Hello!" + } + ] }' - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - assistant = client.beta.assistants.create( - model="gpt-4o", - ) - print(assistant.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const assistant = await client.beta.assistants.create({ model: 'gpt-4o' }); - - console.log(assistant.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" + completion = client.chat.completions.create( + model="VAR_model_id", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ] ) - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{ - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", assistant.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.beta.assistants.Assistant; - import com.openai.models.beta.assistants.AssistantCreateParams; + print(completion.choices[0].message) + node.js: |- + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const completion = await openai.chat.completions.create({ + messages: [{ role: "system", content: "You are a helpful assistant." }], + model: "VAR_model_id", + }); - AssistantCreateParams params = AssistantCreateParams.builder() - .model(ChatModel.GPT_5_1) - .build(); - Assistant assistant = client.beta().assistants().create(params); - } + console.log(completion.choices[0]); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - assistant = openai.beta.assistants.create(model: :"gpt-5.1") - - puts(assistant) - response: | + main(); + response: &chat_completion_example | { - "id": "asst_abc123", - "object": "assistant", - "created_at": 1698984975, - "name": "Math Tutor", - "description": null, - "model": "gpt-4o", - "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", - "tools": [ - { - "type": "code_interpreter" - } - ], - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1677652288, + "model": "gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": "\n\nHello there, how may I assist you today?", + }, + "logprobs": null, + "finish_reason": "stop" + }], + "usage": { + "prompt_tokens": 9, + "completion_tokens": 12, + "total_tokens": 21 + } } - - title: Files + - title: Image input request: curl: | - curl https://api.openai.com/v1/assistants \ + curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ -d '{ - "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", - "tools": [{"type": "file_search"}], - "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}}, - "model": "gpt-4o" + "model": "gpt-4o", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "What'\''s in this image?" + }, + { + "type": "image_url", + "image_url": { + "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" + } + } + ] + } + ], + "max_tokens": 300 }' - python: |- + python: | from openai import OpenAI - client = OpenAI( - api_key="My API Key", - ) - assistant = client.beta.assistants.create( - model="gpt-4o", - ) - print(assistant.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const assistant = await client.beta.assistants.create({ model: 'gpt-4o' }); - - console.log(assistant.id); - go: | - package main + client = OpenAI() - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" + response = client.chat.completions.create( + model="gpt-4o", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "What's in this image?"}, + { + "type": "image_url", + "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + ], + } + ], + max_tokens=300, ) - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{ - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", assistant.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.beta.assistants.Assistant; - import com.openai.models.beta.assistants.AssistantCreateParams; + print(response.choices[0]) + node.js: |- + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - AssistantCreateParams params = AssistantCreateParams.builder() - .model(ChatModel.GPT_5_1) - .build(); - Assistant assistant = client.beta().assistants().create(params); - } + async function main() { + const response = await openai.chat.completions.create({ + model: "gpt-4o", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "What's in this image?" }, + { + type: "image_url", + image_url: + "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + ], + }, + ], + }); + console.log(response.choices[0]); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - assistant = openai.beta.assistants.create(model: :"gpt-5.1") - - puts(assistant) - response: | + main(); + response: &chat_completion_image_example | { - "id": "asst_abc123", - "object": "assistant", - "created_at": 1699009403, - "name": "HR Helper", - "description": null, - "model": "gpt-4o", - "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", - "tools": [ - { - "type": "file_search" - } - ], - "tool_resources": { - "file_search": { - "vector_store_ids": ["vs_123"] - } - }, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - } - description: Create an assistant with a model and instructions. - /assistants/{assistant_id}: - get: - operationId: getAssistant - tags: - - Assistants - summary: Retrieve assistant - parameters: - - in: path - name: assistant_id - required: true - schema: - type: string - description: The ID of the assistant to retrieve. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/AssistantObject' - x-oaiMeta: - name: Retrieve assistant - group: assistants - beta: true - returns: >- - The [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object matching - the specified ID. - examples: - response: | - { - "id": "asst_abc123", - "object": "assistant", - "created_at": 1699009709, - "name": "HR Helper", - "description": null, - "model": "gpt-4o", - "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", - "tools": [ - { - "type": "file_search" + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1677652288, + "model": "gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": "\n\nThis image shows a wooden boardwalk extending through a lush green marshland.", + }, + "logprobs": null, + "finish_reason": "stop" + }], + "usage": { + "prompt_tokens": 9, + "completion_tokens": 12, + "total_tokens": 21 } - ], - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - } - request: - curl: | - curl https://api.openai.com/v1/assistants/asst_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - assistant = client.beta.assistants.retrieve( - "assistant_id", - ) - print(assistant.id) - node.js: |- - import OpenAI from 'openai'; + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "VAR_model_id", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Hello!" + } + ], + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() - const client = new OpenAI({ - apiKey: 'My API Key', - }); + completion = client.chat.completions.create( + model="VAR_model_id", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ], + stream=True + ) - const assistant = await client.beta.assistants.retrieve('assistant_id'); + for chunk in completion: + print(chunk.choices[0].delta) - console.log(assistant.id); - go: | - package main + node.js: |- + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const completion = await openai.chat.completions.create({ + model: "VAR_model_id", + messages: [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ], + stream: true, + }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - assistant, err := client.Beta.Assistants.Get(context.TODO(), "assistant_id") - if err != nil { - panic(err.Error()) + for await (const chunk of completion) { + console.log(chunk.choices[0].delta.content); + } } - fmt.Printf("%+v\n", assistant.ID) - } - java: |- - package com.openai.example; - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.assistants.Assistant; - import com.openai.models.beta.assistants.AssistantRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Assistant assistant = client.beta().assistants().retrieve("assistant_id"); - } - } - ruby: |- - require "openai" + main(); + response: &chat_completion_chunk_example | + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} - openai = OpenAI::Client.new(api_key: "My API Key") + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} - assistant = openai.beta.assistants.retrieve("assistant_id") + .... - puts(assistant) - description: Retrieves an assistant. - post: - operationId: modifyAssistant - tags: - - Assistants - summary: Modify assistant - parameters: - - in: path - name: assistant_id - required: true - schema: - type: string - description: The ID of the assistant to modify. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ModifyAssistantRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/AssistantObject' - x-oaiMeta: - name: Modify assistant - group: assistants - beta: true - returns: The modified [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object. - examples: - response: | - { - "id": "asst_123", - "object": "assistant", - "created_at": 1699009709, - "name": "HR Helper", - "description": null, - "model": "gpt-4o", - "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", - "tools": [ - { - "type": "file_search" - } - ], - "tool_resources": { - "file_search": { - "vector_store_ids": [] - } - }, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - } - request: - curl: | - curl https://api.openai.com/v1/assistants/asst_abc123 \ + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + - title: Functions + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ -d '{ - "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", - "tools": [{"type": "file_search"}], - "model": "gpt-4o" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - assistant = client.beta.assistants.update( - assistant_id="assistant_id", - ) - print(assistant.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); + "model": "gpt-4o", + "messages": [ + { + "role": "user", + "content": "What'\''s the weather like in Boston today?" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "tool_choice": "auto" + }' + python: | + from openai import OpenAI + client = OpenAI() - const assistant = await client.beta.assistants.update('assistant_id'); + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ] + messages = [{"role": "user", "content": "What's the weather like in Boston today?"}] + completion = client.chat.completions.create( + model="VAR_model_id", + messages=messages, + tools=tools, + tool_choice="auto" + ) - console.log(assistant.id); - go: | - package main + print(completion) + node.js: |- + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]; + const tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ]; - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - assistant, err := client.Beta.Assistants.Update( - context.TODO(), - "assistant_id", - openai.BetaAssistantUpdateParams{ + const response = await openai.chat.completions.create({ + model: "gpt-4o", + messages: messages, + tools: tools, + tool_choice: "auto", + }); - }, - ) - if err != nil { - panic(err.Error()) + console.log(response); } - fmt.Printf("%+v\n", assistant.ID) - } - java: |- - package com.openai.example; - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.assistants.Assistant; - import com.openai.models.beta.assistants.AssistantUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Assistant assistant = client.beta().assistants().update("assistant_id"); + main(); + response: &chat_completion_function_example | + { + "id": "chatcmpl-abc123", + "object": "chat.completion", + "created": 1699896916, + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "call_abc123", + "type": "function", + "function": { + "name": "get_current_weather", + "arguments": "{\n\"location\": \"Boston, MA\"\n}" + } + } + ] + }, + "logprobs": null, + "finish_reason": "tool_calls" } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - assistant = openai.beta.assistants.update("assistant_id") - - puts(assistant) - description: Modifies an assistant. - delete: - operationId: deleteAssistant - tags: - - Assistants - summary: Delete assistant - parameters: - - in: path - name: assistant_id - required: true - schema: - type: string - description: The ID of the assistant to delete. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/DeleteAssistantResponse' - x-oaiMeta: - name: Delete assistant - group: assistants - beta: true - returns: Deletion status - examples: - response: | - { - "id": "asst_abc123", - "object": "assistant.deleted", - "deleted": true - } - request: - curl: | - curl https://api.openai.com/v1/assistants/asst_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -X DELETE - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - assistant_deleted = client.beta.assistants.delete( - "assistant_id", - ) - print(assistant_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const assistantDeleted = await client.beta.assistants.delete('assistant_id'); - - console.log(assistantDeleted.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - assistantDeleted, err := client.Beta.Assistants.Delete(context.TODO(), "assistant_id") - if err != nil { - panic(err.Error()) + ], + "usage": { + "prompt_tokens": 82, + "completion_tokens": 17, + "total_tokens": 99 } - fmt.Printf("%+v\n", assistantDeleted.ID) } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.assistants.AssistantDeleteParams; - import com.openai.models.beta.assistants.AssistantDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - AssistantDeleted assistantDeleted = client.beta().assistants().delete("assistant_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - assistant_deleted = openai.beta.assistants.delete("assistant_id") - - puts(assistant_deleted) - description: Delete an assistant. - /audio/speech: - post: - operationId: createSpeech - tags: - - Audio - summary: Create speech - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateSpeechRequest' - responses: - '200': - description: OK - headers: - Transfer-Encoding: - schema: - type: string - description: chunked - content: - application/octet-stream: - schema: - type: string - format: binary - text/event-stream: - schema: - $ref: '#/components/schemas/CreateSpeechResponseStreamEvent' - x-oaiMeta: - name: Create speech - group: audio - returns: >- - The audio file content or a [stream of audio - events](https://platform.openai.com/docs/api-reference/audio/speech-audio-delta-event). - examples: - - title: Default + - title: Logprobs request: curl: | - curl https://api.openai.com/v1/audio/speech \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ + curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ - "model": "gpt-4o-mini-tts", - "input": "The quick brown fox jumped over the lazy dog.", - "voice": "alloy" - }' \ - --output speech.mp3 - python: |- + "model": "VAR_model_id", + "messages": [ + { + "role": "user", + "content": "Hello!" + } + ], + "logprobs": true, + "top_logprobs": 2 + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - speech = client.audio.speech.create( - input="input", - model="string", - voice="ash", + completion = client.chat.completions.create( + model="VAR_model_id", + messages=[ + {"role": "user", "content": "Hello!"} + ], + logprobs=True, + top_logprobs=2 ) - print(speech) - content = speech.read() - print(content) - javascript: | - import fs from "fs"; - import path from "path"; + + print(completion.choices[0].message) + print(completion.choices[0].logprobs) + node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); - const speechFile = path.resolve("./speech.mp3"); - async function main() { - const mp3 = await openai.audio.speech.create({ - model: "gpt-4o-mini-tts", - voice: "alloy", - input: "Today is a wonderful day to build something people love!", + const completion = await openai.chat.completions.create({ + messages: [{ role: "user", content: "Hello!" }], + model: "VAR_model_id", + logprobs: true, + top_logprobs: 2, }); - console.log(speechFile); - const buffer = Buffer.from(await mp3.arrayBuffer()); - await fs.promises.writeFile(speechFile, buffer); - } - main(); - csharp: | - using System; - using System.IO; - - using OpenAI.Audio; - - AudioClient client = new( - model: "gpt-4o-mini-tts", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - BinaryData speech = client.GenerateSpeech( - text: "The quick brown fox jumped over the lazy dog.", - voice: GeneratedSpeechVoice.Alloy - ); - - using FileStream stream = File.OpenWrite("speech.mp3"); - speech.ToStream().CopyTo(stream); - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: - 'ash' }); - - - console.log(speech); - - - const content = await speech.blob(); - - console.log(content); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{ - Input: "input", - Model: openai.SpeechModelTTS1, - Voice: openai.AudioSpeechNewParamsVoiceAlloy, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", speech) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.http.HttpResponse; - import com.openai.models.audio.speech.SpeechCreateParams; - import com.openai.models.audio.speech.SpeechModel; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - SpeechCreateParams params = SpeechCreateParams.builder() - .input("input") - .model(SpeechModel.TTS_1) - .voice(SpeechCreateParams.Voice.ALLOY) - .build(); - HttpResponse speech = client.audio().speech().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - speech = openai.audio.speech.create(input: "input", model: :"tts-1", voice: :alloy) - - puts(speech) - - title: SSE Stream Format - request: - curl: | - curl https://api.openai.com/v1/audio/speech \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "model": "gpt-4o-mini-tts", - "input": "The quick brown fox jumped over the lazy dog.", - "voice": "alloy", - "stream_format": "sse" - }' - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: - 'ash' }); - - console.log(speech); - - - const content = await speech.blob(); - - console.log(content); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - speech = client.audio.speech.create( - input="input", - model="string", - voice="ash", - ) - print(speech) - content = speech.read() - print(content) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{ - Input: "input", - Model: openai.SpeechModelTTS1, - Voice: openai.AudioSpeechNewParamsVoiceAlloy, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", speech) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.http.HttpResponse; - import com.openai.models.audio.speech.SpeechCreateParams; - import com.openai.models.audio.speech.SpeechModel; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - SpeechCreateParams params = SpeechCreateParams.builder() - .input("input") - .model(SpeechModel.TTS_1) - .voice(SpeechCreateParams.Voice.ALLOY) - .build(); - HttpResponse speech = client.audio().speech().create(params); - } + console.log(completion.choices[0]); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - speech = openai.audio.speech.create(input: "input", model: :"tts-1", voice: :alloy) - - puts(speech) - description: Generates audio from the input text. - /audio/transcriptions: - post: - operationId: createTranscription - tags: - - Audio - summary: Create transcription - requestBody: - required: true - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/CreateTranscriptionRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - anyOf: - - $ref: '#/components/schemas/CreateTranscriptionResponseJson' - - $ref: '#/components/schemas/CreateTranscriptionResponseDiarizedJson' - x-stainless-skip: - - go - - $ref: '#/components/schemas/CreateTranscriptionResponseVerboseJson' - discriminator: - propertyName: task - text/event-stream: - schema: - $ref: '#/components/schemas/CreateTranscriptionResponseStreamEvent' - x-oaiMeta: - name: Create transcription - group: audio - returns: >- - The [transcription object](https://platform.openai.com/docs/api-reference/audio/json-object), a - [diarized transcription - object](https://platform.openai.com/docs/api-reference/audio/diarized-json-object), a [verbose - transcription object](https://platform.openai.com/docs/api-reference/audio/verbose-json-object), or - a [stream of transcript - events](https://platform.openai.com/docs/api-reference/audio/transcript-text-delta-event). - examples: - - title: Default - request: - curl: | - curl https://api.openai.com/v1/audio/transcriptions \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: multipart/form-data" \ - -F file="@/path/to/file/audio.mp3" \ - -F model="gpt-4o-transcribe" - python: |- - from openai import OpenAI - client = OpenAI( - api_key="My API Key", - ) - transcription = client.audio.transcriptions.create( - file=b"raw file contents", - model="gpt-4o-transcribe", - ) - print(transcription) - javascript: | - import fs from "fs"; - import OpenAI from "openai"; - - const openai = new OpenAI(); - - async function main() { - const transcription = await openai.audio.transcriptions.create({ - file: fs.createReadStream("audio.mp3"), - model: "gpt-4o-transcribe", - }); - - console.log(transcription.text); - } main(); - csharp: | - using System; - - using OpenAI.Audio; - string audioFilePath = "audio.mp3"; - - AudioClient client = new( - model: "gpt-4o-transcribe", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - AudioTranscription transcription = client.TranscribeAudio(audioFilePath); - - Console.WriteLine($"{transcription.Text}"); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const transcription = await client.audio.transcriptions.create({ - file: fs.createReadStream('speech.mp3'), - model: 'gpt-4o-transcribe', - }); - - console.log(transcription); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", transcription) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.transcriptions.TranscriptionCreateParams; - import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranscriptionCreateParams params = TranscriptionCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: - :"whisper-1") - - - puts(transcription) response: | { - "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.", + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1702685778, + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Hello! How can I assist you today?" + }, + "logprobs": { + "content": [ + { + "token": "Hello", + "logprob": -0.31725305, + "bytes": [72, 101, 108, 108, 111], + "top_logprobs": [ + { + "token": "Hello", + "logprob": -0.31725305, + "bytes": [72, 101, 108, 108, 111] + }, + { + "token": "Hi", + "logprob": -1.3190403, + "bytes": [72, 105] + } + ] + }, + { + "token": "!", + "logprob": -0.02380986, + "bytes": [ + 33 + ], + "top_logprobs": [ + { + "token": "!", + "logprob": -0.02380986, + "bytes": [33] + }, + { + "token": " there", + "logprob": -3.787621, + "bytes": [32, 116, 104, 101, 114, 101] + } + ] + }, + { + "token": " How", + "logprob": -0.000054669687, + "bytes": [32, 72, 111, 119], + "top_logprobs": [ + { + "token": " How", + "logprob": -0.000054669687, + "bytes": [32, 72, 111, 119] + }, + { + "token": "<|end|>", + "logprob": -10.953937, + "bytes": null + } + ] + }, + { + "token": " can", + "logprob": -0.015801601, + "bytes": [32, 99, 97, 110], + "top_logprobs": [ + { + "token": " can", + "logprob": -0.015801601, + "bytes": [32, 99, 97, 110] + }, + { + "token": " may", + "logprob": -4.161023, + "bytes": [32, 109, 97, 121] + } + ] + }, + { + "token": " I", + "logprob": -3.7697225e-6, + "bytes": [ + 32, + 73 + ], + "top_logprobs": [ + { + "token": " I", + "logprob": -3.7697225e-6, + "bytes": [32, 73] + }, + { + "token": " assist", + "logprob": -13.596657, + "bytes": [32, 97, 115, 115, 105, 115, 116] + } + ] + }, + { + "token": " assist", + "logprob": -0.04571125, + "bytes": [32, 97, 115, 115, 105, 115, 116], + "top_logprobs": [ + { + "token": " assist", + "logprob": -0.04571125, + "bytes": [32, 97, 115, 115, 105, 115, 116] + }, + { + "token": " help", + "logprob": -3.1089056, + "bytes": [32, 104, 101, 108, 112] + } + ] + }, + { + "token": " you", + "logprob": -5.4385737e-6, + "bytes": [32, 121, 111, 117], + "top_logprobs": [ + { + "token": " you", + "logprob": -5.4385737e-6, + "bytes": [32, 121, 111, 117] + }, + { + "token": " today", + "logprob": -12.807695, + "bytes": [32, 116, 111, 100, 97, 121] + } + ] + }, + { + "token": " today", + "logprob": -0.0040071653, + "bytes": [32, 116, 111, 100, 97, 121], + "top_logprobs": [ + { + "token": " today", + "logprob": -0.0040071653, + "bytes": [32, 116, 111, 100, 97, 121] + }, + { + "token": "?", + "logprob": -5.5247097, + "bytes": [63] + } + ] + }, + { + "token": "?", + "logprob": -0.0008108172, + "bytes": [63], + "top_logprobs": [ + { + "token": "?", + "logprob": -0.0008108172, + "bytes": [63] + }, + { + "token": "?\n", + "logprob": -7.184561, + "bytes": [63, 10] + } + ] + } + ] + }, + "finish_reason": "stop" + } + ], "usage": { - "type": "tokens", - "input_tokens": 14, - "input_token_details": { - "text_tokens": 0, - "audio_tokens": 14 - }, - "output_tokens": 45, - "total_tokens": 59 - } + "prompt_tokens": 9, + "completion_tokens": 9, + "total_tokens": 18 + }, + "system_fingerprint": null } - - title: Diarization + + /completions: + post: + operationId: createCompletion + tags: + - Completions + summary: Creates a completion for the provided prompt and parameters. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateCompletionRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/CreateCompletionResponse" + x-oaiMeta: + name: Create completion + group: completions + returns: | + Returns a [completion](/docs/api-reference/completions/object) object, or a sequence of completion objects if the request is streamed. + legacy: true + examples: + - title: No streaming request: curl: | - curl https://api.openai.com/v1/audio/transcriptions \ + curl https://api.openai.com/v1/completions \ + -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: multipart/form-data" \ - -F file="@/path/to/file/meeting.wav" \ - -F model="gpt-4o-transcribe-diarize" \ - -F response_format="diarized_json" \ - -F chunking_strategy=auto \ - -F 'known_speaker_names[]=agent' \ - -F 'known_speaker_references[]=data:audio/wav;base64,AAA...' - python: |- + -d '{ + "model": "VAR_model_id", + "prompt": "Say this is a test", + "max_tokens": 7, + "temperature": 0 + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - transcription = client.audio.transcriptions.create( - file=b"raw file contents", - model="gpt-4o-transcribe", + client.completions.create( + model="VAR_model_id", + prompt="Say this is a test", + max_tokens=7, + temperature=0 ) - print(transcription) - javascript: | - import fs from "fs"; + node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); - const speakerRef = fs.readFileSync("agent.wav").toString("base64"); + async function main() { + const completion = await openai.completions.create({ + model: "VAR_model_id", + prompt: "Say this is a test.", + max_tokens: 7, + temperature: 0, + }); - const transcript = await openai.audio.transcriptions.create({ - file: fs.createReadStream("meeting.wav"), - model: "gpt-4o-transcribe-diarize", - response_format: "diarized_json", - chunking_strategy: "auto", - extra_body: { - known_speaker_names: ["agent"], - known_speaker_references: [`data:audio/wav;base64,${speakerRef}`], - }, - }); - - console.log(transcript.segments); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const transcription = await client.audio.transcriptions.create({ - file: fs.createReadStream('speech.mp3'), - model: 'gpt-4o-transcribe', - }); - - console.log(transcription); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", transcription) + console.log(completion); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.transcriptions.TranscriptionCreateParams; - import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranscriptionCreateParams params = TranscriptionCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: - :"whisper-1") - - - puts(transcription) + main(); response: | { - "task": "transcribe", - "duration": 27.4, - "text": "Agent: Thanks for calling OpenAI support.\nA: Hi, I'm trying to enable diarization.\nAgent: Happy to walk you through the steps.", - "segments": [ - { - "type": "transcript.text.segment", - "id": "seg_001", - "start": 0.0, - "end": 4.7, - "text": "Thanks for calling OpenAI support.", - "speaker": "agent" - }, - { - "type": "transcript.text.segment", - "id": "seg_002", - "start": 4.7, - "end": 11.8, - "text": "Hi, I'm trying to enable diarization.", - "speaker": "A" - }, + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "VAR_model_id", + "system_fingerprint": "fp_44709d6fcb", + "choices": [ { - "type": "transcript.text.segment", - "id": "seg_003", - "start": 12.1, - "end": 18.5, - "text": "Happy to walk you through the steps.", - "speaker": "agent" + "text": "\n\nThis is indeed a test", + "index": 0, + "logprobs": null, + "finish_reason": "length" } ], "usage": { - "type": "duration", - "seconds": 27 + "prompt_tokens": 5, + "completion_tokens": 7, + "total_tokens": 12 } } - title: Streaming request: curl: | - curl https://api.openai.com/v1/audio/transcriptions \ + curl https://api.openai.com/v1/completions \ + -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: multipart/form-data" \ - -F file="@/path/to/file/audio.mp3" \ - -F model="gpt-4o-mini-transcribe" \ - -F stream=true - python: |- + -d '{ + "model": "VAR_model_id", + "prompt": "Say this is a test", + "max_tokens": 7, + "temperature": 0, + "stream": true + }' + python: | from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - transcription = client.audio.transcriptions.create( - file=b"raw file contents", - model="gpt-4o-transcribe", - ) - print(transcription) - javascript: | - import fs from "fs"; + client = OpenAI() + + for chunk in client.completions.create( + model="VAR_model_id", + prompt="Say this is a test", + max_tokens=7, + temperature=0, + stream=True + ): + print(chunk.choices[0].text) + node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); - const stream = await openai.audio.transcriptions.create({ - file: fs.createReadStream("audio.mp3"), - model: "gpt-4o-mini-transcribe", - stream: true, - }); - - for await (const event of stream) { - console.log(event); - } - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const transcription = await client.audio.transcriptions.create({ - file: fs.createReadStream('speech.mp3'), - model: 'gpt-4o-transcribe', - }); - - console.log(transcription); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const stream = await openai.completions.create({ + model: "VAR_model_id", + prompt: "Say this is a test.", + stream: true, + }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) + for await (const chunk of stream) { + console.log(chunk.choices[0].text) } - fmt.Printf("%+v\n", transcription) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.transcriptions.TranscriptionCreateParams; - import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranscriptionCreateParams params = TranscriptionCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); - } } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: - :"whisper-1") - - - puts(transcription) - response: > - data: - {"type":"transcript.text.delta","delta":"I","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]}]} - - - data: {"type":"transcript.text.delta","delta":" see","logprobs":[{"token":" - see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]}]} - - - data: {"type":"transcript.text.delta","delta":" skies","logprobs":[{"token":" - skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]}]} - - - data: {"type":"transcript.text.delta","delta":" of","logprobs":[{"token":" - of","logprob":-3.1281633e-7,"bytes":[32,111,102]}]} - - - data: {"type":"transcript.text.delta","delta":" blue","logprobs":[{"token":" - blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]}]} - - - data: {"type":"transcript.text.delta","delta":" and","logprobs":[{"token":" - and","logprob":-0.0005108566,"bytes":[32,97,110,100]}]} - - - data: {"type":"transcript.text.delta","delta":" clouds","logprobs":[{"token":" - clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]}]} - - - data: {"type":"transcript.text.delta","delta":" of","logprobs":[{"token":" - of","logprob":-1.9361265e-7,"bytes":[32,111,102]}]} + main(); + response: | + { + "id": "cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe", + "object": "text_completion", + "created": 1690759702, + "choices": [ + { + "text": "This", + "index": 0, + "logprobs": null, + "finish_reason": null + } + ], + "model": "gpt-3.5-turbo-instruct" + "system_fingerprint": "fp_44709d6fcb", + } + /images/generations: + post: + operationId: createImage + tags: + - Images + summary: Creates an image given a prompt. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateImageRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ImagesResponse" + x-oaiMeta: + name: Create image + group: images + returns: Returns a list of [image](/docs/api-reference/images/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/images/generations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "dall-e-3", + "prompt": "A cute baby sea otter", + "n": 1, + "size": "1024x1024" + }' + python: | + from openai import OpenAI + client = OpenAI() - data: {"type":"transcript.text.delta","delta":" white","logprobs":[{"token":" - white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]}]} + client.images.generate( + model="dall-e-3", + prompt="A cute baby sea otter", + n=1, + size="1024x1024" + ) + node.js: |- + import OpenAI from "openai"; + const openai = new OpenAI(); - data: - {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0014890312,"bytes":[44]}]} + async function main() { + const image = await openai.images.generate({ model: "dall-e-3", prompt: "A cute baby sea otter" }); + console.log(image.data); + } + main(); + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } + /images/edits: + post: + operationId: createImageEdit + tags: + - Images + summary: Creates an edited or extended image given an original image and a prompt. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateImageEditRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ImagesResponse" + x-oaiMeta: + name: Create image edit + group: images + returns: Returns a list of [image](/docs/api-reference/images/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/images/edits \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F image="@otter.png" \ + -F mask="@mask.png" \ + -F prompt="A cute baby sea otter wearing a beret" \ + -F n=2 \ + -F size="1024x1024" + python: | + from openai import OpenAI + client = OpenAI() - data: {"type":"transcript.text.delta","delta":" the","logprobs":[{"token":" - the","logprob":-0.0110956915,"bytes":[32,116,104,101]}]} + client.images.edit( + image=open("otter.png", "rb"), + mask=open("mask.png", "rb"), + prompt="A cute baby sea otter wearing a beret", + n=2, + size="1024x1024" + ) + node.js: |- + import fs from "fs"; + import OpenAI from "openai"; + const openai = new OpenAI(); - data: {"type":"transcript.text.delta","delta":" bright","logprobs":[{"token":" - bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]}]} + async function main() { + const image = await openai.images.edit({ + image: fs.createReadStream("otter.png"), + mask: fs.createReadStream("mask.png"), + prompt: "A cute baby sea otter wearing a beret", + }); + console.log(image.data); + } + main(); + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } + /images/variations: + post: + operationId: createImageVariation + tags: + - Images + summary: Creates a variation of a given image. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateImageVariationRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ImagesResponse" + x-oaiMeta: + name: Create image variation + group: images + returns: Returns a list of [image](/docs/api-reference/images/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/images/variations \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F image="@otter.png" \ + -F n=2 \ + -F size="1024x1024" + python: | + from openai import OpenAI + client = OpenAI() - data: {"type":"transcript.text.delta","delta":" blessed","logprobs":[{"token":" - blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]}]} + response = client.images.create_variation( + image=open("image_edit_original.png", "rb"), + n=2, + size="1024x1024" + ) + node.js: |- + import fs from "fs"; + import OpenAI from "openai"; + const openai = new OpenAI(); - data: {"type":"transcript.text.delta","delta":" days","logprobs":[{"token":" - days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]}]} + async function main() { + const image = await openai.images.createVariation({ + image: fs.createReadStream("otter.png"), + }); + console.log(image.data); + } + main(); + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } - data: - {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.00001700133,"bytes":[44]}]} - - - data: {"type":"transcript.text.delta","delta":" the","logprobs":[{"token":" - the","logprob":-0.0000118755715,"bytes":[32,116,104,101]}]} - - - data: {"type":"transcript.text.delta","delta":" dark","logprobs":[{"token":" - dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]}]} - - - data: {"type":"transcript.text.delta","delta":" sacred","logprobs":[{"token":" - sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]}]} - - - data: {"type":"transcript.text.delta","delta":" nights","logprobs":[{"token":" - nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]}]} - - - data: - {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0036910512,"bytes":[44]}]} - - - data: {"type":"transcript.text.delta","delta":" and","logprobs":[{"token":" - and","logprob":-0.0031903093,"bytes":[32,97,110,100]}]} - - - data: {"type":"transcript.text.delta","delta":" I","logprobs":[{"token":" - I","logprob":-1.504853e-6,"bytes":[32,73]}]} - - - data: {"type":"transcript.text.delta","delta":" think","logprobs":[{"token":" - think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]}]} - - - data: {"type":"transcript.text.delta","delta":" to","logprobs":[{"token":" - to","logprob":-1.9361265e-7,"bytes":[32,116,111]}]} - - - data: {"type":"transcript.text.delta","delta":" myself","logprobs":[{"token":" - myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]}]} - - - data: - {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.29254505,"bytes":[44]}]} - - - data: {"type":"transcript.text.delta","delta":" what","logprobs":[{"token":" - what","logprob":-0.016815351,"bytes":[32,119,104,97,116]}]} + /embeddings: + post: + operationId: createEmbedding + tags: + - Embeddings + summary: Creates an embedding vector representing the input text. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateEmbeddingRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/CreateEmbeddingResponse" + x-oaiMeta: + name: Create embeddings + group: embeddings + returns: A list of [embedding](/docs/api-reference/embeddings/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/embeddings \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "input": "The food was delicious and the waiter...", + "model": "text-embedding-ada-002", + "encoding_format": "float" + }' + python: | + from openai import OpenAI + client = OpenAI() + client.embeddings.create( + model="text-embedding-ada-002", + input="The food was delicious and the waiter...", + encoding_format="float" + ) + node.js: |- + import OpenAI from "openai"; - data: {"type":"transcript.text.delta","delta":" a","logprobs":[{"token":" - a","logprob":-3.1281633e-7,"bytes":[32,97]}]} + const openai = new OpenAI(); + async function main() { + const embedding = await openai.embeddings.create({ + model: "text-embedding-ada-002", + input: "The quick brown fox jumped over the lazy dog", + encoding_format: "float", + }); - data: {"type":"transcript.text.delta","delta":" wonderful","logprobs":[{"token":" - wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]}]} + console.log(embedding); + } + main(); + response: | + { + "object": "list", + "data": [ + { + "object": "embedding", + "embedding": [ + 0.0023064255, + -0.009327292, + .... (1536 floats total for ada-002) + -0.0028842222, + ], + "index": 0 + } + ], + "model": "text-embedding-ada-002", + "usage": { + "prompt_tokens": 8, + "total_tokens": 8 + } + } - data: {"type":"transcript.text.delta","delta":" world","logprobs":[{"token":" - world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]}]} + /audio/speech: + post: + operationId: createSpeech + tags: + - Audio + summary: Generates audio from the input text. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateSpeechRequest" + responses: + "200": + description: OK + headers: + Transfer-Encoding: + schema: + type: string + description: chunked + content: + application/octet-stream: + schema: + type: string + format: binary + x-oaiMeta: + name: Create speech + group: audio + returns: The audio file content. + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/speech \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "tts-1", + "input": "The quick brown fox jumped over the lazy dog.", + "voice": "alloy" + }' \ + --output speech.mp3 + python: | + from pathlib import Path + import openai + speech_file_path = Path(__file__).parent / "speech.mp3" + response = openai.audio.speech.create( + model="tts-1", + voice="alloy", + input="The quick brown fox jumped over the lazy dog." + ) + response.stream_to_file(speech_file_path) + node: | + import fs from "fs"; + import path from "path"; + import OpenAI from "openai"; - data: - {"type":"transcript.text.delta","delta":".","logprobs":[{"token":".","logprob":-0.014231676,"bytes":[46]}]} + const openai = new OpenAI(); + const speechFile = path.resolve("./speech.mp3"); - data: {"type":"transcript.text.done","text":"I see skies of blue and clouds of white, the bright - blessed days, the dark sacred nights, and I think to myself, what a wonderful - world.","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]},{"token":" - see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]},{"token":" - skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]},{"token":" - of","logprob":-3.1281633e-7,"bytes":[32,111,102]},{"token":" - blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]},{"token":" - and","logprob":-0.0005108566,"bytes":[32,97,110,100]},{"token":" - clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]},{"token":" - of","logprob":-1.9361265e-7,"bytes":[32,111,102]},{"token":" - white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]},{"token":",","logprob":-0.0014890312,"bytes":[44]},{"token":" - the","logprob":-0.0110956915,"bytes":[32,116,104,101]},{"token":" - bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]},{"token":" - blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]},{"token":" - days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]},{"token":",","logprob":-0.00001700133,"bytes":[44]},{"token":" - the","logprob":-0.0000118755715,"bytes":[32,116,104,101]},{"token":" - dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]},{"token":" - sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]},{"token":" - nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]},{"token":",","logprob":-0.0036910512,"bytes":[44]},{"token":" - and","logprob":-0.0031903093,"bytes":[32,97,110,100]},{"token":" - I","logprob":-1.504853e-6,"bytes":[32,73]},{"token":" - think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]},{"token":" - to","logprob":-1.9361265e-7,"bytes":[32,116,111]},{"token":" - myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]},{"token":",","logprob":-0.29254505,"bytes":[44]},{"token":" - what","logprob":-0.016815351,"bytes":[32,119,104,97,116]},{"token":" - a","logprob":-3.1281633e-7,"bytes":[32,97]},{"token":" - wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]},{"token":" - world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]},{"token":".","logprob":-0.014231676,"bytes":[46]}],"usage":{"input_tokens":14,"input_token_details":{"text_tokens":0,"audio_tokens":14},"output_tokens":45,"total_tokens":59}} - - title: Logprobs + async function main() { + const mp3 = await openai.audio.speech.create({ + model: "tts-1", + voice: "alloy", + input: "Today is a wonderful day to build something people love!", + }); + console.log(speechFile); + const buffer = Buffer.from(await mp3.arrayBuffer()); + await fs.promises.writeFile(speechFile, buffer); + } + main(); + /audio/transcriptions: + post: + operationId: createTranscription + tags: + - Audio + summary: Transcribes audio into the input language. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateTranscriptionRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/CreateTranscriptionResponseJson" + - $ref: "#/components/schemas/CreateTranscriptionResponseVerboseJson" + x-oaiMeta: + name: Create transcription + group: audio + returns: The [transcription object](/docs/api-reference/audio/json-object) or a [verbose transcription object](/docs/api-reference/audio/verbose-json-object). + examples: + - title: Default request: curl: | curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/audio.mp3" \ - -F "include[]=logprobs" \ - -F model="gpt-4o-transcribe" \ - -F response_format="json" - python: |- + -F model="whisper-1" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - transcription = client.audio.transcriptions.create( - file=b"raw file contents", - model="gpt-4o-transcribe", + audio_file = open("speech.mp3", "rb") + transcript = client.audio.transcriptions.create( + model="whisper-1", + file=audio_file ) - print(transcription) - javascript: | + node: | import fs from "fs"; import OpenAI from "openai"; @@ -1739,143 +1236,15 @@ paths: async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), - model: "gpt-4o-transcribe", - response_format: "json", - include: ["logprobs"] + model: "whisper-1", }); - console.log(transcription); + console.log(transcription.text); } main(); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const transcription = await client.audio.transcriptions.create({ - file: fs.createReadStream('speech.mp3'), - model: 'gpt-4o-transcribe', - }); - - console.log(transcription); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", transcription) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.transcriptions.TranscriptionCreateParams; - import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranscriptionCreateParams params = TranscriptionCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: - :"whisper-1") - - - puts(transcription) - response: | + response: &basic_transcription_response_example | { - "text": "Hey, my knee is hurting and I want to see the doctor tomorrow ideally.", - "logprobs": [ - { "token": "Hey", "logprob": -1.0415299, "bytes": [72, 101, 121] }, - { "token": ",", "logprob": -9.805982e-5, "bytes": [44] }, - { "token": " my", "logprob": -0.00229799, "bytes": [32, 109, 121] }, - { - "token": " knee", - "logprob": -4.7159858e-5, - "bytes": [32, 107, 110, 101, 101] - }, - { "token": " is", "logprob": -0.043909557, "bytes": [32, 105, 115] }, - { - "token": " hurting", - "logprob": -1.1041146e-5, - "bytes": [32, 104, 117, 114, 116, 105, 110, 103] - }, - { "token": " and", "logprob": -0.011076359, "bytes": [32, 97, 110, 100] }, - { "token": " I", "logprob": -5.3193703e-6, "bytes": [32, 73] }, - { - "token": " want", - "logprob": -0.0017156356, - "bytes": [32, 119, 97, 110, 116] - }, - { "token": " to", "logprob": -7.89631e-7, "bytes": [32, 116, 111] }, - { "token": " see", "logprob": -5.5122365e-7, "bytes": [32, 115, 101, 101] }, - { "token": " the", "logprob": -0.0040786397, "bytes": [32, 116, 104, 101] }, - { - "token": " doctor", - "logprob": -2.3392786e-6, - "bytes": [32, 100, 111, 99, 116, 111, 114] - }, - { - "token": " tomorrow", - "logprob": -7.89631e-7, - "bytes": [32, 116, 111, 109, 111, 114, 114, 111, 119] - }, - { - "token": " ideally", - "logprob": -0.5800861, - "bytes": [32, 105, 100, 101, 97, 108, 108, 121] - }, - { "token": ".", "logprob": -0.00011093382, "bytes": [46] } - ], - "usage": { - "type": "tokens", - "input_tokens": 14, - "input_token_details": { - "text_tokens": 0, - "audio_tokens": 14 - }, - "output_tokens": 45, - "total_tokens": 59 - } + "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that." } - title: Word timestamps request: @@ -1887,18 +1256,20 @@ paths: -F "timestamp_granularities[]=word" \ -F model="whisper-1" \ -F response_format="verbose_json" - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - transcription = client.audio.transcriptions.create( - file=b"raw file contents", - model="gpt-4o-transcribe", + audio_file = open("speech.mp3", "rb") + transcript = client.audio.transcriptions.create( + file=audio_file, + model="whisper-1", + response_format="verbose_json", + timestamp_granularities=["word"] ) - print(transcription) - javascript: | + + print(transcript.words) + node: | import fs from "fs"; import OpenAI from "openai"; @@ -1915,101 +1286,6 @@ paths: console.log(transcription.text); } main(); - csharp: | - using System; - - using OpenAI.Audio; - - string audioFilePath = "audio.mp3"; - - AudioClient client = new( - model: "whisper-1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - AudioTranscriptionOptions options = new() - { - ResponseFormat = AudioTranscriptionFormat.Verbose, - TimestampGranularities = AudioTimestampGranularities.Word, - }; - - AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); - - Console.WriteLine($"{transcription.Text}"); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const transcription = await client.audio.transcriptions.create({ - file: fs.createReadStream('speech.mp3'), - model: 'gpt-4o-transcribe', - }); - - console.log(transcription); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", transcription) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.transcriptions.TranscriptionCreateParams; - import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranscriptionCreateParams params = TranscriptionCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: - :"whisper-1") - - - puts(transcription) response: | { "task": "transcribe", @@ -2028,11 +1304,7 @@ paths: "start": 7.400000095367432, "end": 7.900000095367432 } - ], - "usage": { - "type": "duration", - "seconds": 9 - } + ] } - title: Segment timestamps request: @@ -2044,18 +1316,20 @@ paths: -F "timestamp_granularities[]=segment" \ -F model="whisper-1" \ -F response_format="verbose_json" - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - transcription = client.audio.transcriptions.create( - file=b"raw file contents", - model="gpt-4o-transcribe", + audio_file = open("speech.mp3", "rb") + transcript = client.audio.transcriptions.create( + file=audio_file, + model="whisper-1", + response_format="verbose_json", + timestamp_granularities=["segment"] ) - print(transcription) - javascript: | + + print(transcript.words) + node: | import fs from "fs"; import OpenAI from "openai"; @@ -2072,102 +1346,7 @@ paths: console.log(transcription.text); } main(); - csharp: | - using System; - - using OpenAI.Audio; - - string audioFilePath = "audio.mp3"; - - AudioClient client = new( - model: "whisper-1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - AudioTranscriptionOptions options = new() - { - ResponseFormat = AudioTranscriptionFormat.Verbose, - TimestampGranularities = AudioTimestampGranularities.Segment, - }; - - AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); - - Console.WriteLine($"{transcription.Text}"); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const transcription = await client.audio.transcriptions.create({ - file: fs.createReadStream('speech.mp3'), - model: 'gpt-4o-transcribe', - }); - - console.log(transcription); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", transcription) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.transcriptions.TranscriptionCreateParams; - import com.openai.models.audio.transcriptions.TranscriptionCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranscriptionCreateParams params = TranscriptionCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: - :"whisper-1") - - - puts(transcription) - response: | + response: &verbose_transcription_response_example | { "task": "transcribe", "language": "english", @@ -2189,45 +1368,34 @@ paths: "no_speech_prob": 0.00985979475080967 }, ... - ], - "usage": { - "type": "duration", - "seconds": 9 - } + ] } - description: Transcribes audio into the input language. /audio/translations: post: operationId: createTranslation tags: - Audio - summary: Create translation + summary: Translates audio into English. requestBody: required: true content: multipart/form-data: schema: - $ref: '#/components/schemas/CreateTranslationRequest' + $ref: "#/components/schemas/CreateTranslationRequest" responses: - '200': + "200": description: OK content: application/json: schema: - anyOf: - - $ref: '#/components/schemas/CreateTranslationResponseJson' - - $ref: '#/components/schemas/CreateTranslationResponseVerboseJson' - x-stainless-skip: - - go + oneOf: + - $ref: "#/components/schemas/CreateTranslationResponseJson" + - $ref: "#/components/schemas/CreateTranslationResponseVerboseJson" x-oaiMeta: name: Create translation group: audio returns: The translated text. examples: - response: | - { - "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?" - } request: curl: | curl https://api.openai.com/v1/audio/translations \ @@ -2235,18 +1403,16 @@ paths: -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/german.m4a" \ -F model="whisper-1" - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", + audio_file = open("speech.mp3", "rb") + transcript = client.audio.translations.create( + model="whisper-1", + file=audio_file ) - translation = client.audio.translations.create( - file=b"raw file contents", - model="whisper-1", - ) - print(translation) - javascript: | + node: | import fs from "fs"; import OpenAI from "openai"; @@ -2261,65611 +1427,15021 @@ paths: console.log(translation.text); } main(); - csharp: | - using System; - - using OpenAI.Audio; - - string audioFilePath = "audio.mp3"; - - AudioClient client = new( - model: "whisper-1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); + response: | + { + "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?" + } - AudioTranscription transcription = client.TranscribeAudio(audioFilePath); + /files: + get: + operationId: listFiles + tags: + - Files + summary: Returns a list of files that belong to the user's organization. + parameters: + - in: query + name: purpose + required: false + schema: + type: string + description: Only return files with the given purpose. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListFilesResponse" + x-oaiMeta: + name: List files + group: files + returns: A list of [File](/docs/api-reference/files/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() - Console.WriteLine($"{transcription.Text}"); + client.files.list() node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const translation = await client.audio.translations.create({ - file: fs.createReadStream('speech.mp3'), - model: 'whisper-1', - }); - - console.log(translation); - go: | - package main + import OpenAI from "openai"; - import ( - "bytes" - "context" - "fmt" - "io" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const list = await openai.files.list(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - translation, err := client.Audio.Translations.New(context.TODO(), openai.AudioTranslationNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Model: openai.AudioModelWhisper1, - }) - if err != nil { - panic(err.Error()) + for await (const file of list) { + console.log(file); } - fmt.Printf("%+v\n", translation) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.audio.AudioModel; - import com.openai.models.audio.translations.TranslationCreateParams; - import com.openai.models.audio.translations.TranslationCreateResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - TranslationCreateParams params = TranslationCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .model(AudioModel.WHISPER_1) - .build(); - TranslationCreateResponse translation = client.audio().translations().create(params); - } } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - translation = openai.audio.translations.create(file: Pathname(__FILE__), model: :"whisper-1") - - puts(translation) - description: Translates audio into English. - /batches: + main(); + response: | + { + "data": [ + { + "id": "file-abc123", + "object": "file", + "bytes": 175, + "created_at": 1613677385, + "filename": "salesOverview.pdf", + "purpose": "assistants", + }, + { + "id": "file-abc123", + "object": "file", + "bytes": 140, + "created_at": 1613779121, + "filename": "puppy.jsonl", + "purpose": "fine-tune", + } + ], + "object": "list" + } post: - summary: Create batch - operationId: createBatch + operationId: createFile tags: - - Batch - requestBody: - required: true - content: - application/json: - schema: - type: object - required: - - input_file_id - - endpoint - - completion_window - properties: - input_file_id: - type: string - description: > - The ID of an uploaded file that contains requests for the new batch. + - Files + summary: | + Upload a file that can be used across various endpoints. Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 100 GB. + The Assistants API supports files up to 2 million tokens and of specific file types. See the [Assistants Tools guide](/docs/assistants/tools) for details. - See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to - upload a file. + The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats for fine-tuning [chat](/docs/api-reference/fine-tuning/chat-input) or [completions](/docs/api-reference/fine-tuning/completions-input) models. + The Batch API only supports `.jsonl` files up to 100 MB in size. The input also has a specific required [format](/docs/api-reference/batch/request-input). - Your input file must be formatted as a [JSONL - file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be - uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be - up to 200 MB in size. - endpoint: - type: string - enum: - - /v1/responses - - /v1/chat/completions - - /v1/embeddings - - /v1/completions - - /v1/moderations - description: >- - The endpoint to be used for all requests in the batch. Currently `/v1/responses`, - `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, and `/v1/moderations` are - supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 - embedding inputs across all requests in the batch. - completion_window: - type: string - enum: - - 24h - description: >- - The time frame within which the batch should be processed. Currently only `24h` is - supported. - metadata: - $ref: '#/components/schemas/Metadata' - output_expires_after: - $ref: '#/components/schemas/BatchFileExpirationAfter' + Please [contact us](https://help.openai.com/) if you need to increase these storage limits. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateFileRequest" responses: - '200': - description: Batch created successfully. + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/Batch' + $ref: "#/components/schemas/OpenAIFile" x-oaiMeta: - name: Create batch - group: batch - returns: The created [Batch](https://platform.openai.com/docs/api-reference/batch/object) object. + name: Upload file + group: files + returns: The uploaded [File](/docs/api-reference/files/object) object. examples: - response: | - { - "id": "batch_abc123", - "object": "batch", - "endpoint": "/v1/chat/completions", - "errors": null, - "input_file_id": "file-abc123", - "completion_window": "24h", - "status": "validating", - "output_file_id": null, - "error_file_id": null, - "created_at": 1711471533, - "in_progress_at": null, - "expires_at": null, - "finalizing_at": null, - "completed_at": null, - "failed_at": null, - "expired_at": null, - "cancelling_at": null, - "cancelled_at": null, - "request_counts": { - "total": 0, - "completed": 0, - "failed": 0 - }, - "metadata": { - "customer_id": "user_123456789", - "batch_description": "Nightly eval job", - } - } request: curl: | - curl https://api.openai.com/v1/batches \ + curl https://api.openai.com/v1/files \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "input_file_id": "file-abc123", - "endpoint": "/v1/chat/completions", - "completion_window": "24h" - }' - python: |- + -F purpose="fine-tune" \ + -F file="@mydata.jsonl" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", + client.files.create( + file=open("mydata.jsonl", "rb"), + purpose="fine-tune" ) - batch = client.batches.create( - completion_window="24h", - endpoint="/v1/responses", - input_file_id="input_file_id", - ) - print(batch.id) - node: | + node.js: |- + import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { - const batch = await openai.batches.create({ - input_file_id: "file-abc123", - endpoint: "/v1/chat/completions", - completion_window: "24h" + const file = await openai.files.create({ + file: fs.createReadStream("mydata.jsonl"), + purpose: "fine-tune", }); - console.log(batch); + console.log(file); } main(); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const batch = await client.batches.create({ - completion_window: '24h', - endpoint: '/v1/responses', - input_file_id: 'input_file_id', - }); + response: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "mydata.jsonl", + "purpose": "fine-tune", + } + /files/{file_id}: + delete: + operationId: deleteFile + tags: + - Files + summary: Delete a file. + parameters: + - in: path + name: file_id + required: true + schema: + type: string + description: The ID of the file to use for this request. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/DeleteFileResponse" + x-oaiMeta: + name: Delete file + group: files + returns: Deletion status. + examples: + request: + curl: | + curl https://api.openai.com/v1/files/file-abc123 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() - console.log(batch.id); - go: | - package main + client.files.delete("file-abc123") + node.js: |- + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const file = await openai.files.del("file-abc123"); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - batch, err := client.Batches.New(context.TODO(), openai.BatchNewParams{ - CompletionWindow: openai.BatchNewParamsCompletionWindow24h, - Endpoint: openai.BatchNewParamsEndpointV1Responses, - InputFileID: "input_file_id", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", batch.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.batches.Batch; - import com.openai.models.batches.BatchCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - BatchCreateParams params = BatchCreateParams.builder() - .completionWindow(BatchCreateParams.CompletionWindow._24H) - .endpoint(BatchCreateParams.Endpoint.V1_RESPONSES) - .inputFileId("input_file_id") - .build(); - Batch batch = client.batches().create(params); - } + console.log(file); } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - batch = openai.batches.create( - completion_window: :"24h", - endpoint: :"/v1/responses", - input_file_id: "input_file_id" - ) - - puts(batch) - description: Creates and executes a batch from an uploaded file of requests + main(); + response: | + { + "id": "file-abc123", + "object": "file", + "deleted": true + } get: - operationId: listBatches + operationId: retrieveFile tags: - - Batch - summary: List batch + - Files + summary: Returns information about a specific file. parameters: - - in: query - name: after - required: false + - in: path + name: file_id + required: true schema: type: string - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 + description: The ID of the file to use for this request. responses: - '200': - description: Batch listed successfully. + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ListBatchesResponse' + $ref: "#/components/schemas/OpenAIFile" x-oaiMeta: - name: List batch - group: batch - returns: A list of paginated [Batch](https://platform.openai.com/docs/api-reference/batch/object) objects. + name: Retrieve file + group: files + returns: The [File](/docs/api-reference/files/object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "id": "batch_abc123", - "object": "batch", - "endpoint": "/v1/chat/completions", - "errors": null, - "input_file_id": "file-abc123", - "completion_window": "24h", - "status": "completed", - "output_file_id": "file-cvaTdG", - "error_file_id": "file-HOWS94", - "created_at": 1711471533, - "in_progress_at": 1711471538, - "expires_at": 1711557933, - "finalizing_at": 1711493133, - "completed_at": 1711493163, - "failed_at": null, - "expired_at": null, - "cancelling_at": null, - "cancelled_at": null, - "request_counts": { - "total": 100, - "completed": 95, - "failed": 5 - }, - "metadata": { - "customer_id": "user_123456789", - "batch_description": "Nightly job", - } - }, - { ... }, - ], - "first_id": "batch_abc123", - "last_id": "batch_abc456", - "has_more": true - } request: curl: | - curl https://api.openai.com/v1/batches?limit=2 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + curl https://api.openai.com/v1/files/file-abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.batches.list() - page = page.data[0] - print(page.id) - node: | + client.files.retrieve("file-abc123") + node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { - const list = await openai.batches.list(); + const file = await openai.files.retrieve("file-abc123"); - for await (const batch of list) { - console.log(batch); - } + console.log(file); } main(); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const batch of client.batches.list()) { - console.log(batch.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Batches.List(context.TODO(), openai.BatchListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.batches.BatchListPage; - import com.openai.models.batches.BatchListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - BatchListPage page = client.batches().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.batches.list - - puts(page) - description: List your organization's batches. - /batches/{batch_id}: + response: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "mydata.jsonl", + "purpose": "fine-tune", + } + /files/{file_id}/content: get: - operationId: retrieveBatch + operationId: downloadFile tags: - - Batch - summary: Retrieve batch + - Files + summary: Returns the contents of the specified file. parameters: - in: path - name: batch_id + name: file_id required: true schema: type: string - description: The ID of the batch to retrieve. + description: The ID of the file to use for this request. responses: - '200': - description: Batch retrieved successfully. + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/Batch' + type: string x-oaiMeta: - name: Retrieve batch - group: batch - returns: >- - The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the - specified ID. + name: Retrieve file content + group: files + returns: The file content. examples: - response: | - { - "id": "batch_abc123", - "object": "batch", - "endpoint": "/v1/completions", - "errors": null, - "input_file_id": "file-abc123", - "completion_window": "24h", - "status": "completed", - "output_file_id": "file-cvaTdG", - "error_file_id": "file-HOWS94", - "created_at": 1711471533, - "in_progress_at": 1711471538, - "expires_at": 1711557933, - "finalizing_at": 1711493133, - "completed_at": 1711493163, - "failed_at": null, - "expired_at": null, - "cancelling_at": null, - "cancelled_at": null, - "request_counts": { - "total": 100, - "completed": 95, - "failed": 5 - }, - "metadata": { - "customer_id": "user_123456789", - "batch_description": "Nightly eval job", - } - } request: curl: | - curl https://api.openai.com/v1/batches/batch_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - python: |- + curl https://api.openai.com/v1/files/file-abc123/content \ + -H "Authorization: Bearer $OPENAI_API_KEY" > file.jsonl + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - batch = client.batches.retrieve( - "batch_id", - ) - print(batch.id) - node: | + content = client.files.content("file-abc123") + node.js: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { - const batch = await openai.batches.retrieve("batch_abc123"); + const file = await openai.files.content("file-abc123"); - console.log(batch); + console.log(file); } main(); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const batch = await client.batches.retrieve('batch_id'); - - console.log(batch.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - batch, err := client.Batches.Get(context.TODO(), "batch_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", batch.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.batches.Batch; - import com.openai.models.batches.BatchRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + /uploads: + post: + operationId: createUpload + tags: + - Uploads + summary: | + Creates an intermediate [Upload](/docs/api-reference/uploads/object) object that you can add [Parts](/docs/api-reference/uploads/part-object) to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. - Batch batch = client.batches().retrieve("batch_id"); - } - } - ruby: |- - require "openai" + Once you complete the Upload, we will create a [File](/docs/api-reference/files/object) object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. - openai = OpenAI::Client.new(api_key: "My API Key") + For certain `purpose`s, the correct `mime_type` must be specified. Please refer to documentation for the supported MIME types for your use case: + - [Assistants](/docs/assistants/tools/file-search/supported-files) - batch = openai.batches.retrieve("batch_id") + For guidance on the proper filename extensions for each purpose, please follow the documentation on [creating a File](/docs/api-reference/files/create). + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateUploadRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Upload" + x-oaiMeta: + name: Create upload + group: uploads + returns: The [Upload](/docs/api-reference/uploads/object) object with status `pending`. + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "purpose": "fine-tune", + "filename": "training_examples.jsonl", + "bytes": 2147483648, + "mime_type": "text/jsonl" + }' + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "pending", + "expires_at": 1719127296 + } - puts(batch) - description: Retrieves a batch. - /batches/{batch_id}/cancel: + /uploads/{upload_id}/parts: post: - operationId: cancelBatch + operationId: addUploadPart tags: - - Batch - summary: Cancel batch + - Uploads + summary: | + Adds a [Part](/docs/api-reference/uploads/part-object) to an [Upload](/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. + + Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + + It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](/docs/api-reference/uploads/complete). parameters: - in: path - name: batch_id + name: upload_id required: true schema: type: string - description: The ID of the batch to cancel. + example: upload_abc123 + description: | + The ID of the Upload. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/AddUploadPartRequest" responses: - '200': - description: Batch is cancelling. Returns the cancelling batch's details. + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/Batch' + $ref: "#/components/schemas/UploadPart" x-oaiMeta: - name: Cancel batch - group: batch - returns: >- - The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the - specified ID. + name: Add upload part + group: uploads + returns: The upload [Part](/docs/api-reference/uploads/part-object) object. examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/parts + -F data="aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz..." response: | { - "id": "batch_abc123", - "object": "batch", - "endpoint": "/v1/chat/completions", - "errors": null, - "input_file_id": "file-abc123", - "completion_window": "24h", - "status": "cancelling", - "output_file_id": null, - "error_file_id": null, - "created_at": 1711471533, - "in_progress_at": 1711471538, - "expires_at": 1711557933, - "finalizing_at": null, - "completed_at": null, - "failed_at": null, - "expired_at": null, - "cancelling_at": 1711475133, - "cancelled_at": null, - "request_counts": { - "total": 100, - "completed": 23, - "failed": 1 - }, - "metadata": { - "customer_id": "user_123456789", - "batch_description": "Nightly eval job", - } + "id": "part_def456", + "object": "upload.part", + "created_at": 1719185911, + "upload_id": "upload_abc123" } - request: - curl: | - curl https://api.openai.com/v1/batches/batch_abc123/cancel \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -X POST - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - batch = client.batches.cancel( - "batch_id", - ) - print(batch.id) - node: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - async function main() { - const batch = await openai.batches.cancel("batch_abc123"); - - console.log(batch); - } - - main(); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const batch = await client.batches.cancel('batch_id'); - - console.log(batch.id); - go: | - package main - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - batch, err := client.Batches.Cancel(context.TODO(), "batch_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", batch.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.batches.Batch; - import com.openai.models.batches.BatchCancelParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Batch batch = client.batches().cancel("batch_id"); - } - } - ruby: |- - require "openai" + /uploads/{upload_id}/complete: + post: + operationId: completeUpload + tags: + - Uploads + summary: | + Completes the [Upload](/docs/api-reference/uploads/object). - openai = OpenAI::Client.new(api_key: "My API Key") + Within the returned Upload object, there is a nested [File](/docs/api-reference/files/object) object that is ready to use in the rest of the platform. - batch = openai.batches.cancel("batch_id") + You can specify the order of the Parts by passing in an ordered list of the Part IDs. - puts(batch) - description: >- - Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before - changing to `cancelled`, where it will have partial results (if any) available in the output file. - /chat/completions: - get: - operationId: listChatCompletions - tags: - - Chat - summary: List Chat Completions + The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. parameters: - - name: model - in: query - description: The model used to generate the Chat Completions. - required: false + - in: path + name: upload_id + required: true schema: type: string - - name: metadata - in: query + example: upload_abc123 description: | - A list of metadata keys to filter the Chat Completions by. Example: + The ID of the Upload. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CompleteUploadRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Upload" + x-oaiMeta: + name: Complete upload + group: uploads + returns: The [Upload](/docs/api-reference/uploads/object) object with status `completed` with an additional `file` property containing the created usable File object. + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/complete + -d '{ + "part_ids": ["part_def456", "part_ghi789"] + }' + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "completed", + "expires_at": 1719127296, + "file": { + "id": "file-xyz321", + "object": "file", + "bytes": 2147483648, + "created_at": 1719186911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + } + } - `metadata[key1]=value1&metadata[key2]=value2` - required: false - schema: - $ref: '#/components/schemas/Metadata' - - name: after - in: query - description: Identifier for the last chat completion from the previous pagination request. - required: false - schema: - type: string - - name: limit - in: query - description: Number of Chat Completions to retrieve. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: >- - Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for - descending order. Defaults to `asc`. - required: false + /uploads/{upload_id}/cancel: + post: + operationId: cancelUpload + tags: + - Uploads + summary: | + Cancels the Upload. No Parts may be added after an Upload is cancelled. + parameters: + - in: path + name: upload_id + required: true schema: type: string - enum: - - asc - - desc - default: asc + example: upload_abc123 + description: | + The ID of the Upload. responses: - '200': - description: A list of Chat Completions + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ChatCompletionList' + $ref: "#/components/schemas/Upload" x-oaiMeta: - name: List Chat Completions - group: chat - returns: >- - A list of [Chat Completions](https://platform.openai.com/docs/api-reference/chat/list-object) - matching the specified filters. - path: list + name: Cancel upload + group: uploads + returns: The [Upload](/docs/api-reference/uploads/object) object with status `cancelled`. examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/cancel response: | { - "object": "list", - "data": [ - { - "object": "chat.completion", - "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "model": "gpt-4.1-2025-04-14", - "created": 1738960610, - "request_id": "req_ded8ab984ec4bf840f37566c1011c417", - "tool_choice": null, - "usage": { - "total_tokens": 31, - "completion_tokens": 18, - "prompt_tokens": 13 - }, - "seed": 4944116822809979520, - "top_p": 1.0, - "temperature": 1.0, - "presence_penalty": 0.0, - "frequency_penalty": 0.0, - "system_fingerprint": "fp_50cad350e4", - "input_user": null, - "service_tier": "default", - "tools": null, - "metadata": {}, - "choices": [ - { - "index": 0, - "message": { - "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", - "role": "assistant", - "tool_calls": null, - "function_call": null - }, - "finish_reason": "stop", - "logprobs": null - } - ], - "response_format": null - } - ], - "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "has_more": false + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "cancelled", + "expires_at": 1719127296 } - request: - curl: | - curl https://api.openai.com/v1/chat/completions \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.chat.completions.list() - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const chatCompletion of client.chat.completions.list()) { - console.log(chatCompletion.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Chat.Completions.List(context.TODO(), openai.ChatCompletionListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.chat.completions.ChatCompletionListPage; - import com.openai.models.chat.completions.ChatCompletionListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionListPage page = client.chat().completions().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.chat.completions.list - puts(page) - description: | - List stored Chat Completions. Only Chat Completions that have been stored - with the `store` parameter set to `true` will be returned. + /fine_tuning/jobs: post: - operationId: createChatCompletion + operationId: createFineTuningJob tags: - - Chat - summary: Create chat completion + - Fine-tuning + summary: | + Creates a fine-tuning job which begins the process of creating a new model from a given dataset. + + Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. + + [Learn more about fine-tuning](/docs/guides/fine-tuning) requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/CreateChatCompletionRequest' + $ref: "#/components/schemas/CreateFineTuningJobRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/CreateChatCompletionResponse' - text/event-stream: - schema: - $ref: '#/components/schemas/CreateChatCompletionStreamResponse' + $ref: "#/components/schemas/FineTuningJob" x-oaiMeta: - name: Create chat completion - group: chat - returns: > - Returns a [chat completion](https://platform.openai.com/docs/api-reference/chat/object) object, or a - streamed sequence of [chat completion - chunk](https://platform.openai.com/docs/api-reference/chat/streaming) objects if the request is - streamed. - path: create + name: Create fine-tuning job + group: fine-tuning + returns: A [fine-tuning.job](/docs/api-reference/fine-tuning/object) object. examples: - title: Default request: curl: | - curl https://api.openai.com/v1/chat/completions \ + curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ - "model": "VAR_chat_model_id", - "messages": [ - { - "role": "developer", - "content": "You are a helpful assistant." - }, - { - "role": "user", - "content": "Hello!" - } - ] + "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo", + "model": "gpt-4o-mini" }' - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", + client.fine_tuning.jobs.create( + training_file="file-abc123", + model="gpt-4o-mini" ) - chat_completion = client.chat.completions.create( - messages=[{ - "content": "string", - "role": "developer", - }], - model="gpt-4o", - ) - print(chat_completion) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatCompletion = await client.chat.completions.create({ - messages: [{ content: 'string', role: 'developer' }], - model: 'gpt-4o', - }); - - console.log(chatCompletion); - csharp: | - using System; - using System.Collections.Generic; - - using OpenAI.Chat; - - ChatClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - List messages = - [ - new SystemChatMessage("You are a helpful assistant."), - new UserChatMessage("Hello!") - ]; - - ChatCompletion completion = client.CompleteChat(messages); - - Console.WriteLine(completion.Content[0].Text); - go: | - package main + node.js: | + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123" + }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ - OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ - Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ - OfString: openai.String("string"), - }, - }, - }}, - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion) + console.log(fineTune); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .addDeveloperMessage("string") - .model(ChatModel.GPT_5_1) - .build(); - ChatCompletion chatCompletion = client.chat().completions().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - chat_completion = openai.chat.completions.create(messages: [{content: "string", role: - :developer}], model: :"gpt-5.1") - - - puts(chat_completion) + main(); response: | { - "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT", - "object": "chat.completion", - "created": 1741569952, - "model": "gpt-4.1-2025-04-14", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "content": "Hello! How can I assist you today?", - "refusal": null, - "annotations": [] - }, - "logprobs": null, - "finish_reason": "stop" - } - ], - "usage": { - "prompt_tokens": 19, - "completion_tokens": 10, - "total_tokens": 29, - "prompt_tokens_details": { - "cached_tokens": 0, - "audio_tokens": 0 - }, - "completion_tokens_details": { - "reasoning_tokens": 0, - "audio_tokens": 0, - "accepted_prediction_tokens": 0, - "rejected_prediction_tokens": 0 - } - }, - "service_tier": "default" + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", } - - title: Image input + - title: Epochs request: curl: | - curl https://api.openai.com/v1/chat/completions \ + curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ - "model": "gpt-4.1", - "messages": [ - { - "role": "user", - "content": [ - { - "type": "text", - "text": "What is in this image?" - }, - { - "type": "image_url", - "image_url": { - "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" - } - } - ] - } - ], - "max_tokens": 300 + "training_file": "file-abc123", + "model": "gpt-4o-mini", + "hyperparameters": { + "n_epochs": 2 + } }' - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - chat_completion = client.chat.completions.create( - messages=[{ - "content": "string", - "role": "developer", - }], - model="gpt-4o", + client.fine_tuning.jobs.create( + training_file="file-abc123", + model="gpt-4o-mini", + hyperparameters={ + "n_epochs":2 + } ) - print(chat_completion) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatCompletion = await client.chat.completions.create({ - messages: [{ content: 'string', role: 'developer' }], - model: 'gpt-4o', - }); - - console.log(chatCompletion); - csharp: | - using System; - using System.Collections.Generic; - - using OpenAI.Chat; - - ChatClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - List messages = - [ - new UserChatMessage( - [ - ChatMessageContentPart.CreateTextPart("What's in this image?"), - ChatMessageContentPart.CreateImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) - ]) - ]; - - ChatCompletion completion = client.CompleteChat(messages); - - Console.WriteLine(completion.Content[0].Text); - go: | - package main + node.js: | + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123", + model: "gpt-4o-mini", + hyperparameters: { n_epochs: 2 } + }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ - OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ - Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ - OfString: openai.String("string"), - }, - }, - }}, - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .addDeveloperMessage("string") - .model(ChatModel.GPT_5_1) - .build(); - ChatCompletion chatCompletion = client.chat().completions().create(params); - } + console.log(fineTune); } - ruby: >- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - - chat_completion = openai.chat.completions.create(messages: [{content: "string", role: - :developer}], model: :"gpt-5.1") - - - puts(chat_completion) + main(); response: | { - "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", - "object": "chat.completion", - "created": 1741570283, - "model": "gpt-4.1-2025-04-14", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", - "refusal": null, - "annotations": [] - }, - "logprobs": null, - "finish_reason": "stop" - } - ], - "usage": { - "prompt_tokens": 1117, - "completion_tokens": 46, - "total_tokens": 1163, - "prompt_tokens_details": { - "cached_tokens": 0, - "audio_tokens": 0 - }, - "completion_tokens_details": { - "reasoning_tokens": 0, - "audio_tokens": 0, - "accepted_prediction_tokens": 0, - "rejected_prediction_tokens": 0 - } - }, - "service_tier": "default" + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", + "hyperparameters": {"n_epochs": 2}, } - - title: Streaming + - title: Validation file request: curl: | - curl https://api.openai.com/v1/chat/completions \ + curl https://api.openai.com/v1/fine_tuning/jobs \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ - "model": "VAR_chat_model_id", - "messages": [ - { - "role": "developer", - "content": "You are a helpful assistant." - }, - { - "role": "user", - "content": "Hello!" - } - ], - "stream": true + "training_file": "file-abc123", + "validation_file": "file-abc123", + "model": "gpt-4o-mini" }' - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - chat_completion = client.chat.completions.create( - messages=[{ - "content": "string", - "role": "developer", - }], - model="gpt-4o", + client.fine_tuning.jobs.create( + training_file="file-abc123", + validation_file="file-def456", + model="gpt-4o-mini" ) - print(chat_completion) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatCompletion = await client.chat.completions.create({ - messages: [{ content: 'string', role: 'developer' }], - model: 'gpt-4o', - }); - - console.log(chatCompletion); - csharp: > - using System; - - using System.ClientModel; - - using System.Collections.Generic; - - using System.Threading.Tasks; - - - using OpenAI.Chat; - - - ChatClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - - List messages = - - [ - new SystemChatMessage("You are a helpful assistant."), - new UserChatMessage("Hello!") - ]; - - - AsyncCollectionResult completionUpdates = - client.CompleteChatStreamingAsync(messages); + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - await foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates) + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123", + validation_file: "file-abc123" + }); - { - if (completionUpdate.ContentUpdate.Count > 0) - { - Console.Write(completionUpdate.ContentUpdate[0].Text); - } + console.log(fineTune); } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ - OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ - Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ - OfString: openai.String("string"), - }, - }, - }}, - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .addDeveloperMessage("string") - .model(ChatModel.GPT_5_1) - .build(); - ChatCompletion chatCompletion = client.chat().completions().create(params); + main(); + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": "file-abc123", + "training_file": "file-abc123", + } + - title: W&B Integration + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-abc123", + "validation_file": "file-abc123", + "model": "gpt-4o-mini", + "integrations": [ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "ft-run-display-name" + "tags": [ + "first-experiment", "v2" + ] + } + } + ] + }' + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": "file-abc123", + "training_file": "file-abc123", + "integrations": [ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "entity": None, + "run_id": "ftjob-abc123" } - } - ruby: >- - require "openai" + } + ] + } + get: + operationId: listPaginatedFineTuningJobs + tags: + - Fine-tuning + summary: | + List your organization's fine-tuning jobs + parameters: + - name: after + in: query + description: Identifier for the last job from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of fine-tuning jobs to retrieve. + required: false + schema: + type: integer + default: 20 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListPaginatedFineTuningJobsResponse" + x-oaiMeta: + name: List fine-tuning jobs + group: fine-tuning + returns: A list of paginated [fine-tuning job](/docs/api-reference/fine-tuning/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs?limit=2 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + client.fine_tuning.jobs.list() + node.js: |- + import OpenAI from "openai"; - openai = OpenAI::Client.new(api_key: "My API Key") + const openai = new OpenAI(); + async function main() { + const list = await openai.fineTuning.jobs.list(); - chat_completion = openai.chat.completions.create(messages: [{content: "string", role: - :developer}], model: :"gpt-5.1") + for await (const fineTune of list) { + console.log(fineTune); + } + } + main(); + response: | + { + "object": "list", + "data": [ + { + "object": "fine_tuning.job.event", + "id": "ft-event-TjX0lMfOniCZX64t9PUQT5hn", + "created_at": 1689813489, + "level": "warn", + "message": "Fine tuning process stopping due to job cancellation", + "data": null, + "type": "message" + }, + { ... }, + { ... } + ], "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}: + get: + operationId: retrieveFineTuningJob + tags: + - Fine-tuning + summary: | + Get info about a fine-tuning job. - puts(chat_completion) - response: > - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", - "system_fingerprint": "fp_44709d6fcb", - "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} - - - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", - "system_fingerprint": "fp_44709d6fcb", - "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} - - - .... - + [Learn more about fine-tuning](/docs/guides/fine-tuning) + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/FineTuningJob" + x-oaiMeta: + name: Retrieve fine-tuning job + group: fine-tuning + returns: The [fine-tuning](/docs/api-reference/fine-tuning/object) object with the given ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs/ft-AF1WoRqd3aJAHsqc9NY7iL8F \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", - "system_fingerprint": "fp_44709d6fcb", - "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - - title: Functions - request: - curl: | - curl https://api.openai.com/v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "messages": [ - { - "role": "user", - "content": "What is the weather like in Boston today?" - } - ], - "tools": [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather in a given location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"] - } - }, - "required": ["location"] - } - } - } - ], - "tool_choice": "auto" - }' - python: |- - from openai import OpenAI + client.fine_tuning.jobs.retrieve("ftjob-abc123") + node.js: | + import OpenAI from "openai"; - client = OpenAI( - api_key="My API Key", - ) - chat_completion = client.chat.completions.create( - messages=[{ - "content": "string", - "role": "developer", - }], - model="gpt-4o", - ) - print(chat_completion) - node.js: |- - import OpenAI from 'openai'; + const openai = new OpenAI(); - const client = new OpenAI({ - apiKey: 'My API Key', - }); + async function main() { + const fineTune = await openai.fineTuning.jobs.retrieve("ftjob-abc123"); - const chatCompletion = await client.chat.completions.create({ - messages: [{ content: 'string', role: 'developer' }], - model: 'gpt-4o', - }); + console.log(fineTune); + } - console.log(chatCompletion); - csharp: | - using System; - using System.Collections.Generic; + main(); + response: &fine_tuning_example | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "davinci-002", + "created_at": 1692661014, + "finished_at": 1692661190, + "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", + "organization_id": "org-123", + "result_files": [ + "file-abc123" + ], + "status": "succeeded", + "validation_file": null, + "training_file": "file-abc123", + "hyperparameters": { + "n_epochs": 4, + "batch_size": 1, + "learning_rate_multiplier": 1.0 + }, + "trained_tokens": 5768, + "integrations": [], + "seed": 0, + "estimated_finish": 0 + } + /fine_tuning/jobs/{fine_tuning_job_id}/events: + get: + operationId: listFineTuningEvents + tags: + - Fine-tuning + summary: | + Get status updates for a fine-tuning job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to get events for. + - name: after + in: query + description: Identifier for the last event from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of events to retrieve. + required: false + schema: + type: integer + default: 20 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListFineTuningJobEventsResponse" + x-oaiMeta: + name: List fine-tuning events + group: fine-tuning + returns: A list of fine-tuning event objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/events \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() - using OpenAI.Chat; + client.fine_tuning.jobs.list_events( + fine_tuning_job_id="ftjob-abc123", + limit=2 + ) + node.js: |- + import OpenAI from "openai"; - ChatClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); + const openai = new OpenAI(); - ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool( - functionName: "get_current_weather", - functionDescription: "Get the current weather in a given location", - functionParameters: BinaryData.FromString(""" - { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": [ "celsius", "fahrenheit" ] - } - }, - "required": [ "location" ] - } - """) - ); + async function main() { + const list = await openai.fineTuning.list_events(id="ftjob-abc123", limit=2); - List messages = - [ - new UserChatMessage("What's the weather like in Boston today?"), - ]; + for await (const fineTune of list) { + console.log(fineTune); + } + } - ChatCompletionOptions options = new() + main(); + response: | + { + "object": "list", + "data": [ { - Tools = - { - getCurrentWeatherTool - }, - ToolChoice = ChatToolChoice.CreateAutoChoice(), - }; - - ChatCompletion completion = client.CompleteChat(messages, options); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ - OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ - Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ - OfString: openai.String("string"), - }, - }, - }}, - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .addDeveloperMessage("string") - .model(ChatModel.GPT_5_1) - .build(); - ChatCompletion chatCompletion = client.chat().completions().create(params); - } + "object": "fine_tuning.job.event", + "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm", + "created_at": 1721764800, + "level": "info", + "message": "Fine tuning job successfully completed", + "data": null, + "type": "message" + }, + { + "object": "fine_tuning.job.event", + "id": "ft-event-tyiGuB72evQncpH87xe505Sv", + "created_at": 1721764800, + "level": "info", + "message": "New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel", + "data": null, + "type": "message" } - ruby: >- - require "openai" + ], + "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}/cancel: + post: + operationId: cancelFineTuningJob + tags: + - Fine-tuning + summary: | + Immediately cancel a fine-tune job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to cancel. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/FineTuningJob" + x-oaiMeta: + name: Cancel fine-tuning + group: fine-tuning + returns: The cancelled [fine-tuning](/docs/api-reference/fine-tuning/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/cancel \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + client.fine_tuning.jobs.cancel("ftjob-abc123") + node.js: |- + import OpenAI from "openai"; - openai = OpenAI::Client.new(api_key: "My API Key") - - - chat_completion = openai.chat.completions.create(messages: [{content: "string", role: - :developer}], model: :"gpt-5.1") + const openai = new OpenAI(); + async function main() { + const fineTune = await openai.fineTuning.jobs.cancel("ftjob-abc123"); - puts(chat_completion) - response: | - { - "id": "chatcmpl-abc123", - "object": "chat.completion", - "created": 1699896916, - "model": "gpt-4o-mini", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "content": null, - "tool_calls": [ - { - "id": "call_abc123", - "type": "function", - "function": { - "name": "get_current_weather", - "arguments": "{\n\"location\": \"Boston, MA\"\n}" - } - } - ] - }, - "logprobs": null, - "finish_reason": "tool_calls" - } - ], - "usage": { - "prompt_tokens": 82, - "completion_tokens": 17, - "total_tokens": 99, - "completion_tokens_details": { - "reasoning_tokens": 0, - "accepted_prediction_tokens": 0, - "rejected_prediction_tokens": 0 - } - } + console.log(fineTune); } - - title: Logprobs - request: - curl: | - curl https://api.openai.com/v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "VAR_chat_model_id", - "messages": [ - { - "role": "user", - "content": "Hello!" - } - ], - "logprobs": true, - "top_logprobs": 2 - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - chat_completion = client.chat.completions.create( - messages=[{ - "content": "string", - "role": "developer", - }], - model="gpt-4o", - ) - print(chat_completion) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatCompletion = await client.chat.completions.create({ - messages: [{ content: 'string', role: 'developer' }], - model: 'gpt-4o', - }); - - console.log(chatCompletion); - csharp: | - using System; - using System.Collections.Generic; - - using OpenAI.Chat; - - ChatClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - List messages = - [ - new UserChatMessage("Hello!") - ]; - - ChatCompletionOptions options = new() + main(); + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "hyperparameters": { + "n_epochs": "auto" + }, + "status": "cancelled", + "validation_file": "file-abc123", + "training_file": "file-abc123" + } + /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints: + get: + operationId: listFineTuningJobCheckpoints + tags: + - Fine-tuning + summary: | + List checkpoints for a fine-tuning job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to get checkpoints for. + - name: after + in: query + description: Identifier for the last checkpoint ID from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of checkpoints to retrieve. + required: false + schema: + type: integer + default: 10 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListFineTuningJobCheckpointsResponse" + x-oaiMeta: + name: List fine-tuning checkpoints + group: fine-tuning + returns: A list of fine-tuning [checkpoint objects](/docs/api-reference/fine-tuning/checkpoint-object) for a fine-tuning job. + examples: + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints \ + -H "Authorization: Bearer $OPENAI_API_KEY" + response: | + { + "object": "list" + "data": [ + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", + "created_at": 1721764867, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000", + "metrics": { + "full_valid_loss": 0.134, + "full_valid_mean_token_accuracy": 0.874 + }, + "fine_tuning_job_id": "ftjob-abc123", + "step_number": 2000, + }, { - IncludeLogProbabilities = true, - TopLogProbabilityCount = 2 - }; + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", + "created_at": 1721764800, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000", + "metrics": { + "full_valid_loss": 0.167, + "full_valid_mean_token_accuracy": 0.781 + }, + "fine_tuning_job_id": "ftjob-abc123", + "step_number": 1000, + }, + ], + "first_id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", + "last_id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", + "has_more": true + } - ChatCompletion completion = client.CompleteChat(messages, options); + /models: + get: + operationId: listModels + tags: + - Models + summary: Lists the currently available models, and provides basic information about each one such as the owner and availability. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListModelsResponse" + x-oaiMeta: + name: List models + group: models + returns: A list of [model](/docs/api-reference/models/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/models \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() - Console.WriteLine(completion.Content[0].Text); - go: | - package main + client.models.list() + node.js: |- + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) + async function main() { + const list = await openai.models.list(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{ - OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{ - Content: openai.ChatCompletionDeveloperMessageParamContentUnion{ - OfString: openai.String("string"), - }, - }, - }}, - Model: shared.ChatModelGPT5_1, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.ChatModel; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .addDeveloperMessage("string") - .model(ChatModel.GPT_5_1) - .build(); - ChatCompletion chatCompletion = client.chat().completions().create(params); - } + for await (const model of list) { + console.log(model); } - ruby: >- - require "openai" - + } + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "model-id-0", + "object": "model", + "created": 1686935002, + "owned_by": "organization-owner" + }, + { + "id": "model-id-1", + "object": "model", + "created": 1686935002, + "owned_by": "organization-owner", + }, + { + "id": "model-id-2", + "object": "model", + "created": 1686935002, + "owned_by": "openai" + }, + ], + "object": "list" + } + /models/{model}: + get: + operationId: retrieveModel + tags: + - Models + summary: Retrieves a model instance, providing basic information about the model such as the owner and permissioning. + parameters: + - in: path + name: model + required: true + schema: + type: string + # ideally this will be an actual ID, so this will always work from browser + example: gpt-4o-mini + description: The ID of the model to use for this request + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Model" + x-oaiMeta: + name: Retrieve model + group: models + returns: The [model](/docs/api-reference/models/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/models/VAR_model_id \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() - openai = OpenAI::Client.new(api_key: "My API Key") + client.models.retrieve("VAR_model_id") + node.js: |- + import OpenAI from "openai"; + const openai = new OpenAI(); - chat_completion = openai.chat.completions.create(messages: [{content: "string", role: - :developer}], model: :"gpt-5.1") + async function main() { + const model = await openai.models.retrieve("VAR_model_id"); + console.log(model); + } - puts(chat_completion) - response: | - { - "id": "chatcmpl-123", - "object": "chat.completion", - "created": 1702685778, - "model": "gpt-4o-mini", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "content": "Hello! How can I assist you today?" - }, - "logprobs": { - "content": [ - { - "token": "Hello", - "logprob": -0.31725305, - "bytes": [72, 101, 108, 108, 111], - "top_logprobs": [ - { - "token": "Hello", - "logprob": -0.31725305, - "bytes": [72, 101, 108, 108, 111] - }, - { - "token": "Hi", - "logprob": -1.3190403, - "bytes": [72, 105] - } - ] - }, - { - "token": "!", - "logprob": -0.02380986, - "bytes": [ - 33 - ], - "top_logprobs": [ - { - "token": "!", - "logprob": -0.02380986, - "bytes": [33] - }, - { - "token": " there", - "logprob": -3.787621, - "bytes": [32, 116, 104, 101, 114, 101] - } - ] - }, - { - "token": " How", - "logprob": -0.000054669687, - "bytes": [32, 72, 111, 119], - "top_logprobs": [ - { - "token": " How", - "logprob": -0.000054669687, - "bytes": [32, 72, 111, 119] - }, - { - "token": "<|end|>", - "logprob": -10.953937, - "bytes": null - } - ] - }, - { - "token": " can", - "logprob": -0.015801601, - "bytes": [32, 99, 97, 110], - "top_logprobs": [ - { - "token": " can", - "logprob": -0.015801601, - "bytes": [32, 99, 97, 110] - }, - { - "token": " may", - "logprob": -4.161023, - "bytes": [32, 109, 97, 121] - } - ] - }, - { - "token": " I", - "logprob": -3.7697225e-6, - "bytes": [ - 32, - 73 - ], - "top_logprobs": [ - { - "token": " I", - "logprob": -3.7697225e-6, - "bytes": [32, 73] - }, - { - "token": " assist", - "logprob": -13.596657, - "bytes": [32, 97, 115, 115, 105, 115, 116] - } - ] - }, - { - "token": " assist", - "logprob": -0.04571125, - "bytes": [32, 97, 115, 115, 105, 115, 116], - "top_logprobs": [ - { - "token": " assist", - "logprob": -0.04571125, - "bytes": [32, 97, 115, 115, 105, 115, 116] - }, - { - "token": " help", - "logprob": -3.1089056, - "bytes": [32, 104, 101, 108, 112] - } - ] - }, - { - "token": " you", - "logprob": -5.4385737e-6, - "bytes": [32, 121, 111, 117], - "top_logprobs": [ - { - "token": " you", - "logprob": -5.4385737e-6, - "bytes": [32, 121, 111, 117] - }, - { - "token": " today", - "logprob": -12.807695, - "bytes": [32, 116, 111, 100, 97, 121] - } - ] - }, - { - "token": " today", - "logprob": -0.0040071653, - "bytes": [32, 116, 111, 100, 97, 121], - "top_logprobs": [ - { - "token": " today", - "logprob": -0.0040071653, - "bytes": [32, 116, 111, 100, 97, 121] - }, - { - "token": "?", - "logprob": -5.5247097, - "bytes": [63] - } - ] - }, - { - "token": "?", - "logprob": -0.0008108172, - "bytes": [63], - "top_logprobs": [ - { - "token": "?", - "logprob": -0.0008108172, - "bytes": [63] - }, - { - "token": "?\n", - "logprob": -7.184561, - "bytes": [63, 10] - } - ] - } - ] - }, - "finish_reason": "stop" - } - ], - "usage": { - "prompt_tokens": 9, - "completion_tokens": 9, - "total_tokens": 18, - "completion_tokens_details": { - "reasoning_tokens": 0, - "accepted_prediction_tokens": 0, - "rejected_prediction_tokens": 0 - } - }, - "system_fingerprint": null - } - description: > - **Starting a new project?** We recommend trying - [Responses](https://platform.openai.com/docs/api-reference/responses) - - to take advantage of the latest OpenAI platform features. Compare - - [Chat Completions with - Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). - - - --- - - - Creates a model response for the given chat conversation. Learn more in the - - [text generation](https://platform.openai.com/docs/guides/text-generation), - [vision](https://platform.openai.com/docs/guides/vision), - - and [audio](https://platform.openai.com/docs/guides/audio) guides. - - - Parameter support can differ depending on the model used to generate the - - response, particularly for newer reasoning models. Parameters that are only - - supported for reasoning models are noted below. For the current state of - - unsupported parameters in reasoning models, - - [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). - /chat/completions/{completion_id}: - get: - operationId: getChatCompletion + main(); + response: &retrieve_model_response | + { + "id": "VAR_model_id", + "object": "model", + "created": 1686935002, + "owned_by": "openai" + } + delete: + operationId: deleteModel tags: - - Chat - summary: Get chat completion + - Models + summary: Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. parameters: - in: path - name: completion_id + name: model required: true schema: type: string - description: The ID of the chat completion to retrieve. + example: ft:gpt-4o-mini:acemeco:suffix:abc123 + description: The model to delete responses: - '200': - description: A chat completion + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/CreateChatCompletionResponse' + $ref: "#/components/schemas/DeleteModelResponse" x-oaiMeta: - name: Get chat completion - group: chat - returns: >- - The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the - specified ID. + name: Delete a fine-tuned model + group: models + returns: Deletion status. examples: - response: | - { - "object": "chat.completion", - "id": "chatcmpl-abc123", - "model": "gpt-4o-2024-08-06", - "created": 1738960610, - "request_id": "req_ded8ab984ec4bf840f37566c1011c417", - "tool_choice": null, - "usage": { - "total_tokens": 31, - "completion_tokens": 18, - "prompt_tokens": 13 - }, - "seed": 4944116822809979520, - "top_p": 1.0, - "temperature": 1.0, - "presence_penalty": 0.0, - "frequency_penalty": 0.0, - "system_fingerprint": "fp_50cad350e4", - "input_user": null, - "service_tier": "default", - "tools": null, - "metadata": {}, - "choices": [ - { - "index": 0, - "message": { - "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", - "role": "assistant", - "tool_calls": null, - "function_call": null - }, - "finish_reason": "stop", - "logprobs": null - } - ], - "response_format": null - } request: curl: | - curl https://api.openai.com/v1/chat/completions/chatcmpl-abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - chat_completion = client.chat.completions.retrieve( - "completion_id", - ) - print(chat_completion.id) + client.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123") node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatCompletion = await client.chat.completions.retrieve('completion_id'); - - console.log(chatCompletion.id); - go: | - package main + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const model = await openai.models.del("ft:gpt-4o-mini:acemeco:suffix:abc123"); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.Get(context.TODO(), "completion_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion.ID) + console.log(model); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + main(); + response: | + { + "id": "ft:gpt-4o-mini:acemeco:suffix:abc123", + "object": "model", + "deleted": true + } - ChatCompletion chatCompletion = client.chat().completions().retrieve("completion_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - chat_completion = openai.chat.completions.retrieve("completion_id") - - puts(chat_completion) - description: | - Get a stored chat completion. Only Chat Completions that have been created - with the `store` parameter set to `true` will be returned. + /moderations: post: - operationId: updateChatCompletion + operationId: createModeration tags: - - Chat - summary: Update chat completion - parameters: - - in: path - name: completion_id - required: true - schema: - type: string - description: The ID of the chat completion to update. + - Moderations + summary: Classifies if text is potentially harmful. requestBody: required: true content: application/json: schema: - type: object - required: - - metadata - properties: - metadata: - $ref: '#/components/schemas/Metadata' + $ref: "#/components/schemas/CreateModerationRequest" responses: - '200': - description: A chat completion + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/CreateChatCompletionResponse' + $ref: "#/components/schemas/CreateModerationResponse" x-oaiMeta: - name: Update chat completion - group: chat - returns: >- - The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the - specified ID. + name: Create moderation + group: moderations + returns: A [moderation](/docs/api-reference/moderations/object) object. examples: - response: | - { - "object": "chat.completion", - "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "model": "gpt-4o-2024-08-06", - "created": 1738960610, - "request_id": "req_ded8ab984ec4bf840f37566c1011c417", - "tool_choice": null, - "usage": { - "total_tokens": 31, - "completion_tokens": 18, - "prompt_tokens": 13 - }, - "seed": 4944116822809979520, - "top_p": 1.0, - "temperature": 1.0, - "presence_penalty": 0.0, - "frequency_penalty": 0.0, - "system_fingerprint": "fp_50cad350e4", - "input_user": null, - "service_tier": "default", - "tools": null, - "metadata": { - "foo": "bar" - }, - "choices": [ - { - "index": 0, - "message": { - "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", - "role": "assistant", - "tool_calls": null, - "function_call": null - }, - "finish_reason": "stop", - "logprobs": null - } - ], - "response_format": null - } request: curl: | - curl -X POST https://api.openai.com/v1/chat/completions/chat_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ + curl https://api.openai.com/v1/moderations \ -H "Content-Type: application/json" \ - -d '{"metadata": {"foo": "bar"}}' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - chat_completion = client.chat.completions.update( - completion_id="completion_id", - metadata={ - "foo": "string" - }, - ) - print(chat_completion.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const chatCompletion = await client.chat.completions.update('completion_id', { metadata: { foo: - 'string' } }); - - - console.log(chatCompletion.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletion, err := client.Chat.Completions.Update( - context.TODO(), - "completion_id", - openai.ChatCompletionUpdateParams{ - Metadata: shared.Metadata{ - "foo": "string", - }, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletion.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.JsonValue; - import com.openai.models.chat.completions.ChatCompletion; - import com.openai.models.chat.completions.ChatCompletionUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionUpdateParams params = ChatCompletionUpdateParams.builder() - .completionId("completion_id") - .metadata(ChatCompletionUpdateParams.Metadata.builder() - .putAdditionalProperty("foo", JsonValue.from("string")) - .build()) - .build(); - ChatCompletion chatCompletion = client.chat().completions().update(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - chat_completion = openai.chat.completions.update("completion_id", metadata: {foo: "string"}) - - puts(chat_completion) - description: | - Modify a stored chat completion. Only Chat Completions that have been - created with the `store` parameter set to `true` can be modified. Currently, - the only supported modification is to update the `metadata` field. - delete: - operationId: deleteChatCompletion - tags: - - Chat - summary: Delete chat completion - parameters: - - in: path - name: completion_id - required: true - schema: - type: string - description: The ID of the chat completion to delete. - responses: - '200': - description: The chat completion was deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ChatCompletionDeleted' - x-oaiMeta: - name: Delete chat completion - group: chat - returns: A deletion confirmation object. - examples: - response: | - { - "object": "chat.completion.deleted", - "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/chat/completions/chat_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + -d '{ + "input": "I want to kill them." + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - chat_completion_deleted = client.chat.completions.delete( - "completion_id", - ) - print(chat_completion_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatCompletionDeleted = await client.chat.completions.delete('completion_id'); - - console.log(chatCompletionDeleted.id); - go: | - package main + moderation = client.moderations.create(input="I want to kill them.") + print(moderation) + node.js: | + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const moderation = await openai.moderations.create({ input: "I want to kill them." }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatCompletionDeleted, err := client.Chat.Completions.Delete(context.TODO(), "completion_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatCompletionDeleted.ID) + console.log(moderation); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.chat.completions.ChatCompletionDeleteParams; - import com.openai.models.chat.completions.ChatCompletionDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatCompletionDeleted chatCompletionDeleted = client.chat().completions().delete("completion_id"); + main(); + response: &moderation_example | + { + "id": "modr-XXXXX", + "model": "text-moderation-005", + "results": [ + { + "flagged": true, + "categories": { + "sexual": false, + "hate": false, + "harassment": false, + "self-harm": false, + "sexual/minors": false, + "hate/threatening": false, + "violence/graphic": false, + "self-harm/intent": false, + "self-harm/instructions": false, + "harassment/threatening": true, + "violence": true, + }, + "category_scores": { + "sexual": 1.2282071e-06, + "hate": 0.010696256, + "harassment": 0.29842457, + "self-harm": 1.5236925e-08, + "sexual/minors": 5.7246268e-08, + "hate/threatening": 0.0060676364, + "violence/graphic": 4.435014e-06, + "self-harm/intent": 8.098441e-10, + "self-harm/instructions": 2.8498655e-11, + "harassment/threatening": 0.63055265, + "violence": 0.99011886, } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - chat_completion_deleted = openai.chat.completions.delete("completion_id") + } + ] + } - puts(chat_completion_deleted) - description: | - Delete a stored chat completion. Only Chat Completions that have been - created with the `store` parameter set to `true` can be deleted. - /chat/completions/{completion_id}/messages: + /assistants: get: - operationId: getChatCompletionMessages + operationId: listAssistants tags: - - Chat - summary: Get chat messages + - Assistants + summary: Returns a list of assistants. parameters: - - in: path - name: completion_id - required: true - schema: - type: string - description: The ID of the chat completion to retrieve messages from. - - name: after - in: query - description: Identifier for the last message from the previous pagination request. - required: false - schema: - type: string - name: limit in: query - description: Number of messages to retrieve. + description: &pagination_limit_param_description | + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query - description: >- - Sort order for messages by timestamp. Use `asc` for ascending order or `desc` for descending - order. Defaults to `asc`. - required: false + description: &pagination_order_param_description | + Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: &pagination_after_param_description | + A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: &pagination_before_param_description | + A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string - enum: - - asc - - desc - default: asc responses: - '200': - description: A list of messages + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ChatCompletionMessageList' + $ref: "#/components/schemas/ListAssistantsResponse" x-oaiMeta: - name: Get chat messages - group: chat - returns: >- - A list of [messages](https://platform.openai.com/docs/api-reference/chat/message-list) for the - specified chat completion. + name: List assistants + group: assistants + beta: true + returns: A list of [assistant](/docs/api-reference/assistants/object) objects. examples: - response: | - { - "object": "list", - "data": [ - { - "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", - "role": "user", - "content": "write a haiku about ai", - "name": null, - "content_parts": null - } - ], - "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", - "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", - "has_more": false - } request: curl: | - curl https://api.openai.com/v1/chat/completions/chat_abc123/messages \ + curl "https://api.openai.com/v1/assistants?order=desc&limit=20" \ + -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.chat.completions.messages.list( - completion_id="completion_id", + my_assistants = client.beta.assistants.list( + order="desc", + limit="20", ) - page = page.data[0] - print(page) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); + print(my_assistants.data) + node.js: |- + import OpenAI from "openai"; + const openai = new OpenAI(); - // Automatically fetches more pages as needed. + async function main() { + const myAssistants = await openai.beta.assistants.list({ + order: "desc", + limit: "20", + }); - for await (const chatCompletionStoreMessage of - client.chat.completions.messages.list('completion_id')) { - console.log(chatCompletionStoreMessage); + console.log(myAssistants.data); } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Chat.Completions.Messages.List( - context.TODO(), - "completion_id", - openai.ChatCompletionMessageListParams{ - - }, - ) - if err != nil { - panic(err.Error()) + main(); + response: &list_assistants_example | + { + "object": "list", + "data": [ + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698982736, + "name": "Coding Tutor", + "description": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant designed to make me better at coding!", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + }, + { + "id": "asst_abc456", + "object": "assistant", + "created_at": 1698982718, + "name": "My Assistant", + "description": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant designed to make me better at coding!", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + }, + { + "id": "asst_abc789", + "object": "assistant", + "created_at": 1698982643, + "name": null, + "description": null, + "model": "gpt-4o", + "instructions": null, + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.chat.completions.messages.MessageListPage; - import com.openai.models.chat.completions.messages.MessageListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - MessageListPage page = client.chat().completions().messages().list("completion_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.chat.completions.messages.list("completion_id") - - puts(page) - description: | - Get the messages in a stored chat completion. Only Chat Completions that - have been created with the `store` parameter set to `true` will be - returned. - /completions: + ], + "first_id": "asst_abc123", + "last_id": "asst_abc789", + "has_more": false + } post: - operationId: createCompletion + operationId: createAssistant tags: - - Completions - summary: Create completion + - Assistants + summary: Create an assistant with a model and instructions. requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/CreateCompletionRequest' + $ref: "#/components/schemas/CreateAssistantRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/CreateCompletionResponse' + $ref: "#/components/schemas/AssistantObject" x-oaiMeta: - name: Create completion - group: completions - returns: > - Returns a [completion](https://platform.openai.com/docs/api-reference/completions/object) object, or - a sequence of completion objects if the request is streamed. - legacy: true + name: Create assistant + group: assistants + beta: true + returns: An [assistant](/docs/api-reference/assistants/object) object. examples: - - title: No streaming + - title: Code Interpreter request: curl: | - curl https://api.openai.com/v1/completions \ + curl "https://api.openai.com/v1/assistants" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ -d '{ - "model": "VAR_completion_model_id", - "prompt": "Say this is a test", - "max_tokens": 7, - "temperature": 0 + "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + "name": "Math Tutor", + "tools": [{"type": "code_interpreter"}], + "model": "gpt-4o" }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - completion = client.completions.create( - model="string", - prompt="This is a test.", - ) - print(completion) - node.js: >- - import OpenAI from 'openai'; + python: | + from openai import OpenAI + client = OpenAI() - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const completion = await client.completions.create({ model: 'string', prompt: 'This is a - test.' }); - - - console.log(completion); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + my_assistant = client.beta.assistants.create( + instructions="You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + name="Math Tutor", + tools=[{"type": "code_interpreter"}], + model="gpt-4o", ) + print(my_assistant) + node.js: |- + import OpenAI from "openai"; - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{ - Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct, - Prompt: openai.CompletionNewParamsPromptUnion{ - OfString: openai.String("This is a test."), - }, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", completion) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.completions.Completion; - import com.openai.models.completions.CompletionCreateParams; - - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const myAssistant = await openai.beta.assistants.create({ + instructions: + "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + name: "Math Tutor", + tools: [{ type: "code_interpreter" }], + model: "gpt-4o", + }); - CompletionCreateParams params = CompletionCreateParams.builder() - .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT) - .prompt("This is a test.") - .build(); - Completion completion = client.completions().create(params); - } + console.log(myAssistant); } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - completion = openai.completions.create(model: :"gpt-3.5-turbo-instruct", prompt: "This is a - test.") - - puts(completion) - response: | + main(); + response: &create_assistants_example | { - "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", - "object": "text_completion", - "created": 1589478378, - "model": "VAR_completion_model_id", - "system_fingerprint": "fp_44709d6fcb", - "choices": [ + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698984975, + "name": "Math Tutor", + "description": null, + "model": "gpt-4o", + "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + "tools": [ { - "text": "\n\nThis is indeed a test", - "index": 0, - "logprobs": null, - "finish_reason": "length" + "type": "code_interpreter" } ], - "usage": { - "prompt_tokens": 5, - "completion_tokens": 7, - "total_tokens": 12 - } + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" } - - title: Streaming + - title: Files request: curl: | - curl https://api.openai.com/v1/completions \ + curl https://api.openai.com/v1/assistants \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ -d '{ - "model": "VAR_completion_model_id", - "prompt": "Say this is a test", - "max_tokens": 7, - "temperature": 0, - "stream": true + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", + "tools": [{"type": "file_search"}], + "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}}, + "model": "gpt-4o" }' - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - completion = client.completions.create( - model="string", - prompt="This is a test.", + my_assistant = client.beta.assistants.create( + instructions="You are an HR bot, and you have access to files to answer employee questions about company policies.", + name="HR Helper", + tools=[{"type": "file_search"}], + tool_resources={"file_search": {"vector_store_ids": ["vs_123"]}}, + model="gpt-4o" ) - print(completion) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const completion = await client.completions.create({ model: 'string', prompt: 'This is a - test.' }); - - - console.log(completion); - go: | - package main - - import ( - "context" - "fmt" + print(my_assistant) + node.js: |- + import OpenAI from "openai"; - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{ - Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct, - Prompt: openai.CompletionNewParamsPromptUnion{ - OfString: openai.String("This is a test."), + async function main() { + const myAssistant = await openai.beta.assistants.create({ + instructions: + "You are an HR bot, and you have access to files to answer employee questions about company policies.", + name: "HR Helper", + tools: [{ type: "file_search" }], + tool_resources: { + file_search: { + vector_store_ids: ["vs_123"] + } }, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", completion) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.completions.Completion; - import com.openai.models.completions.CompletionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + model: "gpt-4o" + }); - CompletionCreateParams params = CompletionCreateParams.builder() - .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT) - .prompt("This is a test.") - .build(); - Completion completion = client.completions().create(params); - } + console.log(myAssistant); } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - completion = openai.completions.create(model: :"gpt-3.5-turbo-instruct", prompt: "This is a - test.") - - - puts(completion) + main(); response: | { - "id": "cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe", - "object": "text_completion", - "created": 1690759702, - "choices": [ + "id": "asst_abc123", + "object": "assistant", + "created_at": 1699009403, + "name": "HR Helper", + "description": null, + "model": "gpt-4o", + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", + "tools": [ { - "text": "This", - "index": 0, - "logprobs": null, - "finish_reason": null + "type": "file_search" } ], - "model": "gpt-3.5-turbo-instruct" - "system_fingerprint": "fp_44709d6fcb", + "tool_resources": { + "file_search": { + "vector_store_ids": ["vs_123"] + } + }, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" } - description: Creates a completion for the provided prompt and parameters. - /containers: + + /assistants/{assistant_id}: get: - summary: List containers - description: List Containers - operationId: ListContainers + operationId: getAssistant + tags: + - Assistants + summary: Retrieves an assistant. parameters: - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. + - in: path + name: assistant_id + required: true schema: type: string + description: The ID of the assistant to retrieve. responses: - '200': - description: Success + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ContainerListResource' + $ref: "#/components/schemas/AssistantObject" x-oaiMeta: - name: List containers - group: containers - returns: a list of [container](https://platform.openai.com/docs/api-reference/containers/object) objects. - path: get + name: Retrieve assistant + group: assistants + beta: true + returns: The [assistant](/docs/api-reference/assistants/object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", - "object": "container", - "created_at": 1747844794, - "status": "running", - "expires_after": { - "anchor": "last_active_at", - "minutes": 20 - }, - "last_active_at": 1747844794, - "name": "My Container" - } - ], - "first_id": "container_123", - "last_id": "container_123", - "has_more": false - } request: curl: | - curl https://api.openai.com/v1/containers \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const containerListResponse of client.containers.list()) { - console.log(containerListResponse.id); - } - python: |- + curl https://api.openai.com/v1/assistants/asst_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.containers.list() - page = page.data[0] - print(page.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Containers.List(context.TODO(), openai.ContainerListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.ContainerListPage; - import com.openai.models.containers.ContainerListParams; + my_assistant = client.beta.assistants.retrieve("asst_abc123") + print(my_assistant) + node.js: |- + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const myAssistant = await openai.beta.assistants.retrieve( + "asst_abc123" + ); - ContainerListPage page = client.containers().list(); - } + console.log(myAssistant); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - page = openai.containers.list - - puts(page) + main(); + response: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1699009709, + "name": "HR Helper", + "description": null, + "model": "gpt-4o", + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", + "tools": [ + { + "type": "file_search" + } + ], + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } post: - summary: Create container - description: Create Container - operationId: CreateContainer - parameters: [] + operationId: modifyAssistant + tags: + - Assistants + summary: Modifies an assistant. + parameters: + - in: path + name: assistant_id + required: true + schema: + type: string + description: The ID of the assistant to modify. requestBody: + required: true content: application/json: schema: - $ref: '#/components/schemas/CreateContainerBody' + $ref: "#/components/schemas/ModifyAssistantRequest" responses: - '200': - description: Success + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ContainerResource' + $ref: "#/components/schemas/AssistantObject" x-oaiMeta: - name: Create container - group: containers - returns: The created [container](https://platform.openai.com/docs/api-reference/containers/object) object. - path: post + name: Modify assistant + group: assistants + beta: true + returns: The modified [assistant](/docs/api-reference/assistants/object) object. examples: - response: | - { - "id": "cntr_682e30645a488191b6363a0cbefc0f0a025ec61b66250591", - "object": "container", - "created_at": 1747857508, - "status": "running", - "expires_after": { - "anchor": "last_active_at", - "minutes": 20 - }, - "last_active_at": 1747857508, - "name": "My Container" - } request: curl: | - curl https://api.openai.com/v1/containers \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ + curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ -d '{ - "name": "My Container" - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const container = await client.containers.create({ name: 'name' }); - - console.log(container.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - container = client.containers.create( - name="name", - ) - print(container.id) - go: | - package main - - import ( - "context" - "fmt" + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + "tools": [{"type": "file_search"}], + "model": "gpt-4o" + }' + python: | + from openai import OpenAI + client = OpenAI() - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + my_updated_assistant = client.beta.assistants.update( + "asst_abc123", + instructions="You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + name="HR Helper", + tools=[{"type": "file_search"}], + model="gpt-4o" ) - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - container, err := client.Containers.New(context.TODO(), openai.ContainerNewParams{ - Name: "name", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", container.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.ContainerCreateParams; - import com.openai.models.containers.ContainerCreateResponse; - - public final class Main { - private Main() {} + print(my_updated_assistant) + node.js: |- + import OpenAI from "openai"; - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + const openai = new OpenAI(); - ContainerCreateParams params = ContainerCreateParams.builder() - .name("name") - .build(); - ContainerCreateResponse container = client.containers().create(params); + async function main() { + const myUpdatedAssistant = await openai.beta.assistants.update( + "asst_abc123", + { + instructions: + "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + name: "HR Helper", + tools: [{ type: "file_search" }], + model: "gpt-4o" } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") + ); - container = openai.containers.create(name: "name") + console.log(myUpdatedAssistant); + } - puts(container) - /containers/{container_id}: - get: - summary: Retrieve container - description: Retrieve Container - operationId: RetrieveContainer + main(); + response: | + { + "id": "asst_123", + "object": "assistant", + "created_at": 1699009709, + "name": "HR Helper", + "description": null, + "model": "gpt-4o", + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + "tools": [ + { + "type": "file_search" + } + ], + "tool_resources": { + "file_search": { + "vector_store_ids": [] + } + }, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + delete: + operationId: deleteAssistant + tags: + - Assistants + summary: Delete an assistant. parameters: - - name: container_id - in: path + - in: path + name: assistant_id required: true schema: type: string + description: The ID of the assistant to delete. responses: - '200': - description: Success + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ContainerResource' + $ref: "#/components/schemas/DeleteAssistantResponse" x-oaiMeta: - name: Retrieve container - group: containers - returns: The [container](https://platform.openai.com/docs/api-reference/containers/object) object. - path: get + name: Delete assistant + group: assistants + beta: true + returns: Deletion status examples: - response: | - { - "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", - "object": "container", - "created_at": 1747844794, - "status": "running", - "expires_after": { - "anchor": "last_active_at", - "minutes": 20 - }, - "last_active_at": 1747844794, - "name": "My Container" - } request: - curl: > - curl https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 - \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const container = await client.containers.retrieve('container_id'); - - console.log(container.id); - python: |- + curl: | + curl https://api.openai.com/v1/assistants/asst_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - container = client.containers.retrieve( - "container_id", - ) - print(container.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - container, err := client.Containers.Get(context.TODO(), "container_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", container.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.ContainerRetrieveParams; - import com.openai.models.containers.ContainerRetrieveResponse; + response = client.beta.assistants.delete("asst_abc123") + print(response) + node.js: |- + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const response = await openai.beta.assistants.del("asst_abc123"); - ContainerRetrieveResponse container = client.containers().retrieve("container_id"); - } + console.log(response); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - container = openai.containers.retrieve("container_id") + main(); + response: | + { + "id": "asst_abc123", + "object": "assistant.deleted", + "deleted": true + } - puts(container) - delete: - operationId: DeleteContainer - summary: Delete a container - description: Delete Container - parameters: - - name: container_id - in: path - description: The ID of the container to delete. - required: true - schema: - type: string + /threads: + post: + operationId: createThread + tags: + - Assistants + summary: Create a thread. + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/CreateThreadRequest" responses: - '200': + "200": description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ThreadObject" x-oaiMeta: - name: Delete a container - group: containers - returns: Deletion Status - path: delete + name: Create thread + group: threads + beta: true + returns: A [thread](/docs/api-reference/threads) object. examples: - response: | - { - "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", - "object": "container.deleted", - "deleted": true - } - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.containers.delete('container_id'); - python: |- - from openai import OpenAI + - title: Empty + request: + curl: | + curl https://api.openai.com/v1/threads \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '' + python: | + from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - client.containers.delete( - "container_id", - ) - go: | - package main + empty_thread = client.beta.threads.create() + print(empty_thread) + node.js: |- + import OpenAI from "openai"; - import ( - "context" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const emptyThread = await openai.beta.threads.create(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Containers.Delete(context.TODO(), "container_id") - if err != nil { - panic(err.Error()) + console.log(emptyThread); } - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.ContainerDeleteParams; - public final class Main { - private Main() {} + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699012949, + "metadata": {}, + "tool_resources": {} + } + - title: Messages + request: + curl: | + curl https://api.openai.com/v1/threads \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "messages": [{ + "role": "user", + "content": "Hello, what is AI?" + }, { + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }] + }' + python: | + from openai import OpenAI + client = OpenAI() - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + message_thread = client.beta.threads.create( + messages=[ + { + "role": "user", + "content": "Hello, what is AI?" + }, + { + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }, + ] + ) - client.containers().delete("container_id"); - } - } - ruby: |- - require "openai" + print(message_thread) + node.js: |- + import OpenAI from "openai"; - openai = OpenAI::Client.new(api_key: "My API Key") + const openai = new OpenAI(); - result = openai.containers.delete("container_id") + async function main() { + const messageThread = await openai.beta.threads.create({ + messages: [ + { + role: "user", + content: "Hello, what is AI?" + }, + { + role: "user", + content: "How does AI work? Explain it in simple terms.", + }, + ], + }); - puts(result) - /containers/{container_id}/files: - post: - summary: Create container file - description: > - Create a Container File + console.log(messageThread); + } + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": {}, + "tool_resources": {} + } - You can send either a multipart/form-data request with the raw file content, or a JSON request with a - file ID. - operationId: CreateContainerFile + /threads/{thread_id}: + get: + operationId: getThread + tags: + - Assistants + summary: Retrieves a thread. parameters: - - name: container_id - in: path + - in: path + name: thread_id required: true schema: type: string - requestBody: - required: true - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/CreateContainerFileBody' + description: The ID of the thread to retrieve. responses: - '200': - description: Success + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ContainerFileResource' + $ref: "#/components/schemas/ThreadObject" x-oaiMeta: - name: Create container file - group: containers - returns: >- - The created [container file](https://platform.openai.com/docs/api-reference/container-files/object) - object. - path: post + name: Retrieve thread + group: threads + beta: true + returns: The [thread](/docs/api-reference/threads/object) object matching the specified ID. examples: - response: | - { - "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", - "object": "container.file", - "created_at": 1747848842, - "bytes": 880, - "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", - "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", - "source": "user" - } request: - curl: > - curl - https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files - \ + curl: | + curl https://api.openai.com/v1/threads/thread_abc123 \ + -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F file="@example.txt" - node.js: |- - import OpenAI from 'openai'; + -H "OpenAI-Beta: assistants=v2" + python: | + from openai import OpenAI + client = OpenAI() - const client = new OpenAI({ - apiKey: 'My API Key', - }); + my_thread = client.beta.threads.retrieve("thread_abc123") + print(my_thread) + node.js: |- + import OpenAI from "openai"; - const file = await client.containers.files.create('container_id'); + const openai = new OpenAI(); - console.log(file.id); - python: |- - from openai import OpenAI + async function main() { + const myThread = await openai.beta.threads.retrieve( + "thread_abc123" + ); - client = OpenAI( - api_key="My API Key", - ) - file = client.containers.files.create( - container_id="container_id", - ) - print(file.id) - go: | - package main + console.log(myThread); + } - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - file, err := client.Containers.Files.New( - context.TODO(), - "container_id", - openai.ContainerFileNewParams{ - - }, - ) - if err != nil { - panic(err.Error()) + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": {}, + "tool_resources": { + "code_interpreter": { + "file_ids": [] } - fmt.Printf("%+v\n", file.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.files.FileCreateParams; - import com.openai.models.containers.files.FileCreateResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileCreateResponse file = client.containers().files().create("container_id"); - } } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - file = openai.containers.files.create("container_id") - - puts(file) - get: - summary: List container files - description: List Container files - operationId: ListContainerFiles + } + post: + operationId: modifyThread + tags: + - Assistants + summary: Modifies a thread. parameters: - - name: container_id - in: path + - in: path + name: thread_id required: true schema: type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string + description: The ID of the thread to modify. Only the `metadata` can be modified. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ModifyThreadRequest" responses: - '200': - description: Success + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ContainerFileListResource' + $ref: "#/components/schemas/ThreadObject" x-oaiMeta: - name: List container files - group: containers - returns: >- - a list of [container file](https://platform.openai.com/docs/api-reference/container-files/object) - objects. - path: get + name: Modify thread + group: threads + beta: true + returns: The modified [thread](/docs/api-reference/threads/object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", - "object": "container.file", - "created_at": 1747848842, - "bytes": 880, - "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", - "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", - "source": "user" - } - ], - "first_id": "cfile_682e0e8a43c88191a7978f477a09bdf5", - "has_more": false, - "last_id": "cfile_682e0e8a43c88191a7978f477a09bdf5" - } request: - curl: > - curl - https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files - \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const fileListResponse of client.containers.files.list('container_id')) { - console.log(fileListResponse.id); - } - python: |- + curl: | + curl https://api.openai.com/v1/threads/thread_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "metadata": { + "modified": "true", + "user": "abc123" + } + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.containers.files.list( - container_id="container_id", - ) - page = page.data[0] - print(page.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Containers.Files.List( - context.TODO(), - "container_id", - openai.ContainerFileListParams{ - - }, - ) - if err != nil { - panic(err.Error()) + my_updated_thread = client.beta.threads.update( + "thread_abc123", + metadata={ + "modified": "true", + "user": "abc123" } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.files.FileListPage; - import com.openai.models.containers.files.FileListParams; - - public final class Main { - private Main() {} + ) + print(my_updated_thread) + node.js: |- + import OpenAI from "openai"; - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + const openai = new OpenAI(); - FileListPage page = client.containers().files().list("container_id"); + async function main() { + const updatedThread = await openai.beta.threads.update( + "thread_abc123", + { + metadata: { modified: "true", user: "abc123" }, } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") + ); - page = openai.containers.files.list("container_id") + console.log(updatedThread); + } - puts(page) - /containers/{container_id}/files/{file_id}: - get: - summary: Retrieve container file - description: Retrieve Container File - operationId: RetrieveContainerFile + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": { + "modified": "true", + "user": "abc123" + }, + "tool_resources": {} + } + delete: + operationId: deleteThread + tags: + - Assistants + summary: Delete a thread. parameters: - - name: container_id - in: path - required: true - schema: - type: string - - name: file_id - in: path + - in: path + name: thread_id required: true schema: type: string + description: The ID of the thread to delete. responses: - '200': - description: Success + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/ContainerFileResource' + $ref: "#/components/schemas/DeleteThreadResponse" x-oaiMeta: - name: Retrieve container file - group: containers - returns: The [container file](https://platform.openai.com/docs/api-reference/container-files/object) object. - path: get + name: Delete thread + group: threads + beta: true + returns: Deletion status examples: - response: | - { - "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", - "object": "container.file", - "created_at": 1747848842, - "bytes": 880, - "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", - "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", - "source": "user" - } request: curl: | - curl https://api.openai.com/v1/containers/container_123/files/file_456 \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const file = await client.containers.files.retrieve('file_id', { container_id: 'container_id' - }); - - - console.log(file.id); - python: |- + curl https://api.openai.com/v1/threads/thread_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - file = client.containers.files.retrieve( - file_id="file_id", - container_id="container_id", - ) - print(file.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - file, err := client.Containers.Files.Get( - context.TODO(), - "container_id", - "file_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", file.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.files.FileRetrieveParams; - import com.openai.models.containers.files.FileRetrieveResponse; + response = client.beta.threads.delete("thread_abc123") + print(response) + node.js: |- + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const response = await openai.beta.threads.del("thread_abc123"); - FileRetrieveParams params = FileRetrieveParams.builder() - .containerId("container_id") - .fileId("file_id") - .build(); - FileRetrieveResponse file = client.containers().files().retrieve(params); - } + console.log(response); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - file = openai.containers.files.retrieve("file_id", container_id: "container_id") + main(); + response: | + { + "id": "thread_abc123", + "object": "thread.deleted", + "deleted": true + } - puts(file) - delete: - operationId: DeleteContainerFile - summary: Delete a container file - description: Delete Container File + /threads/{thread_id}/messages: + get: + operationId: listMessages + tags: + - Assistants + summary: Returns a list of messages for a given thread. parameters: - - name: container_id - in: path + - in: path + name: thread_id required: true schema: type: string - - name: file_id - in: path - required: true + description: The ID of the [thread](/docs/api-reference/threads) the messages belong to. + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string + - name: run_id + in: query + description: | + Filter messages by the run ID that generated them. schema: type: string responses: - '200': + "200": description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListMessagesResponse" x-oaiMeta: - name: Delete a container file - group: containers - returns: Deletion Status - path: delete + name: List messages + group: threads + beta: true + returns: A list of [message](/docs/api-reference/messages) objects. examples: - response: | - { - "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", - "object": "container.file.deleted", - "deleted": true - } request: - curl: > - curl -X DELETE - https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863/files/cfile_682e0e8a43c88191a7978f477a09bdf5 - \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.containers.files.delete('file_id', { container_id: 'container_id' }); - python: |- + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/messages \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - client.containers.files.delete( - file_id="file_id", - container_id="container_id", - ) - go: | - package main + thread_messages = client.beta.threads.messages.list("thread_abc123") + print(thread_messages.data) + node.js: |- + import OpenAI from "openai"; - import ( - "context" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const threadMessages = await openai.beta.threads.messages.list( + "thread_abc123" + ); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Containers.Files.Delete( - context.TODO(), - "container_id", - "file_id", - ) - if err != nil { - panic(err.Error()) - } + console.log(threadMessages.data); } - java: |- - package com.openai.example; - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.containers.files.FileDeleteParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileDeleteParams params = FileDeleteParams.builder() - .containerId("container_id") - .fileId("file_id") - .build(); - client.containers().files().delete(params); - } - } - ruby: |- - require "openai" + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1699016383, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + }, + { + "id": "msg_abc456", + "object": "thread.message", + "created_at": 1699016383, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "Hello, what is AI?", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + } + ], + "first_id": "msg_abc123", + "last_id": "msg_abc456", + "has_more": false + } + post: + operationId: createMessage + tags: + - Assistants + summary: Create a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/docs/api-reference/threads) to create a message for. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateMessageRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/MessageObject" + x-oaiMeta: + name: Create message + group: threads + beta: true + returns: A [message](/docs/api-reference/messages/object) object. + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/messages \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }' + python: | + from openai import OpenAI + client = OpenAI() + + thread_message = client.beta.threads.messages.create( + "thread_abc123", + role="user", + content="How does AI work? Explain it in simple terms.", + ) + print(thread_message) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const threadMessages = await openai.beta.threads.messages.create( + "thread_abc123", + { role: "user", content: "How does AI work? Explain it in simple terms." } + ); - openai = OpenAI::Client.new(api_key: "My API Key") + console.log(threadMessages); + } - result = openai.containers.files.delete("file_id", container_id: "container_id") + main(); + response: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1713226573, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + } - puts(result) - /containers/{container_id}/files/{file_id}/content: + /threads/{thread_id}/messages/{message_id}: get: - summary: Retrieve container file content - description: Retrieve Container File Content - operationId: RetrieveContainerFileContent + operationId: getMessage + tags: + - Assistants + summary: Retrieve a message. parameters: - - name: container_id - in: path + - in: path + name: thread_id required: true schema: type: string - - name: file_id - in: path + description: The ID of the [thread](/docs/api-reference/threads) to which this message belongs. + - in: path + name: message_id required: true schema: type: string + description: The ID of the message to retrieve. responses: - '200': - description: Success + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/MessageObject" x-oaiMeta: - name: Retrieve container file content - group: containers - returns: The contents of the container file. - path: get + name: Retrieve message + group: threads + beta: true + returns: The [message](/docs/api-reference/messages/object) object matching the specified ID. examples: - response: | - request: curl: | - curl https://api.openai.com/v1/containers/container_123/files/cfile_456/content \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const content = await client.containers.files.content.retrieve('file_id', { container_id: - 'container_id' }); - - - console.log(content); - - - const data = await content.blob(); - - console.log(data); - python: |- + curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - content = client.containers.files.content.retrieve( - file_id="file_id", - container_id="container_id", - ) - print(content) - data = content.read() - print(data) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + message = client.beta.threads.messages.retrieve( + message_id="msg_abc123", + thread_id="thread_abc123", ) + print(message) + node.js: |- + import OpenAI from "openai"; - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - content, err := client.Containers.Files.Content.Get( - context.TODO(), - "container_id", - "file_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", content) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.http.HttpResponse; - import com.openai.models.containers.files.content.ContentRetrieveParams; - - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const message = await openai.beta.threads.messages.retrieve( + "thread_abc123", + "msg_abc123" + ); - ContentRetrieveParams params = ContentRetrieveParams.builder() - .containerId("container_id") - .fileId("file_id") - .build(); - HttpResponse content = client.containers().files().content().retrieve(params); - } + console.log(message); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - content = openai.containers.files.content.retrieve("file_id", container_id: "container_id") - - puts(content) - /conversations/{conversation_id}/items: + main(); + response: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1699017614, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + } post: - operationId: createConversationItems + operationId: modifyMessage tags: - - Conversations - summary: Create items + - Assistants + summary: Modifies a message. parameters: - in: path - name: conversation_id + name: thread_id required: true schema: type: string - example: conv_123 - description: The ID of the conversation to add the item to. - - name: include - in: query - required: false + description: The ID of the thread to which this message belongs. + - in: path + name: message_id + required: true schema: - type: array - items: - $ref: '#/components/schemas/IncludeEnum' - description: > - 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. + type: string + description: The ID of the message to modify. requestBody: required: true content: application/json: schema: - properties: - items: - type: array - description: | - The items to add to the conversation. You may add up to 20 items at a time. - items: - $ref: '#/components/schemas/InputItem' - maxItems: 20 - required: - - items + $ref: "#/components/schemas/ModifyMessageRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ConversationItemList' + $ref: "#/components/schemas/MessageObject" x-oaiMeta: - name: Create items - group: conversations - returns: > - Returns the list of added - [items](https://platform.openai.com/docs/api-reference/conversations/list-items-object). - path: create-item + name: Modify message + group: threads + beta: true + returns: The modified [message](/docs/api-reference/messages/object) object. examples: - - title: Add a user message to a conversation - request: - curl: | - curl https://api.openai.com/v1/conversations/conv_123/items \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "items": [ - { - "type": "message", - "role": "user", - "content": [ - {"type": "input_text", "text": "Hello!"} - ] - }, - { - "type": "message", - "role": "user", - "content": [ - {"type": "input_text", "text": "How are you?"} - ] - } - ] + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "metadata": { + "modified": "true", + "user": "abc123" + } }' - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); + python: | + from openai import OpenAI + client = OpenAI() - const items = await client.conversations.items.create( - "conv_123", - { - items: [ - { - type: "message", - role: "user", - content: [{ type: "input_text", text: "Hello!" }], - }, - { - type: "message", - role: "user", - content: [{ type: "input_text", text: "How are you?" }], - }, - ], - } - ); - console.log(items.data); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - conversation_item_list = client.conversations.items.create( - conversation_id="conv_123", - items=[{ - "content": "string", - "role": "user", - "type": "message", - }], - ) - print(conversation_item_list.first_id) - csharp: | - using System; - using System.Collections.Generic; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - ConversationItemList created = client.ConversationItems.Create( - conversationId: "conv_123", - new CreateConversationItemsOptions - { - Items = new List - { - new ConversationMessage - { - Role = "user", - Content = - { - new ConversationInputText { Text = "Hello!" } - } - }, - new ConversationMessage - { - Role = "user", - Content = - { - new ConversationInputText { Text = "How are you?" } - } - } - } - } - ); - Console.WriteLine(created.Data.Count); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const conversationItemList = await client.conversations.items.create('conv_123', { - items: [{ content: 'string', role: 'user', type: 'message' }], - }); - - console.log(conversationItemList.first_id); - go: | - package main - - import ( - "context" - "fmt" + message = client.beta.threads.messages.update( + message_id="msg_abc12", + thread_id="thread_abc123", + metadata={ + "modified": "true", + "user": "abc123", + }, + ) + print(message) + node.js: |- + import OpenAI from "openai"; - "github.com/openai/openai-go" - "github.com/openai/openai-go/conversations" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversationItemList, err := client.Conversations.Items.New( - context.TODO(), - "conv_123", - conversations.ItemNewParams{ - Items: []responses.ResponseInputItemUnionParam{responses.ResponseInputItemUnionParam{ - OfMessage: &responses.EasyInputMessageParam{ - Content: responses.EasyInputMessageContentUnionParam{ - OfString: openai.String("string"), - }, - Role: responses.EasyInputMessageRoleUser, - Type: responses.EasyInputMessageTypeMessage, - }, - }}, + async function main() { + const message = await openai.beta.threads.messages.update( + "thread_abc123", + "msg_abc123", + { + metadata: { + modified: "true", + user: "abc123", }, - ) - if err != nil { - panic(err.Error()) } - fmt.Printf("%+v\n", conversationItemList.FirstID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.items.ConversationItemList; - import com.openai.models.conversations.items.ItemCreateParams; - import com.openai.models.responses.EasyInputMessage; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ItemCreateParams params = ItemCreateParams.builder() - .conversationId("conv_123") - .addItem(EasyInputMessage.builder() - .content("string") - .role(EasyInputMessage.Role.USER) - .type(EasyInputMessage.Type.MESSAGE) - .build()) - .build(); - ConversationItemList conversationItemList = client.conversations().items().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - conversation_item_list = openai.conversations.items.create("conv_123", items: [{content: - "string", role: :user, type: :message}]) - - - puts(conversation_item_list) - response: | - { - "object": "list", - "data": [ - { - "type": "message", - "id": "msg_abc", - "status": "completed", - "role": "user", - "content": [ - {"type": "input_text", "text": "Hello!"} - ] - }, - { - "type": "message", - "id": "msg_def", - "status": "completed", - "role": "user", - "content": [ - {"type": "input_text", "text": "How are you?"} - ] + }' + response: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1699017614, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] } - ], - "first_id": "msg_abc", - "last_id": "msg_def", - "has_more": false + } + ], + "file_ids": [], + "metadata": { + "modified": "true", + "user": "abc123" } - description: Create items in a conversation with the given ID. - get: - operationId: listConversationItems + } + delete: + operationId: deleteMessage tags: - - Conversations - summary: List items + - Assistants + summary: Deletes a message. parameters: - in: path - name: conversation_id + name: thread_id required: true schema: type: string - example: conv_123 - description: The ID of the conversation to list items for. - - name: limit - in: query - description: | - A limit on the number of objects to be returned. Limit can range between - 1 and 100, and the default is 20. - required: false - schema: - type: integer - default: 20 - - in: query - name: order - schema: - type: string - enum: - - asc - - desc - description: | - 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. - - in: query - name: after + description: The ID of the thread to which this message belongs. + - in: path + name: message_id + required: true schema: type: string - description: | - An item ID to list items after, used in pagination. - - name: include - in: query - required: false - schema: - type: array - items: - $ref: '#/components/schemas/IncludeEnum' - description: >- - 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 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). + description: The ID of the message to delete. responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ConversationItemList' + $ref: "#/components/schemas/DeleteMessageResponse" x-oaiMeta: - name: List items - group: conversations - returns: > - Returns a [list - object](https://platform.openai.com/docs/api-reference/conversations/list-items-object) containing - Conversation items. - path: list-items + name: Delete message + group: threads + beta: true + returns: Deletion status examples: - - title: List items in a conversation - request: - curl: | - curl "https://api.openai.com/v1/conversations/conv_123/items?limit=10" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); + request: + curl: | + curl -X DELETE https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: | + from openai import OpenAI + client = OpenAI() - const items = await client.conversations.items.list("conv_123", { limit: 10 }); - console.log(items.data); - python: |- - from openai import OpenAI + deleted_message = client.beta.threads.messages.delete( + message_id="msg_abc12", + thread_id="thread_abc123", + ) + print(deleted_message) + node.js: |- + import OpenAI from "openai"; - client = OpenAI( - api_key="My API Key", - ) - page = client.conversations.items.list( - conversation_id="conv_123", - ) - page = page.data[0] - print(page) - csharp: | - using System; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); + const openai = new OpenAI(); - ConversationItemList items = client.ConversationItems.List( - conversationId: "conv_123", - new ListConversationItemsOptions { Limit = 10 } + async function main() { + const deletedMessage = await openai.beta.threads.messages.del( + "thread_abc123", + "msg_abc123" ); - Console.WriteLine(items.Data.Count); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const conversationItem of client.conversations.items.list('conv_123')) { - console.log(conversationItem); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/conversations" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Conversations.Items.List( - context.TODO(), - "conv_123", - conversations.ItemListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.items.ItemListPage; - import com.openai.models.conversations.items.ItemListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ItemListPage page = client.conversations().items().list("conv_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - page = openai.conversations.items.list("conv_123") - - puts(page) - response: | - { - "object": "list", - "data": [ - { - "type": "message", - "id": "msg_abc", - "status": "completed", - "role": "user", - "content": [ - {"type": "input_text", "text": "Hello!"} - ] - } - ], - "first_id": "msg_abc", - "last_id": "msg_abc", - "has_more": false + console.log(deletedMessage); } - description: List all items for a conversation with the given ID. - /conversations/{conversation_id}/items/{item_id}: - get: - operationId: getConversationItem - tags: - - Conversations - summary: Retrieve an item - parameters: - - in: path - name: conversation_id - required: true - schema: - type: string - example: conv_123 - description: The ID of the conversation that contains the item. - - in: path - name: item_id - required: true - schema: - type: string - example: msg_abc - description: The ID of the item to retrieve. - - name: include - in: query - required: false - schema: - type: array - items: - $ref: '#/components/schemas/IncludeEnum' - description: > - Additional fields to include in the response. See the `include` + response: | + { + "id": "msg_abc123", + "object": "thread.message.deleted", + "deleted": true + } - parameter for [listing Conversation items - above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) - for more information. + /threads/runs: + post: + operationId: createThreadAndRun + tags: + - Assistants + summary: Create a thread and run it in one request. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateThreadAndRunRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ConversationItem' + $ref: "#/components/schemas/RunObject" x-oaiMeta: - name: Retrieve an item - group: conversations - returns: > - Returns a [Conversation - Item](https://platform.openai.com/docs/api-reference/conversations/item-object). - path: get-item + name: Create thread and run + group: threads + beta: true + returns: A [run](/docs/api-reference/runs/object) object. examples: - - title: Retrieve an item + - title: Default request: curl: | - curl https://api.openai.com/v1/conversations/conv_123/items/msg_abc \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const item = await client.conversations.items.retrieve( - "conv_123", - "msg_abc" - ); - console.log(item); - python: |- + curl https://api.openai.com/v1/threads/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123", + "thread": { + "messages": [ + {"role": "user", "content": "Explain deep learning to a 5 year old."} + ] + } + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - conversation_item = client.conversations.items.retrieve( - item_id="msg_abc", - conversation_id="conv_123", + run = client.beta.threads.create_and_run( + assistant_id="asst_abc123", + thread={ + "messages": [ + {"role": "user", "content": "Explain deep learning to a 5 year old."} + ] + } ) - print(conversation_item) - csharp: | - using System; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - ConversationItem item = client.ConversationItems.Get( - conversationId: "conv_123", - itemId: "msg_abc" - ); - Console.WriteLine(item.Id); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const conversationItem = await client.conversations.items.retrieve('msg_abc', { - conversation_id: 'conv_123', - }); - - console.log(conversationItem); - go: | - package main + print(run) + node.js: | + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/conversations" - "github.com/openai/openai-go/option" - ) + async function main() { + const run = await openai.beta.threads.createAndRun({ + assistant_id: "asst_abc123", + thread: { + messages: [ + { role: "user", content: "Explain deep learning to a 5 year old." }, + ], + }, + }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversationItem, err := client.Conversations.Items.Get( - context.TODO(), - "conv_123", - "msg_abc", - conversations.ItemGetParams{ + console.log(run); + } - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", conversationItem) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.items.ConversationItem; - import com.openai.models.conversations.items.ItemRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ItemRetrieveParams params = ItemRetrieveParams.builder() - .conversationId("conv_123") - .itemId("msg_abc") - .build(); - ConversationItem conversationItem = client.conversations().items().retrieve(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - conversation_item = openai.conversations.items.retrieve("msg_abc", conversation_id: - "conv_123") - - - puts(conversation_item) + main(); response: | { - "type": "message", - "id": "msg_abc", - "status": "completed", - "role": "user", - "content": [ - {"type": "input_text", "text": "Hello!"} - ] + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699076792, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "queued", + "started_at": null, + "expires_at": 1699077392, + "cancelled_at": null, + "failed_at": null, + "completed_at": null, + "required_action": null, + "last_error": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant.", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "temperature": 1.0, + "top_p": 1.0, + "max_completion_tokens": null, + "max_prompt_tokens": null, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "incomplete_details": null, + "usage": null, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true } - description: Get a single item from a conversation with the given IDs. - delete: - operationId: deleteConversationItem - tags: - - Conversations - summary: Delete an item - parameters: - - in: path - name: conversation_id - required: true - schema: - type: string - example: conv_123 - description: The ID of the conversation that contains the item. - - in: path - name: item_id - required: true - schema: - type: string - example: msg_abc - description: The ID of the item to delete. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationResource' - x-oaiMeta: - name: Delete an item - group: conversations - returns: > - Returns the updated - [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object. - path: delete-item - examples: - - title: Delete an item + + - title: Streaming request: curl: | - curl -X DELETE https://api.openai.com/v1/conversations/conv_123/items/msg_abc \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const conversation = await client.conversations.items.delete( - "conv_123", - "msg_abc" - ); - console.log(conversation); - python: |- + curl https://api.openai.com/v1/threads/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_123", + "thread": { + "messages": [ + {"role": "user", "content": "Hello"} + ] + }, + "stream": true + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - conversation = client.conversations.items.delete( - item_id="msg_abc", - conversation_id="conv_123", + stream = client.beta.threads.create_and_run( + assistant_id="asst_123", + thread={ + "messages": [ + {"role": "user", "content": "Hello"} + ] + }, + stream=True ) - print(conversation.id) - csharp: | - using System; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - Conversation conversation = client.ConversationItems.Delete( - conversationId: "conv_123", - itemId: "msg_abc" - ); - Console.WriteLine(conversation.Id); - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const conversation = await client.conversations.items.delete('msg_abc', { conversation_id: - 'conv_123' }); + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; - console.log(conversation.id); - go: | - package main - - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const stream = await openai.beta.threads.createAndRun({ + assistant_id: "asst_123", + thread: { + messages: [ + { role: "user", content: "Hello" }, + ], + }, + stream: true + }); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversation, err := client.Conversations.Items.Delete( - context.TODO(), - "conv_123", - "msg_abc", - ) - if err != nil { - panic(err.Error()) + for await (const event of stream) { + console.log(event); } - fmt.Printf("%+v\n", conversation.ID) } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.Conversation; - import com.openai.models.conversations.items.ItemDeleteParams; - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + main(); + response: | + event: thread.created + data: {"id":"thread_123","object":"thread","created_at":1710348075,"metadata":{}} - ItemDeleteParams params = ItemDeleteParams.builder() - .conversationId("conv_123") - .itemId("msg_abc") - .build(); - Conversation conversation = client.conversations().items().delete(params); - } - } - ruby: |- - require "openai" + event: thread.run.created + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - openai = OpenAI::Client.new(api_key: "My API Key") + event: thread.run.queued + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - conversation = openai.conversations.items.delete("msg_abc", conversation_id: "conv_123") + event: thread.run.in_progress + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - puts(conversation) - response: | - { - "id": "conv_123", - "object": "conversation", - "created_at": 1741900000, - "metadata": {"topic": "demo"} - } - description: Delete an item from a conversation with the given IDs. - /embeddings: - post: - operationId: createEmbedding - tags: - - Embeddings - summary: Create embeddings - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateEmbeddingRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/CreateEmbeddingResponse' - x-oaiMeta: - name: Create embeddings - group: embeddings - returns: A list of [embedding](https://platform.openai.com/docs/api-reference/embeddings/object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "embedding", - "embedding": [ - 0.0023064255, - -0.009327292, - .... (1536 floats total for ada-002) - -0.0028842222, - ], - "index": 0 - } - ], - "model": "text-embedding-ada-002", - "usage": { - "prompt_tokens": 8, - "total_tokens": 8 - } - } - request: - curl: | - curl https://api.openai.com/v1/embeddings \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "input": "The food was delicious and the waiter...", - "model": "text-embedding-ada-002", - "encoding_format": "float" - }' - python: |- - from openai import OpenAI + event: thread.run.step.created + data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - client = OpenAI( - api_key="My API Key", - ) - create_embedding_response = client.embeddings.create( - input="The quick brown fox jumped over the lazy dog", - model="text-embedding-3-small", - ) - print(create_embedding_response.data) - node.js: |- - import OpenAI from 'openai'; + event: thread.run.step.in_progress + data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - const client = new OpenAI({ - apiKey: 'My API Key', - }); + event: thread.message.created + data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], "metadata":{}} - const createEmbeddingResponse = await client.embeddings.create({ - input: 'The quick brown fox jumped over the lazy dog', - model: 'text-embedding-3-small', - }); + event: thread.message.in_progress + data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], "metadata":{}} - console.log(createEmbeddingResponse.data); - csharp: > - using System; + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} + ... - using OpenAI.Embeddings; + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}} + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} - EmbeddingClient client = new( - model: "text-embedding-3-small", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); + event: thread.message.completed + data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}], "metadata":{}} + event: thread.run.step.completed + data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} - OpenAIEmbedding embedding = client.GenerateEmbedding(input: "The quick brown fox jumped over the - lazy dog"); + event: thread.run.completed + {"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - ReadOnlyMemory vector = embedding.ToFloats(); + event: done + data: [DONE] + - title: Streaming with Functions + request: + curl: | + curl https://api.openai.com/v1/threads/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123", + "thread": { + "messages": [ + {"role": "user", "content": "What is the weather like in San Francisco?"} + ] + }, + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() - for (int i = 0; i < vector.Length; i++) + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ] - { - Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); - } - go: | - package main + stream = client.beta.threads.create_and_run( + thread={ + "messages": [ + {"role": "user", "content": "What is the weather like in San Francisco?"} + ] + }, + assistant_id="asst_abc123", + tools=tools, + stream=True + ) - import ( - "context" - "fmt" + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - createEmbeddingResponse, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{ - Input: openai.EmbeddingNewParamsInputUnion{ - OfString: openai.String("The quick brown fox jumped over the lazy dog"), - }, - Model: openai.EmbeddingModelTextEmbeddingAda002, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", createEmbeddingResponse.Data) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.embeddings.CreateEmbeddingResponse; - import com.openai.models.embeddings.EmbeddingCreateParams; - import com.openai.models.embeddings.EmbeddingModel; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - EmbeddingCreateParams params = EmbeddingCreateParams.builder() - .input("The quick brown fox jumped over the lazy dog") - .model(EmbeddingModel.TEXT_EMBEDDING_ADA_002) - .build(); - CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(params); + const tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ]; + + async function main() { + const stream = await openai.beta.threads.createAndRun({ + assistant_id: "asst_123", + thread: { + messages: [ + { role: "user", content: "What is the weather like in San Francisco?" }, + ], + }, + tools: tools, + stream: true + }); + + for await (const event of stream) { + console.log(event); } - } - ruby: |- - require "openai" + } + + main(); + response: | + event: thread.created + data: {"id":"thread_123","object":"thread","created_at":1710351818,"metadata":{}} - openai = OpenAI::Client.new(api_key: "My API Key") + event: thread.run.created + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - create_embedding_response = openai.embeddings.create( - input: "The quick brown fox jumped over the lazy dog", - model: :"text-embedding-ada-002" - ) + event: thread.run.queued + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + event: thread.run.in_progress + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + event: thread.run.step.created + data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} + + event: thread.run.step.in_progress + data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} + + event: thread.run.step.delta + data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"","output":null}}]}}} + + event: thread.run.step.delta + data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"{\""}}]}}} + + event: thread.run.step.delta + data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"location"}}]}}} - puts(create_embedding_response) - description: Creates an embedding vector representing the input text. - /evals: + ... + + event: thread.run.step.delta + data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"ahrenheit"}}]}}} + + event: thread.run.step.delta + data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"\"}"}}]}}} + + event: thread.run.requires_action + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + event: done + data: [DONE] + + /threads/{thread_id}/runs: get: - operationId: listEvals + operationId: listRuns tags: - - Evals - summary: List evals + - Assistants + summary: Returns a list of runs belonging to a thread. parameters: - - name: after - in: query - description: Identifier for the last eval from the previous pagination request. - required: false + - name: thread_id + in: path + required: true schema: type: string + description: The ID of the thread the run belongs to. - name: limit in: query - description: Number of evals to retrieve. + description: *pagination_limit_param_description required: false schema: type: integer default: 20 - name: order in: query - description: Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for descending order. - required: false + description: *pagination_order_param_description schema: type: string - enum: - - asc - - desc - default: asc - - name: order_by + default: desc + enum: ["asc", "desc"] + - name: after in: query - description: | - Evals can be ordered by creation time or last updated time. Use - `created_at` for creation time or `updated_at` for last updated time. - required: false + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description schema: type: string - enum: - - created_at - - updated_at - default: created_at responses: - '200': - description: A list of evals + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/EvalList' + $ref: "#/components/schemas/ListRunsResponse" x-oaiMeta: - name: List evals - group: evals - returns: >- - A list of [evals](https://platform.openai.com/docs/api-reference/evals/object) matching the - specified filters. - path: list + name: List runs + group: threads + beta: true + returns: A list of [run](/docs/api-reference/runs/object) objects. examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | + from openai import OpenAI + client = OpenAI() + + runs = client.beta.threads.runs.list( + "thread_abc123" + ) + + print(runs) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const runs = await openai.beta.threads.runs.list( + "thread_abc123" + ); + + console.log(runs); + } + + main(); response: | { "object": "list", "data": [ { - "id": "eval_67abd54d9b0081909a86353f6fb9317a", - "object": "eval", - "data_source_config": { - "type": "stored_completions", - "metadata": { - "usecase": "push_notifications_summarizer" - }, - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object" - }, - "sample": { - "type": "object" - } - }, - "required": [ - "item", - "sample" + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699075072, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699075072, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699075073, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "tool_resources": { + "code_interpreter": { + "file_ids": [ + "file-abc123", + "file-abc456" ] } }, - "testing_criteria": [ + "metadata": {}, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + }, + { + "id": "run_abc456", + "object": "thread.run", + "created_at": 1699063290, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699063290, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699063291, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ { - "name": "Push Notification Summary Grader", - "id": "Push Notification Summary Grader-9b876f24-4762-4be9-aff4-db7a9b31c673", - "type": "label_model", - "model": "o3-mini", - "input": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "\nLabel the following push notification summary as either correct or incorrect.\nThe push notification and the summary will be provided below.\nA good push notificiation summary is concise and snappy.\nIf it is good, then label it as correct, if not, then incorrect.\n" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "\nPush notifications: {{item.input}}\nSummary: {{sample.output_text}}\n" - } - } - ], - "passing_labels": [ - "correct" - ], - "labels": [ - "correct", - "incorrect" - ], - "sampling_params": null + "type": "code_interpreter" } ], - "name": "Push Notification Summary Grader", - "created_at": 1739314509, - "metadata": { - "description": "A stored completions eval for push notification summaries" - } + "tool_resources": { + "code_interpreter": { + "file_ids": [ + "file-abc123", + "file-abc456" + ] + } + }, + "metadata": {}, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true } ], - "first_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "last_id": "eval_67aa884cf6688190b58f657d4441c8b7", - "has_more": true + "first_id": "run_abc123", + "last_id": "run_abc456", + "has_more": false } - request: - curl: | - curl https://api.openai.com/v1/evals?limit=1 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.evals.list() - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const evalListResponse of client.evals.list()) { - console.log(evalListResponse.id); - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.EvalListPage; - import com.openai.models.evals.EvalListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - EvalListPage page = client.evals().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.evals.list - - puts(page) - description: | - List evaluations for a project. post: - operationId: createEval + operationId: createRun tags: - - Evals - summary: Create eval + - Assistants + summary: Create a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to run. requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/CreateEvalRequest' + $ref: "#/components/schemas/CreateRunRequest" responses: - '201': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/Eval' + $ref: "#/components/schemas/RunObject" x-oaiMeta: - name: Create eval - group: evals - returns: The created [Eval](https://platform.openai.com/docs/api-reference/evals/object) object. - path: post + name: Create run + group: threads + beta: true + returns: A [run](/docs/api-reference/runs/object) object. examples: - response: | - { - "object": "eval", - "id": "eval_67b7fa9a81a88190ab4aa417e397ea21", - "data_source_config": { - "type": "stored_completions", - "metadata": { - "usecase": "chatbot" - }, - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object" - }, - "sample": { - "type": "object" - } - }, - "required": [ - "item", - "sample" - ] - }, - "testing_criteria": [ - { - "name": "Example label grader", - "type": "label_model", - "model": "o3-mini", - "input": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "Statement: {{item.input}}" - } - } - ], - "passing_labels": [ - "positive" - ], - "labels": [ - "positive", - "neutral", - "negative" - ] - } - ], - "name": "Sentiment", - "created_at": 1740110490, - "metadata": { - "description": "An eval for sentiment analysis" - } - } - request: - curl: | - curl https://api.openai.com/v1/evals \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Sentiment", - "data_source_config": { - "type": "stored_completions", - "metadata": { - "usecase": "chatbot" - } - }, - "testing_criteria": [ - { - "type": "label_model", - "model": "o3-mini", - "input": [ - { - "role": "developer", - "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" - }, - { - "role": "user", - "content": "Statement: {{item.input}}" - } - ], - "passing_labels": [ - "positive" - ], - "labels": [ - "positive", - "neutral", - "negative" - ], - "name": "Example label grader" - } - ] - }' - python: |- - from openai import OpenAI + - title: Default + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123" + }' + python: | + from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - eval = client.evals.create( - data_source_config={ - "item_schema": { - "foo": "bar" - }, - "type": "custom", - }, - testing_criteria=[{ - "input": [{ - "content": "content", - "role": "role", - }], - "labels": ["string"], - "model": "model", - "name": "name", - "passing_labels": ["string"], - "type": "label_model", - }], - ) - print(eval.id) - node.js: |- - import OpenAI from 'openai'; + run = client.beta.threads.runs.create( + thread_id="thread_abc123", + assistant_id="asst_abc123" + ) - const client = new OpenAI({ - apiKey: 'My API Key', - }); + print(run) + node.js: | + import OpenAI from "openai"; - const _eval = await client.evals.create({ - data_source_config: { item_schema: { foo: 'bar' }, type: 'custom' }, - testing_criteria: [ - { - input: [{ content: 'content', role: 'role' }], - labels: ['string'], - model: 'model', - name: 'name', - passing_labels: ['string'], - type: 'label_model', - }, - ], - }); - - console.log(_eval.id); - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.JsonValue; - import com.openai.models.evals.EvalCreateParams; - import com.openai.models.evals.EvalCreateResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - EvalCreateParams params = EvalCreateParams.builder() - .customDataSourceConfig(EvalCreateParams.DataSourceConfig.Custom.ItemSchema.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build()) - .addTestingCriterion(EvalCreateParams.TestingCriterion.LabelModel.builder() - .addInput(EvalCreateParams.TestingCriterion.LabelModel.Input.SimpleInputMessage.builder() - .content("content") - .role("role") - .build()) - .addLabel("string") - .model("model") - .name("name") - .addPassingLabel("string") - .build()) - .build(); - EvalCreateResponse eval = client.evals().create(params); - } - } - ruby: |- - require "openai" + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.create( + "thread_abc123", + { assistant_id: "asst_abc123" } + ); - openai = OpenAI::Client.new(api_key: "My API Key") + console.log(run); + } - eval_ = openai.evals.create( - data_source_config: {item_schema: {foo: "bar"}, type: :custom}, - testing_criteria: [ + main(); + response: &run_object_example | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699063290, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "queued", + "started_at": 1699063290, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699063291, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ { - input: [{content: "content", role: "role"}], - labels: ["string"], - model: "model", - name: "name", - passing_labels: ["string"], - type: :label_model + "type": "code_interpreter" } - ] - ) + ], + "metadata": {}, + "usage": null, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/threads/thread_123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_123", + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() - puts(eval_) - description: > - Create the structure of an evaluation that can be used to test a model's performance. + stream = client.beta.threads.runs.create( + thread_id="thread_123", + assistant_id="asst_123", + stream=True + ) - An evaluation is a set of testing criteria and the config for a data source, which dictates the schema - of the data used in the evaluation. After creating an evaluation, you can run it on different models - and model parameters. We support several types of graders and datasources. + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; - For more information, see the [Evals guide](https://platform.openai.com/docs/guides/evals). - /evals/{eval_id}: - get: - operationId: getEval - tags: - - Evals - summary: Get an eval - parameters: - - name: eval_id - in: path - required: true - schema: - type: string - description: The ID of the evaluation to retrieve. - responses: - '200': - description: The evaluation - content: - application/json: - schema: - $ref: '#/components/schemas/Eval' - x-oaiMeta: - name: Get an eval - group: evals - returns: >- - The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the - specified ID. - path: get - examples: - response: | - { - "object": "eval", - "id": "eval_67abd54d9b0081909a86353f6fb9317a", - "data_source_config": { - "type": "custom", - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object", - "properties": { - "input": { - "type": "string" - }, - "ground_truth": { - "type": "string" - } - }, - "required": [ - "input", - "ground_truth" - ] - } - }, - "required": [ - "item" - ] - } - }, - "testing_criteria": [ - { - "name": "String check", - "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", - "type": "string_check", - "input": "{{item.input}}", - "reference": "{{item.ground_truth}}", - "operation": "eq" - } - ], - "name": "External Data Eval", - "created_at": 1739314509, - "metadata": {}, - } - request: - curl: | - curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- - from openai import OpenAI + const openai = new OpenAI(); - client = OpenAI( - api_key="My API Key", - ) - eval = client.evals.retrieve( - "eval_id", - ) - print(eval.id) - node.js: |- - import OpenAI from 'openai'; + async function main() { + const stream = await openai.beta.threads.runs.create( + "thread_123", + { assistant_id: "asst_123", stream: true } + ); - const client = new OpenAI({ - apiKey: 'My API Key', - }); + for await (const event of stream) { + console.log(event); + } + } - const _eval = await client.evals.retrieve('eval_id'); + main(); + response: | + event: thread.run.created + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - console.log(_eval.id); - java: |- - package com.openai.example; + event: thread.run.queued + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.EvalRetrieveParams; - import com.openai.models.evals.EvalRetrieveResponse; + event: thread.run.in_progress + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - public final class Main { - private Main() {} + event: thread.run.step.created + data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + event: thread.run.step.in_progress + data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - EvalRetrieveResponse eval = client.evals().retrieve("eval_id"); - } - } - ruby: |- - require "openai" + event: thread.message.created + data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - openai = OpenAI::Client.new(api_key: "My API Key") + event: thread.message.in_progress + data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - eval_ = openai.evals.retrieve("eval_id") + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} - puts(eval_) - description: | - Get an evaluation by ID. - post: - operationId: updateEval - tags: - - Evals - summary: Update an eval - parameters: - - name: eval_id - in: path - required: true - schema: - type: string - description: The ID of the evaluation to update. - requestBody: - description: Request to update an evaluation - required: true - content: - application/json: - schema: - type: object - properties: - name: - type: string - description: Rename the evaluation. - metadata: - $ref: '#/components/schemas/Metadata' - responses: - '200': - description: The updated evaluation - content: - application/json: - schema: - $ref: '#/components/schemas/Eval' - x-oaiMeta: - name: Update an eval - group: evals - returns: >- - The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the updated - version. - path: update - examples: - response: | - { - "object": "eval", - "id": "eval_67abd54d9b0081909a86353f6fb9317a", - "data_source_config": { - "type": "custom", - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object", - "properties": { - "input": { - "type": "string" - }, - "ground_truth": { - "type": "string" - } - }, - "required": [ - "input", - "ground_truth" - ] - } - }, - "required": [ - "item" - ] - } - }, - "testing_criteria": [ - { - "name": "String check", - "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", - "type": "string_check", - "input": "{{item.input}}", - "reference": "{{item.ground_truth}}", - "operation": "eq" - } - ], - "name": "Updated Eval", - "created_at": 1739314509, - "metadata": {"description": "Updated description"}, - } - request: - curl: | - curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"name": "Updated Eval", "metadata": {"description": "Updated description"}}' - python: |- - from openai import OpenAI + ... - client = OpenAI( - api_key="My API Key", - ) - eval = client.evals.update( - eval_id="eval_id", - ) - print(eval.id) - node.js: |- - import OpenAI from 'openai'; + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}} - const client = new OpenAI({ - apiKey: 'My API Key', - }); + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} - const _eval = await client.evals.update('eval_id'); + event: thread.message.completed + data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710330642,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}],"metadata":{}} - console.log(_eval.id); - java: |- - package com.openai.example; + event: thread.run.step.completed + data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710330642,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.EvalUpdateParams; - import com.openai.models.evals.EvalUpdateResponse; + event: thread.run.completed + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - public final class Main { - private Main() {} + event: done + data: [DONE] - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + - title: Streaming with Functions + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123", + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() - EvalUpdateResponse eval = client.evals().update("eval_id"); - } - } - ruby: |- - require "openai" + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ] - openai = OpenAI::Client.new(api_key: "My API Key") + stream = client.beta.threads.runs.create( + thread_id="thread_abc123", + assistant_id="asst_abc123", + tools=tools, + stream=True + ) - eval_ = openai.evals.update("eval_id") + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; - puts(eval_) - description: | - Update certain properties of an evaluation. - delete: - operationId: deleteEval - tags: - - Evals - summary: Delete an eval - parameters: - - name: eval_id - in: path - required: true - schema: - type: string - description: The ID of the evaluation to delete. - responses: - '200': - description: Successfully deleted the evaluation. - content: - application/json: - schema: - type: object - properties: - object: - type: string - example: eval.deleted - deleted: - type: boolean - example: true - eval_id: - type: string - example: eval_abc123 - required: - - object - - deleted - - eval_id - '404': - description: Evaluation not found. - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - x-oaiMeta: - name: Delete an eval - group: evals - returns: A deletion confirmation object. - examples: - response: | - { - "object": "eval.deleted", - "deleted": true, - "eval_id": "eval_abc123" - } - request: - curl: | - curl https://api.openai.com/v1/evals/eval_abc123 \ - -X DELETE \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI + const openai = new OpenAI(); - client = OpenAI( - api_key="My API Key", - ) - eval = client.evals.delete( - "eval_id", - ) - print(eval.eval_id) - node.js: |- - import OpenAI from 'openai'; + const tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ]; + + async function main() { + const stream = await openai.beta.threads.runs.create( + "thread_abc123", + { + assistant_id: "asst_abc123", + tools: tools, + stream: true + } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + response: | + event: thread.run.created + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - const client = new OpenAI({ - apiKey: 'My API Key', - }); + event: thread.run.queued + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - const _eval = await client.evals.delete('eval_id'); + event: thread.run.in_progress + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - console.log(_eval.eval_id); - java: |- - package com.openai.example; + event: thread.run.step.created + data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.EvalDeleteParams; - import com.openai.models.evals.EvalDeleteResponse; + event: thread.run.step.in_progress + data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - public final class Main { - private Main() {} + event: thread.message.created + data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + event: thread.message.in_progress + data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - EvalDeleteResponse eval = client.evals().delete("eval_id"); - } - } - ruby: |- - require "openai" + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} - openai = OpenAI::Client.new(api_key: "My API Key") + ... - eval_ = openai.evals.delete("eval_id") + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}} - puts(eval_) - description: | - Delete an evaluation. - /evals/{eval_id}/runs: + event: thread.message.delta + data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} + + event: thread.message.completed + data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}],"metadata":{}} + + event: thread.run.step.completed + data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} + + event: thread.run.completed + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + event: done + data: [DONE] + + /threads/{thread_id}/runs/{run_id}: get: - operationId: getEvalRuns + operationId: getRun tags: - - Evals - summary: Get eval runs + - Assistants + summary: Retrieves a run. parameters: - - name: eval_id - in: path + - in: path + name: thread_id required: true schema: type: string - description: The ID of the evaluation to retrieve runs for. - - name: after - in: query - description: Identifier for the last run from the previous pagination request. - required: false - schema: - type: string - - name: limit - in: query - description: Number of runs to retrieve. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: >- - Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. - Defaults to `asc`. - required: false - schema: - type: string - enum: - - asc - - desc - default: asc - - name: status - in: query - description: Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` | `canceled`. - required: false + description: The ID of the [thread](/docs/api-reference/threads) that was run. + - in: path + name: run_id + required: true schema: type: string - enum: - - queued - - in_progress - - completed - - canceled - - failed + description: The ID of the run to retrieve. responses: - '200': - description: A list of runs for the evaluation + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/EvalRunList' + $ref: "#/components/schemas/RunObject" x-oaiMeta: - name: Get eval runs - group: evals - returns: >- - A list of [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) objects - matching the specified ID. - path: get-runs + name: Retrieve run + group: threads + beta: true + returns: The [run](/docs/api-reference/runs/object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "object": "eval.run", - "id": "evalrun_67e0c7d31560819090d60c0780591042", - "eval_id": "eval_67e0c726d560819083f19a957c4c640b", - "report_url": "https://platform.openai.com/evaluations/eval_67e0c726d560819083f19a957c4c640b", - "status": "completed", - "model": "o3-mini", - "name": "bulk_with_negative_examples_o3-mini", - "created_at": 1742784467, - "result_counts": { - "total": 1, - "errored": 0, - "failed": 0, - "passed": 1 - }, - "per_model_usage": [ - { - "model_name": "o3-mini", - "invocation_count": 1, - "prompt_tokens": 563, - "completion_tokens": 874, - "total_tokens": 1437, - "cached_tokens": 0 - } - ], - "per_testing_criteria_results": [ - { - "testing_criteria": "Push Notification Summary Grader-1808cd0b-eeec-4e0b-a519-337e79f4f5d1", - "passed": 1, - "failed": 0 - } - ], - "data_source": { - "type": "completions", - "source": { - "type": "file_content", - "content": [ - { - "item": { - "notifications": "\n- New message from Sarah: \"Can you call me later?\"\n- Your package has been delivered!\n- Flash sale: 20% off electronics for the next 2 hours!\n" - } - } - ] - }, - "input_messages": { - "type": "template", - "template": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "\n\n\n\nYou are a helpful assistant that takes in an array of push notifications and returns a collapsed summary of them.\nThe push notification will be provided as follows:\n\n...notificationlist...\n\n\nYou should return just the summary and nothing else.\n\n\nYou should return a summary that is concise and snappy.\n\n\nHere is an example of a good summary:\n\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n\n\nTraffic alert, package expected by 5pm, suggestion for new friend (Emily).\n\n\n\nHere is an example of a bad summary:\n\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n\n\nTraffic alert reported on main street. You have a package that will arrive by 5pm, Emily is a new friend suggested for you.\n\n" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "{{item.notifications}}" - } - } - ] - }, - "model": "o3-mini", - "sampling_params": null - }, - "error": null, - "metadata": {} - } - ], - "first_id": "evalrun_67e0c7d31560819090d60c0780591042", - "last_id": "evalrun_67e0c7d31560819090d60c0780591042", - "has_more": true - } request: curl: | - curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs \ + curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.evals.runs.list( - eval_id="eval_id", + run = client.beta.threads.runs.retrieve( + thread_id="thread_abc123", + run_id="run_abc123" ) - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const runListResponse of client.evals.runs.list('eval_id')) { - console.log(runListResponse.id); - } - java: |- - package com.openai.example; - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.runs.RunListPage; - import com.openai.models.evals.runs.RunListParams; + print(run) + node.js: | + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const run = await openai.beta.threads.runs.retrieve( + "thread_abc123", + "run_abc123" + ); - RunListPage page = client.evals().runs().list("eval_id"); - } + console.log(run); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.evals.runs.list("eval_id") - puts(page) - description: | - Get a list of runs for an evaluation. + main(); + response: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699075072, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699075072, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699075073, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "metadata": {}, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } post: - operationId: createEvalRun + operationId: modifyRun tags: - - Evals - summary: Create eval run + - Assistants + summary: Modifies a run. parameters: - in: path - name: eval_id + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/docs/api-reference/threads) that was run. + - in: path + name: run_id required: true schema: type: string - description: The ID of the evaluation to create a run for. + description: The ID of the run to modify. requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/CreateEvalRunRequest' + $ref: "#/components/schemas/ModifyRunRequest" responses: - '201': - description: Successfully created a run for the evaluation - content: - application/json: - schema: - $ref: '#/components/schemas/EvalRun' - '400': - description: Bad request (for example, missing eval object) + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: "#/components/schemas/RunObject" x-oaiMeta: - name: Create eval run - group: evals - returns: >- - The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the - specified ID. + name: Modify run + group: threads + beta: true + returns: The modified [run](/docs/api-reference/runs/object) object matching the specified ID. examples: - response: | - { - "object": "eval.run", - "id": "evalrun_67e57965b480819094274e3a32235e4c", - "eval_id": "eval_67e579652b548190aaa83ada4b125f47", - "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47&run_id=evalrun_67e57965b480819094274e3a32235e4c", - "status": "queued", - "model": "gpt-4o-mini", - "name": "gpt-4o-mini", - "created_at": 1743092069, - "result_counts": { - "total": 0, - "errored": 0, - "failed": 0, - "passed": 0 - }, - "per_model_usage": null, - "per_testing_criteria_results": null, - "data_source": { - "type": "completions", - "source": { - "type": "file_content", - "content": [ - { - "item": { - "input": "Tech Company Launches Advanced Artificial Intelligence Platform", - "ground_truth": "Technology" - } - } - ] - }, - "input_messages": { - "type": "template", - "template": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "{{item.input}}" - } - } - ] - }, - "model": "gpt-4o-mini", - "sampling_params": { - "seed": 42, - "temperature": 1.0, - "top_p": 1.0, - "max_completions_tokens": 2048 - } - }, - "error": null, - "metadata": {} - } request: curl: | - curl https://api.openai.com/v1/evals/eval_67e579652b548190aaa83ada4b125f47/runs \ - -X POST \ + curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ - -d '{"name":"gpt-4o-mini","data_source":{"type":"completions","input_messages":{"type":"template","template":[{"role":"developer","content":"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"} , {"role":"user","content":"{{item.input}}"}]} ,"sampling_params":{"temperature":1,"max_completions_tokens":2048,"top_p":1,"seed":42},"model":"gpt-4o-mini","source":{"type":"file_content","content":[{"item":{"input":"Tech Company Launches Advanced Artificial Intelligence Platform","ground_truth":"Technology"}}]}}' - python: |- + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "metadata": { + "user_id": "user_abc123" + } + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - run = client.evals.runs.create( - eval_id="eval_id", - data_source={ - "source": { - "content": [{ - "item": { - "foo": "bar" - } - }], - "type": "file_content", - }, - "type": "jsonl", - }, + run = client.beta.threads.runs.update( + thread_id="thread_abc123", + run_id="run_abc123", + metadata={"user_id": "user_abc123"}, ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.evals.runs.create('eval_id', { - data_source: { source: { content: [{ item: { foo: 'bar' } }], type: 'file_content' }, type: 'jsonl' }, - }); - - console.log(run.id); - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.JsonValue; - import com.openai.models.evals.runs.CreateEvalJsonlRunDataSource; - import com.openai.models.evals.runs.RunCreateParams; - import com.openai.models.evals.runs.RunCreateResponse; - import java.util.List; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunCreateParams params = RunCreateParams.builder() - .evalId("eval_id") - .dataSource(CreateEvalJsonlRunDataSource.builder() - .fileContentSource(List.of(CreateEvalJsonlRunDataSource.Source.FileContent.Content.builder() - .item(CreateEvalJsonlRunDataSource.Source.FileContent.Content.Item.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build()) - .build())) - .build()) - .build(); - RunCreateResponse run = client.evals().runs().create(params); - } - } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") + print(run) + node.js: | + import OpenAI from "openai"; - run = openai.evals.runs.create( - "eval_id", - data_source: {source: {content: [{item: {foo: "bar"}}], type: :file_content}, type: :jsonl} - ) + const openai = new OpenAI(); - puts(run) - description: > - Kicks off a new run for a given evaluation, specifying the data source, and what model configuration - to use to test. The datasource will be validated against the schema specified in the config of the - evaluation. - /evals/{eval_id}/runs/{run_id}: - get: - operationId: getEvalRun - tags: - - Evals - summary: Get an eval run - parameters: - - name: eval_id - in: path - required: true - schema: - type: string - description: The ID of the evaluation to retrieve runs for. - - name: run_id - in: path - required: true - schema: - type: string - description: The ID of the run to retrieve. - responses: - '200': - description: The evaluation run - content: - application/json: - schema: - $ref: '#/components/schemas/EvalRun' - x-oaiMeta: - name: Get an eval run - group: evals - returns: >- - The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the - specified ID. - path: get - examples: + async function main() { + const run = await openai.beta.threads.runs.update( + "thread_abc123", + "run_abc123", + { + metadata: { + user_id: "user_abc123", + }, + } + ); + + console.log(run); + } + + main(); response: | { - "object": "eval.run", - "id": "evalrun_67abd54d60ec8190832b46859da808f7", - "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7", - "status": "queued", - "model": "gpt-4o-mini", - "name": "gpt-4o-mini", - "created_at": 1743092069, - "result_counts": { - "total": 0, - "errored": 0, - "failed": 0, - "passed": 0 - }, - "per_model_usage": null, - "per_testing_criteria_results": null, - "data_source": { - "type": "completions", - "source": { - "type": "file_content", - "content": [ - { - "item": { - "input": "Tech Company Launches Advanced Artificial Intelligence Platform", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "International Summit Addresses Climate Change Strategies", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Major Retailer Reports Record-Breaking Holiday Sales", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "National Team Qualifies for World Championship Finals", - "ground_truth": "Sports" - } - }, - { - "item": { - "input": "Stock Markets Rally After Positive Economic Data Released", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "Global Manufacturer Announces Merger with Competitor", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "Breakthrough in Renewable Energy Technology Unveiled", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "World Leaders Sign Historic Climate Agreement", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Professional Athlete Sets New Record in Championship Event", - "ground_truth": "Sports" - } - }, - { - "item": { - "input": "Financial Institutions Adapt to New Regulatory Requirements", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "Tech Conference Showcases Advances in Artificial Intelligence", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "Global Markets Respond to Oil Price Fluctuations", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "International Cooperation Strengthened Through New Treaty", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Sports League Announces Revised Schedule for Upcoming Season", - "ground_truth": "Sports" - } - } - ] - }, - "input_messages": { - "type": "template", - "template": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "{{item.input}}" - } - } + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699075072, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699075072, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699075073, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "tool_resources": { + "code_interpreter": { + "file_ids": [ + "file-abc123", + "file-abc456" ] - }, - "model": "gpt-4o-mini", - "sampling_params": { - "seed": 42, - "temperature": 1.0, - "top_p": 1.0, - "max_completions_tokens": 2048 } }, - "error": null, - "metadata": {} + "metadata": { + "user_id": "user_abc123" + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true } - request: - curl: > - curl - https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7 - \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.evals.runs.retrieve( - run_id="run_id", - eval_id="eval_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.evals.runs.retrieve('run_id', { eval_id: 'eval_id' }); - - console.log(run.id); - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.runs.RunRetrieveParams; - import com.openai.models.evals.runs.RunRetrieveResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunRetrieveParams params = RunRetrieveParams.builder() - .evalId("eval_id") - .runId("run_id") - .build(); - RunRetrieveResponse run = client.evals().runs().retrieve(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.evals.runs.retrieve("run_id", eval_id: "eval_id") - puts(run) - description: | - Get an evaluation run by ID. + /threads/{thread_id}/runs/{run_id}/submit_tool_outputs: post: - operationId: cancelEvalRun + operationId: submitToolOuputsToRun tags: - - Evals - summary: Cancel eval run + - Assistants + summary: | + When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. parameters: - - name: eval_id - in: path + - in: path + name: thread_id required: true schema: type: string - description: The ID of the evaluation whose run you want to cancel. - - name: run_id - in: path + description: The ID of the [thread](/docs/api-reference/threads) to which this run belongs. + - in: path + name: run_id required: true schema: type: string - description: The ID of the run to cancel. + description: The ID of the run that requires the tool output submission. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/SubmitToolOutputsRunRequest" responses: - '200': - description: The canceled eval run object + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/EvalRun' + $ref: "#/components/schemas/RunObject" x-oaiMeta: - name: Cancel eval run - group: evals - returns: >- - The updated [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object - reflecting that the run is canceled. - path: post + name: Submit tool outputs to run + group: threads + beta: true + returns: The modified [run](/docs/api-reference/runs/object) object matching the specified ID. examples: - response: | - { - "object": "eval.run", - "id": "evalrun_67abd54d60ec8190832b46859da808f7", - "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7", - "status": "canceled", - "model": "gpt-4o-mini", - "name": "gpt-4o-mini", - "created_at": 1743092069, - "result_counts": { - "total": 0, - "errored": 0, - "failed": 0, - "passed": 0 - }, - "per_model_usage": null, - "per_testing_criteria_results": null, - "data_source": { - "type": "completions", - "source": { - "type": "file_content", - "content": [ - { - "item": { - "input": "Tech Company Launches Advanced Artificial Intelligence Platform", - "ground_truth": "Technology" + - title: Default + request: + curl: | + curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "tool_outputs": [ + { + "tool_call_id": "call_001", + "output": "70 degrees and sunny." } - }, + ] + }' + python: | + from openai import OpenAI + client = OpenAI() + + run = client.beta.threads.runs.submit_tool_outputs( + thread_id="thread_123", + run_id="run_123", + tool_outputs=[ { - "item": { - "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", - "ground_truth": "Markets" - } - }, + "tool_call_id": "call_001", + "output": "70 degrees and sunny." + } + ] + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.submitToolOutputs( + "thread_123", + "run_123", { - "item": { - "input": "International Summit Addresses Climate Change Strategies", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Major Retailer Reports Record-Breaking Holiday Sales", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "National Team Qualifies for World Championship Finals", - "ground_truth": "Sports" - } - }, - { - "item": { - "input": "Stock Markets Rally After Positive Economic Data Released", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "Global Manufacturer Announces Merger with Competitor", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "Breakthrough in Renewable Energy Technology Unveiled", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "World Leaders Sign Historic Climate Agreement", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Professional Athlete Sets New Record in Championship Event", - "ground_truth": "Sports" - } - }, - { - "item": { - "input": "Financial Institutions Adapt to New Regulatory Requirements", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "Tech Conference Showcases Advances in Artificial Intelligence", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "Global Markets Respond to Oil Price Fluctuations", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "International Cooperation Strengthened Through New Treaty", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Sports League Announces Revised Schedule for Upcoming Season", - "ground_truth": "Sports" + tool_outputs: [ + { + tool_call_id: "call_001", + output: "70 degrees and sunny.", + }, + ], + } + ); + + console.log(run); + } + + main(); + response: | + { + "id": "run_123", + "object": "thread.run", + "created_at": 1699075592, + "assistant_id": "asst_123", + "thread_id": "thread_123", + "status": "queued", + "started_at": 1699075592, + "expires_at": 1699076192, + "cancelled_at": null, + "failed_at": null, + "completed_at": null, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] } } - ] + } + ], + "metadata": {}, + "usage": null, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null }, - "input_messages": { - "type": "template", - "template": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "tool_outputs": [ + { + "tool_call_id": "call_001", + "output": "70 degrees and sunny." } - }, + ], + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() + + stream = client.beta.threads.runs.submit_tool_outputs( + thread_id="thread_123", + run_id="run_123", + tool_outputs=[ { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "{{item.input}}" - } + "tool_call_id": "call_001", + "output": "70 degrees and sunny." } - ] - }, - "model": "gpt-4o-mini", - "sampling_params": { - "seed": 42, - "temperature": 1.0, - "top_p": 1.0, - "max_completions_tokens": 2048 + ], + stream=True + ) + + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.runs.submitToolOutputs( + "thread_123", + "run_123", + { + tool_outputs: [ + { + tool_call_id: "call_001", + output: "70 degrees and sunny.", + }, + ], + } + ); + + for await (const event of stream) { + console.log(event); + } } - }, - "error": null, - "metadata": {} - } - request: - curl: > - curl - https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/cancel - \ - -X POST \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- - from openai import OpenAI - client = OpenAI( - api_key="My API Key", - ) - response = client.evals.runs.cancel( - run_id="run_id", - eval_id="eval_id", - ) - print(response.id) - node.js: |- - import OpenAI from 'openai'; + main(); + response: | + event: thread.run.step.completed + data: {"id":"step_001","object":"thread.run.step","created_at":1710352449,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"completed","cancelled_at":null,"completed_at":1710352475,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[{"id":"call_iWr0kQ2EaYMaxNdl0v3KYkx7","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}","output":"70 degrees and sunny."}}]},"usage":{"prompt_tokens":291,"completion_tokens":24,"total_tokens":315}} + + event: thread.run.queued + data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - const client = new OpenAI({ - apiKey: 'My API Key', - }); + event: thread.run.in_progress + data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - const response = await client.evals.runs.cancel('run_id', { eval_id: 'eval_id' }); + event: thread.run.step.created + data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} - console.log(response.id); - java: |- - package com.openai.example; + event: thread.run.step.in_progress + data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.runs.RunCancelParams; - import com.openai.models.evals.runs.RunCancelResponse; + event: thread.message.created + data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - public final class Main { - private Main() {} + event: thread.message.in_progress + data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + event: thread.message.delta + data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"The","annotations":[]}}]}} - RunCancelParams params = RunCancelParams.builder() - .evalId("eval_id") - .runId("run_id") - .build(); - RunCancelResponse response = client.evals().runs().cancel(params); - } - } - ruby: |- - require "openai" + event: thread.message.delta + data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" current"}}]}} - openai = OpenAI::Client.new(api_key: "My API Key") + event: thread.message.delta + data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" weather"}}]}} - response = openai.evals.runs.cancel("run_id", eval_id: "eval_id") + ... - puts(response) - description: | - Cancel an ongoing evaluation run. - delete: - operationId: deleteEvalRun + event: thread.message.delta + data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" sunny"}}]}} + + event: thread.message.delta + data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"."}}]}} + + event: thread.message.completed + data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710352477,"role":"assistant","content":[{"type":"text","text":{"value":"The current weather in San Francisco, CA is 70 degrees Fahrenheit and sunny.","annotations":[]}}],"metadata":{}} + + event: thread.run.step.completed + data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710352477,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":{"prompt_tokens":329,"completion_tokens":18,"total_tokens":347}} + + event: thread.run.completed + data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + event: done + data: [DONE] + + /threads/{thread_id}/runs/{run_id}/cancel: + post: + operationId: cancelRun tags: - - Evals - summary: Delete eval run + - Assistants + summary: Cancels a run that is `in_progress`. parameters: - - name: eval_id - in: path + - in: path + name: thread_id required: true schema: type: string - description: The ID of the evaluation to delete the run from. - - name: run_id - in: path + description: The ID of the thread to which this run belongs. + - in: path + name: run_id required: true schema: type: string - description: The ID of the run to delete. + description: The ID of the run to cancel. responses: - '200': - description: Successfully deleted the eval run - content: - application/json: - schema: - type: object - properties: - object: - type: string - example: eval.run.deleted - deleted: - type: boolean - example: true - run_id: - type: string - example: evalrun_677469f564d48190807532a852da3afb - '404': - description: Run not found + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: "#/components/schemas/RunObject" x-oaiMeta: - name: Delete eval run - group: evals - returns: An object containing the status of the delete operation. - path: delete + name: Cancel a run + group: threads + beta: true + returns: The modified [run](/docs/api-reference/runs/object) object matching the specified ID. examples: - response: | - { - "object": "eval.run.deleted", - "deleted": true, - "run_id": "evalrun_abc456" - } request: curl: | - curl https://api.openai.com/v1/evals/eval_123abc/runs/evalrun_abc456 \ - -X DELETE \ + curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/cancel \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + -H "OpenAI-Beta: assistants=v2" \ + -X POST + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - run = client.evals.runs.delete( - run_id="run_id", - eval_id="eval_id", + run = client.beta.threads.runs.cancel( + thread_id="thread_abc123", + run_id="run_abc123" ) - print(run.run_id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - const run = await client.evals.runs.delete('run_id', { eval_id: 'eval_id' }); - - console.log(run.run_id); - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.runs.RunDeleteParams; - import com.openai.models.evals.runs.RunDeleteResponse; + print(run) + node.js: | + import OpenAI from "openai"; - public final class Main { - private Main() {} + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const run = await openai.beta.threads.runs.cancel( + "thread_abc123", + "run_abc123" + ); - RunDeleteParams params = RunDeleteParams.builder() - .evalId("eval_id") - .runId("run_id") - .build(); - RunDeleteResponse run = client.evals().runs().delete(params); - } + console.log(run); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - run = openai.evals.runs.delete("run_id", eval_id: "eval_id") - - puts(run) - description: | - Delete an eval run. - /evals/{eval_id}/runs/{run_id}/output_items: - get: - operationId: getEvalRunOutputItems - tags: - - Evals - summary: Get eval run output items - parameters: - - name: eval_id - in: path - required: true - schema: - type: string - description: The ID of the evaluation to retrieve runs for. - - name: run_id - in: path - required: true - schema: - type: string - description: The ID of the run to retrieve output items for. - - name: after - in: query - description: Identifier for the last output item from the previous pagination request. - required: false - schema: - type: string - - name: limit - in: query - description: Number of output items to retrieve. - required: false - schema: - type: integer - default: 20 - - name: status - in: query - description: | - Filter output items by status. Use `failed` to filter by failed output - items or `pass` to filter by passed output items. - required: false - schema: - type: string - enum: - - fail - - pass - - name: order - in: query - description: >- - Sort order for output items by timestamp. Use `asc` for ascending order or `desc` for descending - order. Defaults to `asc`. - required: false - schema: - type: string - enum: - - asc - - desc - default: asc - responses: - '200': - description: A list of output items for the evaluation run - content: - application/json: - schema: - $ref: '#/components/schemas/EvalRunOutputItemList' - x-oaiMeta: - name: Get eval run output items - group: evals - returns: >- - A list of - [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) - objects matching the specified ID. - path: get - examples: + main(); response: | { - "object": "list", - "data": [ + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699076126, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "cancelling", + "started_at": 1699076126, + "expires_at": 1699076726, + "cancelled_at": null, + "failed_at": null, + "completed_at": null, + "last_error": null, + "model": "gpt-4o", + "instructions": "You summarize books.", + "tools": [ { - "object": "eval.run.output_item", - "id": "outputitem_67e5796c28e081909917bf79f6e6214d", - "created_at": 1743092076, - "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", - "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "status": "pass", - "datasource_item_id": 5, - "datasource_item": { - "input": "Stock Markets Rally After Positive Economic Data Released", - "ground_truth": "Markets" - }, - "results": [ - { - "name": "String check-a2486074-d803-4445-b431-ad2262e85d47", - "sample": null, - "passed": true, - "score": 1.0 - } - ], - "sample": { - "input": [ - { - "role": "developer", - "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n", - "tool_call_id": null, - "tool_calls": null, - "function_call": null - }, - { - "role": "user", - "content": "Stock Markets Rally After Positive Economic Data Released", - "tool_call_id": null, - "tool_calls": null, - "function_call": null - } - ], - "output": [ - { - "role": "assistant", - "content": "Markets", - "tool_call_id": null, - "tool_calls": null, - "function_call": null - } - ], - "finish_reason": "stop", - "model": "gpt-4o-mini-2024-07-18", - "usage": { - "total_tokens": 325, - "completion_tokens": 2, - "prompt_tokens": 323, - "cached_tokens": 0 - }, - "error": null, - "temperature": 1.0, - "max_completion_tokens": 2048, - "top_p": 1.0, - "seed": 42 - } + "type": "file_search" } ], - "first_id": "outputitem_67e5796c28e081909917bf79f6e6214d", - "last_id": "outputitem_67e5796c28e081909917bf79f6e6214d", - "has_more": true + "tool_resources": { + "file_search": { + "vector_store_ids": ["vs_123"] + } + }, + "metadata": {}, + "usage": null, + "temperature": 1.0, + "top_p": 1.0, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true } - request: - curl: > - curl - https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs/erun_67abd54d60ec8190832b46859da808f7/output_items - \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.evals.runs.output_items.list( - run_id="run_id", - eval_id="eval_id", - ) - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const outputItemListResponse of client.evals.runs.outputItems.list('run_id', { - eval_id: 'eval_id', - })) { - console.log(outputItemListResponse.id); - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.runs.outputitems.OutputItemListPage; - import com.openai.models.evals.runs.outputitems.OutputItemListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - OutputItemListParams params = OutputItemListParams.builder() - .evalId("eval_id") - .runId("run_id") - .build(); - OutputItemListPage page = client.evals().runs().outputItems().list(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.evals.runs.output_items.list("run_id", eval_id: "eval_id") - - puts(page) - description: | - Get a list of output items for an evaluation run. - /evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}: + /threads/{thread_id}/runs/{run_id}/steps: get: - operationId: getEvalRunOutputItem + operationId: listRunSteps tags: - - Evals - summary: Get an output item of an eval run + - Assistants + summary: Returns a list of run steps belonging to a run. parameters: - - name: eval_id + - name: thread_id in: path required: true schema: type: string - description: The ID of the evaluation to retrieve runs for. + description: The ID of the thread the run and run steps belong to. - name: run_id in: path required: true schema: type: string - description: The ID of the run to retrieve. - - name: output_item_id - in: path - required: true + description: The ID of the run the run steps belong to. + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description schema: type: string - description: The ID of the output item to retrieve. responses: - '200': - description: The evaluation run output item + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/EvalRunOutputItem' + $ref: "#/components/schemas/ListRunStepsResponse" x-oaiMeta: - name: Get an output item of an eval run - group: evals - returns: >- - The [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) - object matching the specified ID. - path: get + name: List run steps + group: threads + beta: true + returns: A list of [run step](/docs/api-reference/runs/step-object) objects. examples: - response: | - { - "object": "eval.run.output_item", - "id": "outputitem_67e5796c28e081909917bf79f6e6214d", - "created_at": 1743092076, - "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", - "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "status": "pass", - "datasource_item_id": 5, - "datasource_item": { - "input": "Stock Markets Rally After Positive Economic Data Released", - "ground_truth": "Markets" - }, - "results": [ - { - "name": "String check-a2486074-d803-4445-b431-ad2262e85d47", - "sample": null, - "passed": true, - "score": 1.0 - } - ], - "sample": { - "input": [ - { - "role": "developer", - "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n", - "tool_call_id": null, - "tool_calls": null, - "function_call": null - }, - { - "role": "user", - "content": "Stock Markets Rally After Positive Economic Data Released", - "tool_call_id": null, - "tool_calls": null, - "function_call": null - } - ], - "output": [ - { - "role": "assistant", - "content": "Markets", - "tool_call_id": null, - "tool_calls": null, - "function_call": null - } - ], - "finish_reason": "stop", - "model": "gpt-4o-mini-2024-07-18", - "usage": { - "total_tokens": 325, - "completion_tokens": 2, - "prompt_tokens": 323, - "cached_tokens": 0 - }, - "error": null, - "temperature": 1.0, - "max_completion_tokens": 2048, - "top_p": 1.0, - "seed": 42 - } - } request: - curl: > - curl - https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/output_items/outputitem_67abd55eb6548190bb580745d5644a33 - \ + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" - python: |- + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - output_item = client.evals.runs.output_items.retrieve( - output_item_id="output_item_id", - eval_id="eval_id", - run_id="run_id", + run_steps = client.beta.threads.runs.steps.list( + thread_id="thread_abc123", + run_id="run_abc123" ) - print(output_item.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const outputItem = await client.evals.runs.outputItems.retrieve('output_item_id', { - eval_id: 'eval_id', - run_id: 'run_id', - }); - - console.log(outputItem.id); - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.evals.runs.outputitems.OutputItemRetrieveParams; - import com.openai.models.evals.runs.outputitems.OutputItemRetrieveResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - OutputItemRetrieveParams params = OutputItemRetrieveParams.builder() - .evalId("eval_id") - .runId("run_id") - .outputItemId("output_item_id") - .build(); - OutputItemRetrieveResponse outputItem = client.evals().runs().outputItems().retrieve(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") + print(run_steps) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - output_item = openai.evals.runs.output_items.retrieve("output_item_id", eval_id: "eval_id", - run_id: "run_id") + async function main() { + const runStep = await openai.beta.threads.runs.steps.list( + "thread_abc123", + "run_abc123" + ); + console.log(runStep); + } + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "step_abc123", + "object": "thread.run.step", + "created_at": 1699063291, + "run_id": "run_abc123", + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "type": "message_creation", + "status": "completed", + "cancelled_at": null, + "completed_at": 1699063291, + "expired_at": null, + "failed_at": null, + "last_error": null, + "step_details": { + "type": "message_creation", + "message_creation": { + "message_id": "msg_abc123" + } + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + } + } + ], + "first_id": "step_abc123", + "last_id": "step_abc456", + "has_more": false + } - puts(output_item) - description: | - Get an evaluation run output item by ID. - /files: + /threads/{thread_id}/runs/{run_id}/steps/{step_id}: get: - operationId: listFiles + operationId: getRunStep tags: - - Files - summary: List files + - Assistants + summary: Retrieves a run step. parameters: - - in: query - name: purpose - required: false + - in: path + name: thread_id + required: true schema: type: string - description: Only return files with the given purpose. - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 10,000, and the - default is 10,000. - required: false - schema: - type: integer - default: 10000 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. + description: The ID of the thread to which the run and run step belongs. + - in: path + name: run_id + required: true schema: type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. + description: The ID of the run to which the run step belongs. + - in: path + name: step_id + required: true schema: type: string + description: The ID of the run step to retrieve. responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ListFilesResponse' + $ref: "#/components/schemas/RunStepObject" x-oaiMeta: - name: List files - group: files - returns: A list of [File](https://platform.openai.com/docs/api-reference/files/object) objects. + name: Retrieve run step + group: threads + beta: true + returns: The [run step](/docs/api-reference/runs/step-object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "id": "file-abc123", - "object": "file", - "bytes": 175, - "created_at": 1613677385, - "expires_at": 1677614202, - "filename": "salesOverview.pdf", - "purpose": "assistants", - }, - { - "id": "file-abc456", - "object": "file", - "bytes": 140, - "created_at": 1613779121, - "expires_at": 1677614202, - "filename": "puppy.jsonl", - "purpose": "fine-tune", - } - ], - "first_id": "file-abc123", - "last_id": "file-abc456", - "has_more": false - } request: curl: | - curl https://api.openai.com/v1/files \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI + curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | + from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", + run_step = client.beta.threads.runs.steps.retrieve( + thread_id="thread_abc123", + run_id="run_abc123", + step_id="step_abc123" ) - page = client.files.list() - page = page.data[0] - print(page) - node.js: |- - import OpenAI from 'openai'; - const client = new OpenAI({ - apiKey: 'My API Key', - }); + print(run_step) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - // Automatically fetches more pages as needed. - for await (const fileObject of client.files.list()) { - console.log(fileObject); + async function main() { + const runStep = await openai.beta.threads.runs.steps.retrieve( + "thread_abc123", + "run_abc123", + "step_abc123" + ); + console.log(runStep); } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Files.List(context.TODO(), openai.FileListParams{ - - }) - if err != nil { - panic(err.Error()) + main(); + response: &run_step_object_example | + { + "id": "step_abc123", + "object": "thread.run.step", + "created_at": 1699063291, + "run_id": "run_abc123", + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "type": "message_creation", + "status": "completed", + "cancelled_at": null, + "completed_at": 1699063291, + "expired_at": null, + "failed_at": null, + "last_error": null, + "step_details": { + "type": "message_creation", + "message_creation": { + "message_id": "msg_abc123" } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.files.FileListPage; - import com.openai.models.files.FileListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileListPage page = client.files().list(); - } + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.files.list + } - puts(page) - description: Returns a list of files. - post: - operationId: createFile + /vector_stores: + get: + operationId: listVectorStores tags: - - Files - summary: Upload file - requestBody: - required: true - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/CreateFileRequest' + - Vector Stores + summary: Returns a list of vector stores. + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/OpenAIFile' + $ref: "#/components/schemas/ListVectorStoresResponse" x-oaiMeta: - name: Upload file - group: files - returns: The uploaded [File](https://platform.openai.com/docs/api-reference/files/object) object. + name: List vector stores + group: vector_stores + beta: true + returns: A list of [vector store](/docs/api-reference/vector-stores/object) objects. examples: - response: | - { - "id": "file-abc123", - "object": "file", - "bytes": 120000, - "created_at": 1677610602, - "expires_at": 1677614202, - "filename": "mydata.jsonl", - "purpose": "fine-tune", - } request: curl: | - curl https://api.openai.com/v1/files \ + curl https://api.openai.com/v1/vector_stores \ -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F purpose="fine-tune" \ - -F file="@mydata.jsonl" - -F expires_after[anchor]="created_at" - -F expires_after[seconds]=2592000 - python: |- + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - file_object = client.files.create( - file=b"raw file contents", - purpose="assistants", - ) - print(file_object.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fileObject = await client.files.create({ - file: fs.createReadStream('fine-tune.jsonl'), - purpose: 'assistants', - }); - - console.log(fileObject.id); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + vector_stores = client.beta.vector_stores.list() + print(vector_stores) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fileObject, err := client.Files.New(context.TODO(), openai.FileNewParams{ - File: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - Purpose: openai.FilePurposeAssistants, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fileObject.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.files.FileCreateParams; - import com.openai.models.files.FileObject; - import com.openai.models.files.FilePurpose; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileCreateParams params = FileCreateParams.builder() - .file(ByteArrayInputStream("some content".getBytes())) - .purpose(FilePurpose.ASSISTANTS) - .build(); - FileObject fileObject = client.files().create(params); - } + async function main() { + const vectorStores = await openai.beta.vectorStores.list(); + console.log(vectorStores); } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - file_object = openai.files.create(file: Pathname(__FILE__), purpose: :assistants) - - puts(file_object) - description: | - Upload a file that can be used across various endpoints. Individual files - can be up to 512 MB, and the size of all files uploaded by one organization - can be up to 1 TB. - - - The Assistants API supports files up to 2 million tokens and of specific - file types. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for - details. - - The Fine-tuning API only supports `.jsonl` files. The input also has - certain required formats for fine-tuning - [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or - [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models. - - The Batch API only supports `.jsonl` files up to 200 MB in size. The input - also has a specific required - [format](https://platform.openai.com/docs/api-reference/batch/request-input). - - Please [contact us](https://help.openai.com/) if you need to increase these - storage limits. - /files/{file_id}: - delete: - operationId: deleteFile + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + }, + { + "id": "vs_abc456", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ v2", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + } + ], + "first_id": "vs_abc123", + "last_id": "vs_abc456", + "has_more": false + } + post: + operationId: createVectorStore tags: - - Files - summary: Delete file - parameters: - - in: path - name: file_id - required: true - schema: - type: string - description: The ID of the file to use for this request. + - Vector Stores + summary: Create a vector store. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateVectorStoreRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/DeleteFileResponse' + $ref: "#/components/schemas/VectorStoreObject" x-oaiMeta: - name: Delete file - group: files - returns: Deletion status. + name: Create vector store + group: vector_stores + beta: true + returns: A [vector store](/docs/api-reference/vector-stores/object) object. examples: - response: | - { - "id": "file-abc123", - "object": "file", - "deleted": true - } request: curl: | - curl https://api.openai.com/v1/files/file-abc123 \ - -X DELETE \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- + curl https://api.openai.com/v1/vector_stores \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + -d '{ + "name": "Support FAQ" + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - file_deleted = client.files.delete( - "file_id", - ) - print(file_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fileDeleted = await client.files.delete('file_id'); - - console.log(fileDeleted.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + vector_store = client.beta.vector_stores.create( + name="Support FAQ" ) + print(vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fileDeleted, err := client.Files.Delete(context.TODO(), "file_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fileDeleted.ID) + async function main() { + const vectorStore = await openai.beta.vectorStores.create({ + name: "Support FAQ" + }); + console.log(vectorStore); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.files.FileDeleteParams; - import com.openai.models.files.FileDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - FileDeleted fileDeleted = client.files().delete("file_id"); - } + main(); + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - file_deleted = openai.files.delete("file_id") + } - puts(file_deleted) - description: Delete a file and remove it from all vector stores. + /vector_stores/{vector_store_id}: get: - operationId: retrieveFile + operationId: getVectorStore tags: - - Files - summary: Retrieve file + - Vector Stores + summary: Retrieves a vector store. parameters: - in: path - name: file_id + name: vector_store_id required: true schema: type: string - description: The ID of the file to use for this request. + description: The ID of the vector store to retrieve. responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/OpenAIFile' + $ref: "#/components/schemas/VectorStoreObject" x-oaiMeta: - name: Retrieve file - group: files - returns: >- - The [File](https://platform.openai.com/docs/api-reference/files/object) object matching the - specified ID. + name: Retrieve vector store + group: vector_stores + beta: true + returns: The [vector store](/docs/api-reference/vector-stores/object) object matching the specified ID. examples: - response: | - { - "id": "file-abc123", - "object": "file", - "bytes": 120000, - "created_at": 1677610602, - "expires_at": 1677614202, - "filename": "mydata.jsonl", - "purpose": "fine-tune", - } request: curl: | - curl https://api.openai.com/v1/files/file-abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- + curl https://api.openai.com/v1/vector_stores/vs_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - file_object = client.files.retrieve( - "file_id", - ) - print(file_object.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fileObject = await client.files.retrieve('file_id'); - - console.log(fileObject.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + vector_store = client.beta.vector_stores.retrieve( + vector_store_id="vs_abc123" ) + print(vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fileObject, err := client.Files.Get(context.TODO(), "file_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fileObject.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.files.FileObject; - import com.openai.models.files.FileRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileObject fileObject = client.files().retrieve("file_id"); - } + async function main() { + const vectorStore = await openai.beta.vectorStores.retrieve( + "vs_abc123" + ); + console.log(vectorStore); } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - file_object = openai.files.retrieve("file_id") - - puts(file_object) - description: Returns information about a specific file. - /files/{file_id}/content: - get: - operationId: downloadFile + main(); + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776 + } + post: + operationId: modifyVectorStore tags: - - Files - summary: Retrieve file content + - Vector Stores + summary: Modifies a vector store. parameters: - in: path - name: file_id + name: vector_store_id required: true schema: type: string - description: The ID of the file to use for this request. - responses: - '200': - description: OK - content: - application/json: - schema: - type: string - x-oaiMeta: - name: Retrieve file content - group: files - returns: The file content. - examples: - response: '' - request: - curl: | - curl https://api.openai.com/v1/files/file-abc123/content \ - -H "Authorization: Bearer $OPENAI_API_KEY" > file.jsonl - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.files.content( - "file_id", - ) - print(response) - content = response.read() - print(content) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.files.content('file_id'); - - console.log(response); - - const content = await response.blob(); - console.log(content); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Files.Content(context.TODO(), "file_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.http.HttpResponse; - import com.openai.models.files.FileContentParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - HttpResponse response = client.files().content("file_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.files.content("file_id") - - puts(response) - description: Returns the contents of the specified file. - /fine_tuning/alpha/graders/run: - post: - operationId: runGrader - tags: - - Fine-tuning - summary: Run grader + description: The ID of the vector store to modify. requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/RunGraderRequest' + $ref: "#/components/schemas/UpdateVectorStoreRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/RunGraderResponse' + $ref: "#/components/schemas/VectorStoreObject" x-oaiMeta: - name: Run grader + name: Modify vector store + group: vector_stores beta: true - group: graders - returns: The results from the grader run. + returns: The modified [vector store](/docs/api-reference/vector-stores/object) object. examples: - response: | - { - "reward": 1.0, - "metadata": { - "name": "Example score model grader", - "type": "score_model", - "errors": { - "formula_parse_error": false, - "sample_parse_error": false, - "truncated_observation_error": false, - "unresponsive_reward_error": false, - "invalid_variable_error": false, - "other_error": false, - "python_grader_server_error": false, - "python_grader_server_error_type": null, - "python_grader_runtime_error": false, - "python_grader_runtime_error_details": null, - "model_grader_server_error": false, - "model_grader_refusal_error": false, - "model_grader_parse_error": false, - "model_grader_server_error_details": null - }, - "execution_time": 4.365238428115845, - "scores": {}, - "token_usage": { - "prompt_tokens": 190, - "total_tokens": 324, - "completion_tokens": 134, - "cached_tokens": 0 - }, - "sampled_model_name": "gpt-4o-2024-08-06" - }, - "sub_rewards": {}, - "model_grader_token_usage_per_model": { - "gpt-4o-2024-08-06": { - "prompt_tokens": 190, - "total_tokens": 324, - "completion_tokens": 134, - "cached_tokens": 0 - } - } - } request: - curl: > - curl -X POST https://api.openai.com/v1/fine_tuning/alpha/graders/run \ - -H "Content-Type: application/json" \ + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" -d '{ - "grader": { - "type": "score_model", - "name": "Example score model grader", - "input": [ - { - "role": "user", - "content": "Score how close the reference answer is to the model - answer. Score 1.0 if they are the same and 0.0 if they are different. Return just a floating - point score\n\nReference answer: {{item.reference_answer}}\n\nModel answer: - {{sample.output_text}}" - } - ], - "model": "gpt-4o-2024-08-06", - "sampling_params": { - "temperature": 1, - "top_p": 1, - "seed": 42 - } - }, - "item": { - "reference_answer": "fuzzy wuzzy was a bear" - }, - "model_sample": "fuzzy wuzzy was a bear" + "name": "Support FAQ" }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.fineTuning.alpha.graders.run({ - grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' }, - model_sample: 'model_sample', - }); - - console.log(response.metadata); - python: |- + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - response = client.fine_tuning.alpha.graders.run( - grader={ - "input": "input", - "name": "name", - "operation": "eq", - "reference": "reference", - "type": "string_check", - }, - model_sample="model_sample", - ) - print(response.metadata) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + vector_store = client.beta.vector_stores.update( + vector_store_id="vs_abc123", + name="Support FAQ" ) + print(vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{ - Grader: openai.FineTuningAlphaGraderRunParamsGraderUnion{ - OfStringCheck: &openai.StringCheckGraderParam{ - Input: "input", - Name: "name", - Operation: openai.StringCheckGraderOperationEq, - Reference: "reference", - }, - }, - ModelSample: "model_sample", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.Metadata) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.alpha.graders.GraderRunParams; - import com.openai.models.finetuning.alpha.graders.GraderRunResponse; - import com.openai.models.graders.gradermodels.StringCheckGrader; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - GraderRunParams params = GraderRunParams.builder() - .grader(StringCheckGrader.builder() - .input("input") - .name("name") - .operation(StringCheckGrader.Operation.EQ) - .reference("reference") - .build()) - .modelSample("model_sample") - .build(); - GraderRunResponse response = client.fineTuning().alpha().graders().run(params); + async function main() { + const vectorStore = await openai.beta.vectorStores.update( + "vs_abc123", + { + name: "Support FAQ" } + ); + console.log(vectorStore); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - response = openai.fine_tuning.alpha.graders.run( - grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check}, - model_sample: "model_sample" - ) + main(); + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + } - puts(response) - description: | - Run a grader. - /fine_tuning/alpha/graders/validate: - post: - operationId: validateGrader + delete: + operationId: deleteVectorStore tags: - - Fine-tuning - summary: Validate grader - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ValidateGraderRequest' + - Vector Stores + summary: Delete a vector store. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store to delete. responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ValidateGraderResponse' + $ref: "#/components/schemas/DeleteVectorStoreResponse" x-oaiMeta: - name: Validate grader + name: Delete vector store + group: vector_stores beta: true - group: graders - returns: The validated grader object. + returns: Deletion status examples: - response: | - { - "grader": { - "type": "string_check", - "name": "Example string check grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq" - } - } request: curl: | - curl https://api.openai.com/v1/fine_tuning/alpha/graders/validate \ + curl https://api.openai.com/v1/vector_stores/vs_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ - -d '{ - "grader": { - "type": "string_check", - "name": "Example string check grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq" - } - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.fineTuning.alpha.graders.validate({ - grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' }, - }); - - console.log(response.grader); - python: |- + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - response = client.fine_tuning.alpha.graders.validate( - grader={ - "input": "input", - "name": "name", - "operation": "eq", - "reference": "reference", - "type": "string_check", - }, - ) - print(response.grader) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + deleted_vector_store = client.beta.vector_stores.delete( + vector_store_id="vs_abc123" ) + print(deleted_vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.FineTuning.Alpha.Graders.Validate(context.TODO(), openai.FineTuningAlphaGraderValidateParams{ - Grader: openai.FineTuningAlphaGraderValidateParamsGraderUnion{ - OfStringCheckGrader: &openai.StringCheckGraderParam{ - Input: "input", - Name: "name", - Operation: openai.StringCheckGraderOperationEq, - Reference: "reference", - }, - }, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.Grader) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.alpha.graders.GraderValidateParams; - import com.openai.models.finetuning.alpha.graders.GraderValidateResponse; - import com.openai.models.graders.gradermodels.StringCheckGrader; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - GraderValidateParams params = GraderValidateParams.builder() - .grader(StringCheckGrader.builder() - .input("input") - .name("name") - .operation(StringCheckGrader.Operation.EQ) - .reference("reference") - .build()) - .build(); - GraderValidateResponse response = client.fineTuning().alpha().graders().validate(params); - } + async function main() { + const deletedVectorStore = await openai.beta.vectorStores.del( + "vs_abc123" + ); + console.log(deletedVectorStore); } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.fine_tuning.alpha.graders.validate( - grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check} - ) + main(); + response: | + { + id: "vs_abc123", + object: "vector_store.deleted", + deleted: true + } - puts(response) - description: | - Validate a grader. - /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions: + /vector_stores/{vector_store_id}/files: get: - operationId: listFineTuningCheckpointPermissions + operationId: listVectorStoreFiles tags: - - Fine-tuning - summary: List checkpoint permissions + - Vector Stores + summary: Returns a list of vector store files. parameters: - - in: path - name: fine_tuned_model_checkpoint + - name: vector_store_id + in: path + description: The ID of the vector store that the files belong to. required: true schema: type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuned model checkpoint to get permissions for. - - name: project_id + - name: limit in: query - description: The ID of the project to get permissions for. + description: *pagination_limit_param_description required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description schema: type: string + default: desc + enum: ["asc", "desc"] - name: after in: query - description: Identifier for the last permission ID from the previous pagination request. - required: false + description: *pagination_after_param_description schema: type: string - - name: limit + - name: before in: query - description: Number of permissions to retrieve. - required: false + description: *pagination_before_param_description schema: - type: integer - default: 10 - - name: order + type: string + - name: filter in: query - description: The order in which to retrieve permissions. - required: false + description: "Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`." schema: type: string - enum: - - ascending - - descending - default: descending + enum: ["in_progress", "completed", "failed", "cancelled"] responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ListFineTuningCheckpointPermissionResponse' + $ref: "#/components/schemas/ListVectorStoreFilesResponse" x-oaiMeta: - name: List checkpoint permissions - group: fine-tuning - returns: >- - A list of fine-tuned model checkpoint [permission - objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a - fine-tuned model checkpoint. + name: List vector store files + group: vector_stores + beta: true + returns: A list of [vector store file](/docs/api-reference/vector-stores-files/file-object) objects. examples: - response: | - { - "object": "list", - "data": [ - { - "object": "checkpoint.permission", - "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "created_at": 1721764867, - "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" - }, - { - "object": "checkpoint.permission", - "id": "cp_enQCFmOTGj3syEpYVhBRLTSy", - "created_at": 1721764800, - "project_id": "proj_iqGMw1llN8IrBb6SvvY5A1oF" - }, - ], - "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "last_id": "cp_enQCFmOTGj3syEpYVhBRLTSy", - "has_more": false - } request: - curl: > - curl - https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions - \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const permission = await - client.fineTuning.checkpoints.permissions.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - - - console.log(permission.first_id); - python: |- + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - permission = client.fine_tuning.checkpoints.permissions.retrieve( - fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - print(permission.first_id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + vector_store_files = client.beta.vector_stores.files.list( + vector_store_id="vs_abc123" ) + print(vector_store_files) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - permission, err := client.FineTuning.Checkpoints.Permissions.Get( - context.TODO(), - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - openai.FineTuningCheckpointPermissionGetParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", permission.FirstID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveParams; - import com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - PermissionRetrieveResponse permission = client.fineTuning().checkpoints().permissions().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } + async function main() { + const vectorStoreFiles = await openai.beta.vectorStores.files.list( + "vs_abc123" + ); + console.log(vectorStoreFiles); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - permission = openai.fine_tuning.checkpoints.permissions.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F") - puts(permission) - description: | - **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - - Organization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint. + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + }, + { + "id": "file-abc456", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + } + ], + "first_id": "file-abc123", + "last_id": "file-abc456", + "has_more": false + } post: - operationId: createFineTuningCheckpointPermission + operationId: createVectorStoreFile tags: - - Fine-tuning - summary: Create checkpoint permissions + - Vector Stores + summary: Create a vector store file by attaching a [File](/docs/api-reference/files) to a [vector store](/docs/api-reference/vector-stores/object). parameters: - in: path - name: fine_tuned_model_checkpoint + name: vector_store_id required: true schema: type: string - example: ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd + example: vs_abc123 description: | - The ID of the fine-tuned model checkpoint to create a permission for. + The ID of the vector store for which to create a File. requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/CreateFineTuningCheckpointPermissionRequest' + $ref: "#/components/schemas/CreateVectorStoreFileRequest" responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/ListFineTuningCheckpointPermissionResponse' + $ref: "#/components/schemas/VectorStoreFileObject" x-oaiMeta: - name: Create checkpoint permissions - group: fine-tuning - returns: >- - A list of fine-tuned model checkpoint [permission - objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a - fine-tuned model checkpoint. + name: Create vector store file + group: vector_stores + beta: true + returns: A [vector store file](/docs/api-reference/vector-stores-files/file-object) object. examples: - response: | - { - "object": "list", - "data": [ - { - "object": "checkpoint.permission", - "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "created_at": 1721764867, - "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" - } - ], - "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "last_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "has_more": false - } request: - curl: > - curl - https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions - \ - -H "Authorization: Bearer $OPENAI_API_KEY" - -d '{"project_ids": ["proj_abGMw1llN8IrBb6SvvY5A1iH"]}' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( - 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - { project_ids: ['string'] }, - )) { - console.log(permissionCreateResponse.id); - } - python: |- + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "file_id": "file-abc123" + }' + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.fine_tuning.checkpoints.permissions.create( - fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", - project_ids=["string"], - ) - page = page.data[0] - print(page.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + vector_store_file = client.beta.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file-abc123" ) + print(vector_store_file) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.FineTuning.Checkpoints.Permissions.New( - context.TODO(), - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", - openai.FineTuningCheckpointPermissionNewParams{ - ProjectIDs: []string{"string"}, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.checkpoints.permissions.PermissionCreatePage; - import com.openai.models.finetuning.checkpoints.permissions.PermissionCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - PermissionCreateParams params = PermissionCreateParams.builder() - .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd") - .addProjectId("string") - .build(); - PermissionCreatePage page = client.fineTuning().checkpoints().permissions().create(params); + async function main() { + const myVectorStoreFile = await openai.beta.vectorStores.files.create( + "vs_abc123", + { + file_id: "file-abc123" } + ); + console.log(myVectorStoreFile); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - page = openai.fine_tuning.checkpoints.permissions.create( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", - project_ids: ["string"] - ) - - puts(page) - description: | - **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + main(); + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "usage_bytes": 1234, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null + } - This enables organization owners to share fine-tuned models with other projects in their organization. - /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}: - delete: - operationId: deleteFineTuningCheckpointPermission + /vector_stores/{vector_store_id}/files/{file_id}: + get: + operationId: getVectorStoreFile tags: - - Fine-tuning - summary: Delete checkpoint permission + - Vector Stores + summary: Retrieves a vector store file. parameters: - in: path - name: fine_tuned_model_checkpoint + name: vector_store_id required: true schema: type: string - example: ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd - description: | - The ID of the fine-tuned model checkpoint to delete a permission for. + example: vs_abc123 + description: The ID of the vector store that the file belongs to. - in: path - name: permission_id + name: file_id required: true schema: type: string - example: cp_zc4Q7MP6XxulcVzj4MZdwsAB - description: | - The ID of the fine-tuned model checkpoint permission to delete. + example: file-abc123 + description: The ID of the file being retrieved. responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/DeleteFineTuningCheckpointPermissionResponse' + $ref: "#/components/schemas/VectorStoreFileObject" x-oaiMeta: - name: Delete checkpoint permission - group: fine-tuning - returns: >- - The deletion status of the fine-tuned model checkpoint [permission - object](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object). + name: Retrieve vector store file + group: vector_stores + beta: true + returns: The [vector store file](/docs/api-reference/vector-stores-files/file-object) object. examples: - response: | - { - "object": "checkpoint.permission", - "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "deleted": true - } request: - curl: > - curl - https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions/cp_zc4Q7MP6XxulcVzj4MZdwsAB - \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const permission = await - client.fineTuning.checkpoints.permissions.delete('cp_zc4Q7MP6XxulcVzj4MZdwsAB', { - fine_tuned_model_checkpoint: 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - }); - - - console.log(permission.id); - python: |- + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - permission = client.fine_tuning.checkpoints.permissions.delete( - permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", - fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", - ) - print(permission.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" + vector_store_file = client.beta.vector_stores.files.retrieve( + vector_store_id="vs_abc123", + file_id="file-abc123" ) + print(vector_store_file) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - permission, err := client.FineTuning.Checkpoints.Permissions.Delete( - context.TODO(), - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", - "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", permission.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteParams; - import com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - PermissionDeleteParams params = PermissionDeleteParams.builder() - .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd") - .permissionId("cp_zc4Q7MP6XxulcVzj4MZdwsAB") - .build(); - PermissionDeleteResponse permission = client.fineTuning().checkpoints().permissions().delete(params); - } + async function main() { + const vectorStoreFile = await openai.beta.vectorStores.files.retrieve( + "vs_abc123", + "file-abc123" + ); + console.log(vectorStoreFile); } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - permission = openai.fine_tuning.checkpoints.permissions.delete( - "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - fine_tuned_model_checkpoint: "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd" - ) - - puts(permission) - description: | - **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - Organization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint. - /fine_tuning/jobs: - post: - operationId: createFineTuningJob + main(); + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null + } + delete: + operationId: deleteVectorStoreFile tags: - - Fine-tuning - summary: Create fine-tuning job - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateFineTuningJobRequest' + - Vector Stores + summary: Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](/docs/api-reference/files/delete) endpoint. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store that the file belongs to. + - in: path + name: file_id + required: true + schema: + type: string + description: The ID of the file to delete. responses: - '200': + "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/FineTuningJob' + $ref: "#/components/schemas/DeleteVectorStoreFileResponse" x-oaiMeta: - name: Create fine-tuning job - group: fine-tuning - returns: A [fine-tuning.job](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. + name: Delete vector store file + group: vector_stores + beta: true + returns: Deletion status examples: - - title: Default - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo", - "model": "gpt-4o-mini" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.create( - model="gpt-4o-mini", - training_file="file-abc123", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - }); - - console.log(fineTuningJob.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - JobCreateParams params = JobCreateParams.builder() - .model(JobCreateParams.Model.BABBAGE_002) - .trainingFile("file-abc123") - .build(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: | + from openai import OpenAI + client = OpenAI() + deleted_vector_store_file = client.beta.vector_stores.files.delete( + vector_store_id="vs_abc123", + file_id="file-abc123" + ) + print(deleted_vector_store_file) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: - "file-abc123") + async function main() { + const deletedVectorStoreFile = await openai.beta.vectorStores.files.del( + "vs_abc123", + "file-abc123" + ); + console.log(deletedVectorStoreFile); + } + main(); + response: | + { + id: "file-abc123", + object: "vector_store.file.deleted", + deleted: true + } - puts(fine_tuning_job) - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "queued", - "validation_file": null, - "training_file": "file-abc123", - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": "auto", - } - } - }, - "metadata": null - } - - title: Epochs - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs \ - -H "Content-Type: application/json" \ + /vector_stores/{vector_store_id}/file_batches: + post: + operationId: createVectorStoreFileBatch + tags: + - Vector Stores + summary: Create a vector store file batch. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: | + The ID of the vector store for which to create a File Batch. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateVectorStoreFileBatchRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/VectorStoreFileBatchObject" + x-oaiMeta: + name: Create vector store file batch + group: vector_stores + beta: true + returns: A [vector store file batch](/docs/api-reference/vector-stores-file-batches/batch-object) object. + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/file_batches \ -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json \ + -H "OpenAI-Beta: assistants=v2" \ -d '{ - "training_file": "file-abc123", - "model": "gpt-4o-mini", - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "n_epochs": 2 - } - } - } + "file_ids": ["file-abc123", "file-abc456"] }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.create( - model="gpt-4o-mini", - training_file="file-abc123", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - }); - - console.log(fineTuningJob.id); - go: | - package main - - import ( - "context" - "fmt" + python: | + from openai import OpenAI + client = OpenAI() - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + vector_store_file_batch = client.beta.vector_stores.file_batches.create( + vector_store_id="vs_abc123", + file_ids=["file-abc123", "file-abc456"] + ) + print(vector_store_file_batch) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", - }) - if err != nil { - panic(err.Error()) + async function main() { + const myVectorStoreFileBatch = await openai.beta.vectorStores.fileBatches.create( + "vs_abc123", + { + file_ids: ["file-abc123", "file-abc456"] } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCreateParams; + ); + console.log(myVectorStoreFileBatch); + } - public final class Main { - private Main() {} + main(); + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "in_progress", + "file_counts": { + "in_progress": 1, + "completed": 1, + "failed": 0, + "cancelled": 0, + "total": 0, + } + } - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + /vector_stores/{vector_store_id}/file_batches/{batch_id}: + get: + operationId: getVectorStoreFileBatch + tags: + - Vector Stores + summary: Retrieves a vector store file batch. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: The ID of the vector store that the file batch belongs to. + - in: path + name: batch_id + required: true + schema: + type: string + example: vsfb_abc123 + description: The ID of the file batch being retrieved. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/VectorStoreFileBatchObject" + x-oaiMeta: + name: Retrieve vector store file batch + group: vector_stores + beta: true + returns: The [vector store file batch](/docs/api-reference/vector-stores-file-batches/batch-object) object. + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | + from openai import OpenAI + client = OpenAI() - JobCreateParams params = JobCreateParams.builder() - .model(JobCreateParams.Model.BABBAGE_002) - .trainingFile("file-abc123") - .build(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); - } - } - ruby: >- - require "openai" + vector_store_file_batch = client.beta.vector_stores.file_batches.retrieve( + vector_store_id="vs_abc123", + batch_id="vsfb_abc123" + ) + print(vector_store_file_batch) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + async function main() { + const vectorStoreFileBatch = await openai.beta.vectorStores.fileBatches.retrieve( + "vs_abc123", + "vsfb_abc123" + ); + console.log(vectorStoreFileBatch); + } - openai = OpenAI::Client.new(api_key: "My API Key") + main(); + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "in_progress", + "file_counts": { + "in_progress": 1, + "completed": 1, + "failed": 0, + "cancelled": 0, + "total": 0, + } + } + /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel: + post: + operationId: cancelVectorStoreFileBatch + tags: + - Vector Stores + summary: Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store that the file batch belongs to. + - in: path + name: batch_id + required: true + schema: + type: string + description: The ID of the file batch to cancel. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/VectorStoreFileBatchObject" + x-oaiMeta: + name: Cancel vector store file batch + group: vector_stores + beta: true + returns: The modified vector store file batch object. + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/cancel \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -X POST + python: | + from openai import OpenAI + client = OpenAI() - fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: - "file-abc123") + deleted_vector_store_file_batch = client.beta.vector_stores.file_batches.cancel( + vector_store_id="vs_abc123", + file_batch_id="vsfb_abc123" + ) + print(deleted_vector_store_file_batch) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + async function main() { + const deletedVectorStoreFileBatch = await openai.vector_stores.fileBatches.cancel( + "vs_abc123", + "vsfb_abc123" + ); + console.log(deletedVectorStoreFileBatch); + } - puts(fine_tuning_job) - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "queued", - "validation_file": null, - "training_file": "file-abc123", - "hyperparameters": { - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": 2 - }, - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": 2 - } - } - }, - "metadata": null, - "error": { - "code": null, - "message": null, - "param": null - }, - "finished_at": null, - "seed": 683058546, - "trained_tokens": null, - "estimated_finish": null, - "integrations": [], - "user_provided_suffix": null, - "usage_metrics": null, - "shared_with_openai": false + main(); + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "cancelling", + "file_counts": { + "in_progress": 12, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 15, } - - title: DPO - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "training_file": "file-abc123", - "validation_file": "file-abc123", - "model": "gpt-4o-mini", - "method": { - "type": "dpo", - "dpo": { - "hyperparameters": { - "beta": 0.1 - } - } - } - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - }); - - console.log(fineTuningJob.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.create( - model="gpt-4o-mini", - training_file="file-abc123", - ) - print(fine_tuning_job.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; + } - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCreateParams; + /vector_stores/{vector_store_id}/file_batches/{batch_id}/files: + get: + operationId: listFilesInVectorStoreBatch + tags: + - Vector Stores + summary: Returns a list of vector store files in a batch. + parameters: + - name: vector_store_id + in: path + description: The ID of the vector store that the files belong to. + required: true + schema: + type: string + - name: batch_id + in: path + description: The ID of the file batch that the files belong to. + required: true + schema: + type: string + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string + - name: filter + in: query + description: "Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`." + schema: + type: string + enum: ["in_progress", "completed", "failed", "cancelled"] + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListVectorStoreFilesResponse" + x-oaiMeta: + name: List vector store files in a batch + group: vector_stores + beta: true + returns: A list of [vector store file](/docs/api-reference/vector-stores-files/file-object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: | + from openai import OpenAI + client = OpenAI() - public final class Main { - private Main() {} + vector_store_files = client.beta.vector_stores.file_batches.list_files( + vector_store_id="vs_abc123", + batch_id="vsfb_abc123" + ) + print(vector_store_files) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + async function main() { + const vectorStoreFiles = await openai.beta.vectorStores.fileBatches.listFiles( + "vs_abc123", + "vsfb_abc123" + ); + console.log(vectorStoreFiles); + } - JobCreateParams params = JobCreateParams.builder() - .model(JobCreateParams.Model.BABBAGE_002) - .trainingFile("file-abc123") - .build(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); - } + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + }, + { + "id": "file-abc456", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - + ], + "first_id": "file-abc123", + "last_id": "file-abc456", + "has_more": false + } - fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: - "file-abc123") + /batches: + post: + summary: Creates and executes a batch from an uploaded file of requests + operationId: createBatch + tags: + - Batch + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - input_file_id + - endpoint + - completion_window + properties: + input_file_id: + type: string + description: | + The ID of an uploaded file that contains requests for the new batch. + See [upload file](/docs/api-reference/files/create) for how to upload a file. - puts(fine_tuning_job) + Your input file must be formatted as a [JSONL file](/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 100 MB in size. + endpoint: + type: string + enum: + [ + "/v1/chat/completions", + "/v1/embeddings", + "/v1/completions", + ] + description: The endpoint to be used for all requests in the batch. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch. + completion_window: + type: string + enum: ["24h"] + description: The time frame within which the batch should be processed. Currently only `24h` is supported. + metadata: + type: object + additionalProperties: + type: string + description: Optional custom metadata for the batch. + nullable: true + responses: + "200": + description: Batch created successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/Batch" + x-oaiMeta: + name: Create batch + group: batch + returns: The created [Batch](/docs/api-reference/batch/object) object. + examples: + request: + curl: | + curl https://api.openai.com/v1/batches \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "input_file_id": "file-abc123", + "endpoint": "/v1/chat/completions", + "completion_window": "24h" + }' python: | from openai import OpenAI - from openai.types.fine_tuning import DpoMethod, DpoHyperparameters - client = OpenAI() - client.fine_tuning.jobs.create( - training_file="file-abc", - validation_file="file-123", - model="gpt-4o-mini", - method={ - "type": "dpo", - "dpo": DpoMethod( - hyperparameters=DpoHyperparameters(beta=0.1) - ) - } + client.batches.create( + input_file_id="file-abc123", + endpoint="/v1/chat/completions", + completion_window="24h" ) - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc", - "model": "gpt-4o-mini", - "created_at": 1746130590, - "fine_tuned_model": null, - "organization_id": "org-abc", - "result_files": [], - "status": "queued", - "validation_file": "file-123", - "training_file": "file-abc", - "method": { - "type": "dpo", - "dpo": { - "hyperparameters": { - "beta": 0.1, - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": "auto" - } - } - }, - "metadata": null, - "error": { - "code": null, - "message": null, - "param": null - }, - "finished_at": null, - "hyperparameters": null, - "seed": 1036326793, - "estimated_finish": null, - "integrations": [], - "user_provided_suffix": null, - "usage_metrics": null, - "shared_with_openai": false - } - - title: Reinforcement - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "training_file": "file-abc", - "validation_file": "file-123", - "model": "o4-mini", - "method": { - "type": "reinforcement", - "reinforcement": { - "grader": { - "type": "string_check", - "name": "Example string check grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq" - }, - "hyperparameters": { - "reasoning_effort": "medium" - } - } - } - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.create( - model="gpt-4o-mini", - training_file="file-abc123", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; + node: | + import OpenAI from "openai"; - const client = new OpenAI({ - apiKey: 'My API Key', - }); + const openai = new OpenAI(); - const fineTuningJob = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', + async function main() { + const batch = await openai.batches.create({ + input_file_id: "file-abc123", + endpoint: "/v1/chat/completions", + completion_window: "24h" }); - console.log(fineTuningJob.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - JobCreateParams params = JobCreateParams.builder() - .model(JobCreateParams.Model.BABBAGE_002) - .trainingFile("file-abc123") - .build(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: - "file-abc123") - + console.log(batch); + } - puts(fine_tuning_job) - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "o4-mini", - "created_at": 1721764800, - "finished_at": null, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "validating_files", - "validation_file": "file-123", - "training_file": "file-abc", - "trained_tokens": null, - "error": {}, - "user_provided_suffix": null, - "seed": 950189191, - "estimated_finish": null, - "integrations": [], - "method": { - "type": "reinforcement", - "reinforcement": { - "hyperparameters": { - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": "auto", - "eval_interval": "auto", - "eval_samples": "auto", - "compute_multiplier": "auto", - "reasoning_effort": "medium" - }, - "grader": { - "type": "string_check", - "name": "Example string check grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq" - }, - "response_format": null - } - }, - "metadata": null, - "usage_metrics": null, - "shared_with_openai": false - } - - - title: Validation file - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "training_file": "file-abc123", - "validation_file": "file-abc123", - "model": "gpt-4o-mini" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.create( - model="gpt-4o-mini", - training_file="file-abc123", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - }); - - console.log(fineTuningJob.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - JobCreateParams params = JobCreateParams.builder() - .model(JobCreateParams.Model.BABBAGE_002) - .trainingFile("file-abc123") - .build(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: - "file-abc123") - - - puts(fine_tuning_job) - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "queued", - "validation_file": "file-abc123", - "training_file": "file-abc123", - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": "auto", - } - } - }, - "metadata": null - } - - title: W&B Integration - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "training_file": "file-abc123", - "validation_file": "file-abc123", - "model": "gpt-4o-mini", - "integrations": [ - { - "type": "wandb", - "wandb": { - "project": "my-wandb-project", - "name": "ft-run-display-name" - "tags": [ - "first-experiment", "v2" - ] - } - } - ] - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.create({ - model: 'gpt-4o-mini', - training_file: 'file-abc123', - }); - - console.log(fineTuningJob.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.create( - model="gpt-4o-mini", - training_file="file-abc123", - ) - print(fine_tuning_job.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - JobCreateParams params = JobCreateParams.builder() - .model(JobCreateParams.Model.BABBAGE_002) - .trainingFile("file-abc123") - .build(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: - "file-abc123") - - - puts(fine_tuning_job) - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "queued", - "validation_file": "file-abc123", - "training_file": "file-abc123", - "integrations": [ - { - "type": "wandb", - "wandb": { - "project": "my-wandb-project", - "entity": None, - "run_id": "ftjob-abc123" - } - } - ], - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "batch_size": "auto", - "learning_rate_multiplier": "auto", - "n_epochs": "auto", - } - } - }, - "metadata": null + main(); + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/chat/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "validating", + "output_file_id": null, + "error_file_id": null, + "created_at": 1711471533, + "in_progress_at": null, + "expires_at": null, + "finalizing_at": null, + "completed_at": null, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 0, + "completed": 0, + "failed": 0 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", } - description: > - Creates a fine-tuning job which begins the process of creating a new model from a given dataset. - - - Response includes details of the enqueued job including job status and the name of the fine-tuned - models once complete. - - - [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + } get: - operationId: listPaginatedFineTuningJobs + operationId: listBatches tags: - - Fine-tuning - summary: List fine-tuning jobs + - Batch + summary: List your organization's batches. parameters: - - name: after - in: query - description: Identifier for the last job from the previous pagination request. + - in: query + name: after required: false schema: type: string + description: *pagination_after_param_description - name: limit in: query - description: Number of fine-tuning jobs to retrieve. + description: *pagination_limit_param_description required: false schema: type: integer default: 20 - - in: query - name: metadata - required: false - schema: - type: object - nullable: true - additionalProperties: - type: string - style: deepObject - explode: true - description: > - Optional metadata filter. To filter, use the syntax `metadata[k]=v`. Alternatively, set - `metadata=null` to indicate no metadata. responses: - '200': - description: OK + "200": + description: Batch listed successfully. content: application/json: schema: - $ref: '#/components/schemas/ListPaginatedFineTuningJobsResponse' + $ref: "#/components/schemas/ListBatchesResponse" x-oaiMeta: - name: List fine-tuning jobs - group: fine-tuning - returns: >- - A list of paginated [fine-tuning - job](https://platform.openai.com/docs/api-reference/fine-tuning/object) objects. + name: List batch + group: batch + returns: A list of paginated [Batch](/docs/api-reference/batch/object) objects. examples: - response: | - { - "object": "list", - "data": [ - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "queued", - "validation_file": null, - "training_file": "file-abc123", - "metadata": { - "key": "value" - } - }, - { ... }, - { ... } - ], "has_more": true - } request: curl: | - curl https://api.openai.com/v1/fine_tuning/jobs?limit=2&metadata[key]=value \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- + curl https://api.openai.com/v1/batches?limit=2 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - page = client.fine_tuning.jobs.list() - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const fineTuningJob of client.fineTuning.jobs.list()) { - console.log(fineTuningJob.id); - } - go: | - package main - - import ( - "context" - "fmt" + client.batches.list() + node: | + import OpenAI from "openai"; - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + const openai = new OpenAI(); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.FineTuning.Jobs.List(context.TODO(), openai.FineTuningJobListParams{ + async function main() { + const list = await openai.batches.list(); - }) - if err != nil { - panic(err.Error()) + for await (const batch of list) { + console.log(batch); } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.JobListPage; - import com.openai.models.finetuning.jobs.JobListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - JobListPage page = client.fineTuning().jobs().list(); - } } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - page = openai.fine_tuning.jobs.list - - puts(page) - description: | - List your organization's fine-tuning jobs - /fine_tuning/jobs/{fine_tuning_job_id}: - get: - operationId: retrieveFineTuningJob - tags: - - Fine-tuning - summary: Retrieve fine-tuning job - parameters: - - in: path - name: fine_tuning_job_id - required: true + main(); + response: | + { + "object": "list", + "data": [ + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/chat/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "completed", + "output_file_id": "file-cvaTdG", + "error_file_id": "file-HOWS94", + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": 1711493133, + "completed_at": 1711493163, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 95, + "failed": 5 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly job", + } + }, + { ... }, + ], + "first_id": "batch_abc123", + "last_id": "batch_abc456", + "has_more": true + } + + /batches/{batch_id}: + get: + operationId: retrieveBatch + tags: + - Batch + summary: Retrieves a batch. + parameters: + - in: path + name: batch_id + required: true schema: type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuning job. + description: The ID of the batch to retrieve. responses: - '200': - description: OK + "200": + description: Batch retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/FineTuningJob' + $ref: "#/components/schemas/Batch" x-oaiMeta: - name: Retrieve fine-tuning job - group: fine-tuning - returns: >- - The [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object with the - given ID. + name: Retrieve batch + group: batch + returns: The [Batch](/docs/api-reference/batch/object) object matching the specified ID. examples: - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "davinci-002", - "created_at": 1692661014, - "finished_at": 1692661190, - "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", - "organization_id": "org-123", - "result_files": [ - "file-abc123" - ], - "status": "succeeded", - "validation_file": null, - "training_file": "file-abc123", - "hyperparameters": { - "n_epochs": 4, - "batch_size": 1, - "learning_rate_multiplier": 1.0 - }, - "trained_tokens": 5768, - "integrations": [], - "seed": 0, - "estimated_finish": 0, - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "n_epochs": 4, - "batch_size": 1, - "learning_rate_multiplier": 1.0 - } - } - } - } request: curl: | - curl https://api.openai.com/v1/fine_tuning/jobs/ft-AF1WoRqd3aJAHsqc9NY7iL8F \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- + curl https://api.openai.com/v1/batches/batch_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.retrieve( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - - console.log(fineTuningJob.id); - go: | - package main + client.batches.retrieve("batch_abc123") + node: | + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const batch = await openai.batches.retrieve("batch_abc123"); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.Get(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) + console.log(batch); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } + main(); + response: &batch_object | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "completed", + "output_file_id": "file-cvaTdG", + "error_file_id": "file-HOWS94", + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": 1711493133, + "completed_at": 1711493163, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 95, + "failed": 5 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - fine_tuning_job = openai.fine_tuning.jobs.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F") - - puts(fine_tuning_job) - description: | - Get info about a fine-tuning job. + } - [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) - /fine_tuning/jobs/{fine_tuning_job_id}/cancel: + /batches/{batch_id}/cancel: post: - operationId: cancelFineTuningJob + operationId: cancelBatch tags: - - Fine-tuning - summary: Cancel fine-tuning + - Batch + summary: Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file. parameters: - in: path - name: fine_tuning_job_id + name: batch_id required: true schema: type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuning job to cancel. + description: The ID of the batch to cancel. responses: - '200': - description: OK + "200": + description: Batch is cancelling. Returns the cancelling batch's details. content: application/json: schema: - $ref: '#/components/schemas/FineTuningJob' + $ref: "#/components/schemas/Batch" x-oaiMeta: - name: Cancel fine-tuning - group: fine-tuning - returns: >- - The cancelled [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) - object. + name: Cancel batch + group: batch + returns: The [Batch](/docs/api-reference/batch/object) object matching the specified ID. examples: - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "cancelled", - "validation_file": "file-abc123", - "training_file": "file-abc123" - } request: curl: | - curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/cancel \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- + curl https://api.openai.com/v1/batches/batch_abc123/cancel \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -X POST + python: | from openai import OpenAI + client = OpenAI() - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.cancel( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - - console.log(fineTuningJob.id); - go: | - package main + client.batches.cancel("batch_abc123") + node: | + import OpenAI from "openai"; - import ( - "context" - "fmt" + const openai = new OpenAI(); - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) + async function main() { + const batch = await openai.batches.cancel("batch_abc123"); - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.Cancel(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) + console.log(batch); } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobCancelParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - FineTuningJob fineTuningJob = client.fineTuning().jobs().cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } + main(); + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/chat/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "cancelling", + "output_file_id": null, + "error_file_id": null, + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": null, + "completed_at": null, + "failed_at": null, + "expired_at": null, + "cancelling_at": 1711475133, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 23, + "failed": 1 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - fine_tuning_job = openai.fine_tuning.jobs.cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + } - puts(fine_tuning_job) - description: | - Immediately cancel a fine-tune job. - /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints: + # Organization + # Audit Logs List + /organization/audit_logs: get: - operationId: listFineTuningJobCheckpoints + summary: List user actions and configuration changes within this organization. + operationId: list-audit-logs tags: - - Fine-tuning - summary: List fine-tuning checkpoints + - Audit Logs parameters: - - in: path - name: fine_tuning_job_id - required: true - schema: - type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuning job to get checkpoints for. - - name: after + - name: effective_at in: query - description: Identifier for the last checkpoint ID from the previous pagination request. + description: Return only events whose `effective_at` (Unix seconds) is in this range. required: false schema: - type: string + type: object + properties: + gt: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is greater than this value. + gte: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value. + lt: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is less than this value. + lte: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is less than or equal to this value. + - name: project_ids[] + in: query + description: Return only events for these projects. + required: false + schema: + type: array + items: + type: string + - name: event_types[] + in: query + description: Return only events with a `type` in one of these values. For example, `project.created`. For all options, see the documentation for the [audit log object](/docs/api-reference/audit-logs/object). + required: false + schema: + type: array + items: + $ref: "#/components/schemas/AuditLogEventType" + - name: actor_ids[] + in: query + description: Return only events performed by these actors. Can be a user ID, a service account ID, or an api key tracking ID. + required: false + schema: + type: array + items: + type: string + - name: actor_emails[] + in: query + description: Return only events performed by users with these emails. + required: false + schema: + type: array + items: + type: string + - name: resource_ids[] + in: query + description: Return only events performed on these targets. For example, a project ID updated. + required: false + schema: + type: array + items: + type: string - name: limit in: query - description: Number of checkpoints to retrieve. + description: *pagination_limit_param_description required: false schema: type: integer - default: 10 + default: 20 + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string responses: - '200': - description: OK + "200": + description: Audit logs listed successfully. content: application/json: schema: - $ref: '#/components/schemas/ListFineTuningJobCheckpointsResponse' + $ref: "#/components/schemas/ListAuditLogsResponse" x-oaiMeta: - name: List fine-tuning checkpoints - group: fine-tuning - returns: >- - A list of fine-tuning [checkpoint - objects](https://platform.openai.com/docs/api-reference/fine-tuning/checkpoint-object) for a - fine-tuning job. + name: List audit logs + group: audit-logs + returns: A list of paginated [Audit Log](/docs/api-reference/audit-logs/object) objects. examples: + request: + curl: | + curl https://api.openai.com/v1/organization/audit_logs \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ response: | { - "object": "list", - "data": [ - { - "object": "fine_tuning.job.checkpoint", - "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", - "created_at": 1721764867, - "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000", - "metrics": { - "full_valid_loss": 0.134, - "full_valid_mean_token_accuracy": 0.874 - }, - "fine_tuning_job_id": "ftjob-abc123", - "step_number": 2000 - }, - { - "object": "fine_tuning.job.checkpoint", - "id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", - "created_at": 1721764800, - "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000", - "metrics": { - "full_valid_loss": 0.167, - "full_valid_mean_token_accuracy": 0.781 - }, - "fine_tuning_job_id": "ftjob-abc123", - "step_number": 1000 - } - ], - "first_id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", - "last_id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", - "has_more": true + "object": "list", + "data": [ + { + "id": "audit_log-xxx_yyyymmdd", + "type": "project.archived", + "effective_at": 1722461446, + "actor": { + "type": "api_key", + "api_key": { + "type": "user", + "user": { + "id": "user-xxx", + "email": "user@example.com" + } + } + }, + "project.archived": { + "id": "proj_abc" + }, + }, + { + "id": "audit_log-yyy__20240101", + "type": "api_key.updated", + "effective_at": 1720804190, + "actor": { + "type": "session", + "session": { + "user": { + "id": "user-xxx", + "email": "user@example.com" + }, + "ip_address": "127.0.0.1", + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" + } + }, + "api_key.updated": { + "id": "key_xxxx", + "data": { + "scopes": ["resource_2.operation_2"] + } + }, + } + ], + "first_id": "audit_log-xxx__20240101", + "last_id": "audit_log_yyy__20240101", + "has_more": true } - request: - curl: | - curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( - 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - )) { - console.log(fineTuningJobCheckpoint.id); - } - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.fine_tuning.jobs.checkpoints.list( - fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - page = page.data[0] - print(page.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.FineTuning.Jobs.Checkpoints.List( - context.TODO(), - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - openai.FineTuningJobCheckpointListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.checkpoints.CheckpointListPage; - import com.openai.models.finetuning.jobs.checkpoints.CheckpointListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - CheckpointListPage page = client.fineTuning().jobs().checkpoints().list("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.fine_tuning.jobs.checkpoints.list("ft-AF1WoRqd3aJAHsqc9NY7iL8F") - - puts(page) - description: | - List checkpoints for a fine-tuning job. - /fine_tuning/jobs/{fine_tuning_job_id}/events: + /organization/invites: get: - operationId: listFineTuningEvents + summary: Returns a list of invites in the organization. + operationId: list-invites tags: - - Fine-tuning - summary: List fine-tuning events + - Invites parameters: - - in: path - name: fine_tuning_job_id - required: true - schema: - type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuning job to get events for. - - name: after - in: query - description: Identifier for the last event from the previous pagination request. - required: false - schema: - type: string - name: limit in: query - description: Number of events to retrieve. + description: *pagination_limit_param_description required: false schema: type: integer default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string responses: - '200': - description: OK + "200": + description: Invites listed successfully. content: application/json: schema: - $ref: '#/components/schemas/ListFineTuningJobEventsResponse' + $ref: "#/components/schemas/InviteListResponse" x-oaiMeta: - name: List fine-tuning events - group: fine-tuning - returns: A list of fine-tuning event objects. + name: List invites + group: administration + returns: A list of [Invite](/docs/api-reference/invite/object) objects. examples: - response: | - { - "object": "list", - "data": [ - { - "object": "fine_tuning.job.event", - "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm", - "created_at": 1721764800, - "level": "info", - "message": "Fine tuning job successfully completed", - "data": null, - "type": "message" - }, - { - "object": "fine_tuning.job.event", - "id": "ft-event-tyiGuB72evQncpH87xe505Sv", - "created_at": 1721764800, - "level": "info", - "message": "New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel", - "data": null, - "type": "message" - } - ], - "has_more": true - } request: curl: | - curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/events \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.fine_tuning.jobs.list_events( - fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - page = page.data[0] - print(page.id) - node.js: >- - import OpenAI from 'openai'; + curl https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } + ], + "first_id": "invite-abc", + "last_id": "invite-abc", + "has_more": false + } - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - // Automatically fetches more pages as needed. - - for await (const fineTuningJobEvent of - client.fineTuning.jobs.listEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F')) { - console.log(fineTuningJobEvent.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.FineTuning.Jobs.ListEvents( - context.TODO(), - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - openai.FineTuningJobListEventsParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.JobListEventsPage; - import com.openai.models.finetuning.jobs.JobListEventsParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - JobListEventsPage page = client.fineTuning().jobs().listEvents("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } + post: + summary: Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization. + operationId: inviteUser + tags: + - Invites + requestBody: + description: The invite request payload. + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/InviteRequest" + responses: + "200": + description: User invited successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/Invite" + x-oaiMeta: + name: Create invite + group: administration + returns: The created [Invite](/docs/api-reference/invite/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/invites \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "email": "user@example.com", + "role": "owner" + }' + response: + content: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": null } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.fine_tuning.jobs.list_events("ft-AF1WoRqd3aJAHsqc9NY7iL8F") - puts(page) - description: | - Get status updates for a fine-tuning job. - /fine_tuning/jobs/{fine_tuning_job_id}/pause: - post: - operationId: pauseFineTuningJob + /organization/invites/{invite_id}: + get: + summary: Retrieves an invite. + operationId: retrieve-invite tags: - - Fine-tuning - summary: Pause fine-tuning + - Invites parameters: - in: path - name: fine_tuning_job_id + name: invite_id required: true schema: type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuning job to pause. + description: The ID of the invite to retrieve. responses: - '200': - description: OK + "200": + description: Invite retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/FineTuningJob' + $ref: "#/components/schemas/Invite" x-oaiMeta: - name: Pause fine-tuning - group: fine-tuning - returns: The paused [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. + name: Retrieve invite + group: administration + returns: The [Invite](/docs/api-reference/invite/object) object matching the specified ID. examples: - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "paused", - "validation_file": "file-abc123", - "training_file": "file-abc123" - } request: curl: | - curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/pause \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.pause( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.pause('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - - console.log(fineTuningJob.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.Pause(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobPauseParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FineTuningJob fineTuningJob = client.fineTuning().jobs().pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } + curl https://api.openai.com/v1/organization/invites/invite-abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - fine_tuning_job = openai.fine_tuning.jobs.pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F") - - puts(fine_tuning_job) - description: | - Pause a fine-tune job. - /fine_tuning/jobs/{fine_tuning_job_id}/resume: - post: - operationId: resumeFineTuningJob + delete: + summary: Delete an invite. If the invite has already been accepted, it cannot be deleted. + operationId: delete-invite tags: - - Fine-tuning - summary: Resume fine-tuning + - Invites parameters: - in: path - name: fine_tuning_job_id + name: invite_id required: true schema: type: string - example: ft-AF1WoRqd3aJAHsqc9NY7iL8F - description: | - The ID of the fine-tuning job to resume. + description: The ID of the invite to delete. responses: - '200': - description: OK + "200": + description: Invite deleted successfully. content: application/json: schema: - $ref: '#/components/schemas/FineTuningJob' + $ref: "#/components/schemas/InviteDeleteResponse" x-oaiMeta: - name: Resume fine-tuning - group: fine-tuning - returns: The resumed [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object. + name: Delete invite + group: administration + returns: Confirmation that the invite has been deleted examples: - response: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "gpt-4o-mini-2024-07-18", - "created_at": 1721764800, - "fine_tuned_model": null, - "organization_id": "org-123", - "result_files": [], - "status": "queued", - "validation_file": "file-abc123", - "training_file": "file-abc123" - } request: curl: | - curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/resume \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - fine_tuning_job = client.fine_tuning.jobs.resume( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - print(fine_tuning_job.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const fineTuningJob = await client.fineTuning.jobs.resume('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); - - console.log(fineTuningJob.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - fineTuningJob, err := client.FineTuning.Jobs.Resume(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", fineTuningJob.ID) + curl -X DELETE https://api.openai.com/v1/organization/invites/invite-abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.invite.deleted", + "id": "invite-abc", + "deleted": true } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.finetuning.jobs.FineTuningJob; - import com.openai.models.finetuning.jobs.JobResumeParams; - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FineTuningJob fineTuningJob = client.fineTuning().jobs().resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); - } + /organization/users: + get: + summary: Lists all of the users in the organization. + operationId: list-users + tags: + - Users + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + responses: + "200": + description: Users listed successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/UserListResponse" + x-oaiMeta: + name: List users + group: administration + returns: A list of [User](/docs/api-reference/users/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/users?after=user_abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "first_id": "user-abc", + "last_id": "user-xyz", + "has_more": false } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - fine_tuning_job = openai.fine_tuning.jobs.resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + /organization/users/{user_id}: + get: + summary: Retrieves a user by their identifier. + operationId: retrieve-user + tags: + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + "200": + description: User retrieved successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/User" + x-oaiMeta: + name: Retrieve user + group: administration + returns: The [User](/docs/api-reference/users/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - puts(fine_tuning_job) - description: | - Resume a fine-tune job. - /images/edits: post: - operationId: createImageEdit + summary: Modifies a user's role in the organization. + operationId: modify-user tags: - - Images - summary: Create image edit + - Users requestBody: + description: The new user role to modify. This must be one of `owner` or `member`. required: true content: - multipart/form-data: + application/json: schema: - $ref: '#/components/schemas/CreateImageEditRequest' + $ref: "#/components/schemas/UserRoleUpdateRequest" responses: - '200': - description: OK + "200": + description: User role updated successfully. content: application/json: schema: - $ref: '#/components/schemas/ImagesResponse' - text/event-stream: - schema: - $ref: '#/components/schemas/ImageEditStreamEvent' + $ref: "#/components/schemas/User" x-oaiMeta: - name: Create image edit - group: images - returns: Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object. + name: Modify user + group: administration + returns: The updated [User](/docs/api-reference/users/object) object. examples: - - title: Edit image - request: - curl: | - curl -s -D >(grep -i x-request-id >&2) \ - -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \ - -X POST "https://api.openai.com/v1/images/edits" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F "model=gpt-image-1" \ - -F "image[]=@body-lotion.png" \ - -F "image[]=@bath-bomb.png" \ - -F "image[]=@incense-kit.png" \ - -F "image[]=@soap.png" \ - -F 'prompt=Create a lovely gift basket with these four items in it' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - images_response = client.images.edit( - image=b"raw file contents", - prompt="A cute baby sea otter wearing a beret", - ) - print(images_response) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const imagesResponse = await client.images.edit({ - image: fs.createReadStream('path/to/file'), - prompt: 'A cute baby sea otter wearing a beret', - }); - - console.log(imagesResponse); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{ - Image: openai.ImageEditParamsImageUnion{ - OfFile: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - }, - Prompt: "A cute baby sea otter wearing a beret", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", imagesResponse) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.images.ImageEditParams; - import com.openai.models.images.ImagesResponse; - import java.io.ByteArrayInputStream; - import java.io.InputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ImageEditParams params = ImageEditParams.builder() - .image(ByteArrayInputStream("some content".getBytes())) - .prompt("A cute baby sea otter wearing a beret") - .build(); - ImagesResponse imagesResponse = client.images().edit(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - images_response = openai.images.edit(image: Pathname(__FILE__), prompt: "A cute baby sea otter - wearing a beret") - - - puts(images_response) - - title: Streaming - request: - curl: | - curl -s -N -X POST "https://api.openai.com/v1/images/edits" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F "model=gpt-image-1" \ - -F "image[]=@body-lotion.png" \ - -F "image[]=@bath-bomb.png" \ - -F "image[]=@incense-kit.png" \ - -F "image[]=@soap.png" \ - -F 'prompt=Create a lovely gift basket with these four items in it' \ - -F "stream=true" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - images_response = client.images.edit( - image=b"raw file contents", - prompt="A cute baby sea otter wearing a beret", - ) - print(images_response) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const imagesResponse = await client.images.edit({ - image: fs.createReadStream('path/to/file'), - prompt: 'A cute baby sea otter wearing a beret', - }); - - console.log(imagesResponse); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{ - Image: openai.ImageEditParamsImageUnion{ - OfFile: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - }, - Prompt: "A cute baby sea otter wearing a beret", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", imagesResponse) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.images.ImageEditParams; - import com.openai.models.images.ImagesResponse; - import java.io.ByteArrayInputStream; - import java.io.InputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ImageEditParams params = ImageEditParams.builder() - .image(ByteArrayInputStream("some content".getBytes())) - .prompt("A cute baby sea otter wearing a beret") - .build(); - ImagesResponse imagesResponse = client.images().edit(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - images_response = openai.images.edit(image: Pathname(__FILE__), prompt: "A cute baby sea otter - wearing a beret") - - - puts(images_response) - response: > - event: image_edit.partial_image - - data: {"type":"image_edit.partial_image","b64_json":"...","partial_image_index":0} - - - event: image_edit.completed + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role": "owner" + }' + response: + content: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - data: - {"type":"image_edit.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}} - description: >- - Creates an edited or extended image given one or more source images and a prompt. This endpoint only - supports `gpt-image-1` and `dall-e-2`. - /images/generations: - post: - operationId: createImage + delete: + summary: Deletes a user from the organization. + operationId: delete-user tags: - - Images - summary: Create image - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateImageRequest' + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string responses: - '200': - description: OK + "200": + description: User deleted successfully. content: application/json: schema: - $ref: '#/components/schemas/ImagesResponse' - text/event-stream: + $ref: "#/components/schemas/UserDeleteResponse" + x-oaiMeta: + name: Delete user + group: administration + returns: Confirmation of the deleted user + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.user.deleted", + "id": "user_abc", + "deleted": true + } + /organization/projects: + get: + summary: Returns a list of projects. + operationId: list-projects + tags: + - Projects + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + - name: include_archived + in: query + schema: + type: boolean + default: false + description: If `true` returns all projects including those that have been `archived`. Archived projects are not included by default. + responses: + "200": + description: Projects listed successfully. + content: + application/json: schema: - $ref: '#/components/schemas/ImageGenStreamEvent' + $ref: "#/components/schemas/ProjectListResponse" x-oaiMeta: - name: Create image - group: images - returns: Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object. + name: List projects + group: administration + returns: A list of [Project](/docs/api-reference/projects/object) objects. examples: - - title: Generate image - request: - curl: | - curl https://api.openai.com/v1/images/generations \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-image-1", - "prompt": "A cute baby sea otter", - "n": 1, - "size": "1024x1024" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - images_response = client.images.generate( - prompt="A cute baby sea otter", - ) - print(images_response) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' }); - - console.log(imagesResponse); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{ - Prompt: "A cute baby sea otter", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", imagesResponse) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.images.ImageGenerateParams; - import com.openai.models.images.ImagesResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ImageGenerateParams params = ImageGenerateParams.builder() - .prompt("A cute baby sea otter") - .build(); - ImagesResponse imagesResponse = client.images().generate(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - images_response = openai.images.generate(prompt: "A cute baby sea otter") - - puts(images_response) - response: | + request: + curl: | + curl https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | { - "created": 1713833628, - "data": [ - { - "b64_json": "..." - } - ], - "usage": { - "total_tokens": 100, - "input_tokens": 50, - "output_tokens": 50, - "input_tokens_details": { - "text_tokens": 10, - "image_tokens": 40 - } - } + "object": "list", + "data": [ + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + ], + "first_id": "proj-abc", + "last_id": "proj-xyz", + "has_more": false } - - title: Streaming - request: - curl: | - curl https://api.openai.com/v1/images/generations \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-image-1", - "prompt": "A cute baby sea otter", - "n": 1, - "size": "1024x1024", - "stream": true - }' \ - --no-buffer - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - images_response = client.images.generate( - prompt="A cute baby sea otter", - ) - print(images_response) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' }); - - console.log(imagesResponse); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{ - Prompt: "A cute baby sea otter", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", imagesResponse) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.images.ImageGenerateParams; - import com.openai.models.images.ImagesResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ImageGenerateParams params = ImageGenerateParams.builder() - .prompt("A cute baby sea otter") - .build(); - ImagesResponse imagesResponse = client.images().generate(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - images_response = openai.images.generate(prompt: "A cute baby sea otter") - - puts(images_response) - response: > - event: image_generation.partial_image - - data: {"type":"image_generation.partial_image","b64_json":"...","partial_image_index":0} - - - event: image_generation.completed - - data: - {"type":"image_generation.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}} - description: | - Creates an image given a prompt. [Learn more](https://platform.openai.com/docs/guides/images). - /images/variations: post: - operationId: createImageVariation + summary: Create a new project in the organization. Projects can be created and archived, but cannot be deleted. + operationId: create-project tags: - - Images - summary: Create image variation + - Projects requestBody: + description: The project create request payload. required: true content: - multipart/form-data: + application/json: schema: - $ref: '#/components/schemas/CreateImageVariationRequest' + $ref: "#/components/schemas/ProjectCreateRequest" responses: - '200': - description: OK + "200": + description: Project created successfully. content: application/json: schema: - $ref: '#/components/schemas/ImagesResponse' + $ref: "#/components/schemas/Project" x-oaiMeta: - name: Create image variation - group: images - returns: Returns a list of [image](https://platform.openai.com/docs/api-reference/images/object) objects. + name: Create project + group: administration + returns: The created [Project](/docs/api-reference/projects/object) object. examples: - response: | - { - "created": 1589478378, - "data": [ - { - "url": "https://..." - }, - { - "url": "https://..." - } - ] - } request: curl: | - curl https://api.openai.com/v1/images/variations \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F image="@otter.png" \ - -F n=2 \ - -F size="1024x1024" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - images_response = client.images.create_variation( - image=b"raw file contents", - ) - print(images_response.created) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const imagesResponse = await client.images.createVariation({ image: - fs.createReadStream('otter.png') }); - - - console.log(imagesResponse.created); - csharp: | - using System; - - using OpenAI.Images; - - ImageClient client = new( - model: "dall-e-2", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - GeneratedImage image = client.GenerateImageVariation(imageFilePath: "otter.png"); - - Console.WriteLine(image.ImageUri); - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - imagesResponse, err := client.Images.NewVariation(context.TODO(), openai.ImageNewVariationParams{ - Image: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", imagesResponse.Created) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.images.ImageCreateVariationParams; - import com.openai.models.images.ImagesResponse; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ImageCreateVariationParams params = ImageCreateVariationParams.builder() - .image(ByteArrayInputStream("some content".getBytes())) - .build(); - ImagesResponse imagesResponse = client.images().createVariation(params); - } + curl -X POST https://api.openai.com/v1/organization/projects \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Project ABC" + }' + response: + content: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project ABC", + "created_at": 1711471533, + "archived_at": null, + "status": "active" } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - images_response = openai.images.create_variation(image: Pathname(__FILE__)) - - puts(images_response) - description: Creates a variation of a given image. This endpoint only supports `dall-e-2`. - /models: + /organization/projects/{project_id}: get: - operationId: listModels + summary: Retrieves a project. + operationId: retrieve-project tags: - - Models - summary: List models + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string responses: - '200': - description: OK + "200": + description: Project retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/ListModelsResponse' + $ref: "#/components/schemas/Project" x-oaiMeta: - name: List models - group: models - returns: A list of [model](https://platform.openai.com/docs/api-reference/models/object) objects. + name: Retrieve project + group: administration + description: Retrieve a project. + returns: The [Project](/docs/api-reference/projects/object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "id": "model-id-0", - "object": "model", - "created": 1686935002, - "owned_by": "organization-owner" - }, - { - "id": "model-id-1", - "object": "model", - "created": 1686935002, - "owned_by": "organization-owner", - }, - { - "id": "model-id-2", - "object": "model", - "created": 1686935002, - "owned_by": "openai" - }, - ], - "object": "list" - } request: curl: | - curl https://api.openai.com/v1/models \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.models.list() - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const model of client.models.list()) { - console.log(model.id); - } - csharp: | - using System; - - using OpenAI.Models; - - OpenAIModelClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - foreach (var model in client.GetModels().Value) + curl https://api.openai.com/v1/organization/projects/proj_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | { - Console.WriteLine(model.Id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Models.List(context.TODO()) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.models.ModelListPage; - import com.openai.models.models.ModelListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ModelListPage page = client.models().list(); - } + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - page = openai.models.list + post: + summary: Modifies a project in the organization. + operationId: modify-project + tags: + - Projects + requestBody: + description: The project update request payload. + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectUpdateRequest" + responses: + "200": + description: Project updated successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/Project" + "400": + description: Error response when updating the default project. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" + x-oaiMeta: + name: Modify project + group: administration + returns: The updated [Project](/docs/api-reference/projects/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Project DEF" + }' - puts(page) - description: >- - Lists the currently available models, and provides basic information about each one such as the owner - and availability. - /models/{model}: - get: - operationId: retrieveModel + /organization/projects/{project_id}/archive: + post: + summary: Archives a project in the organization. Archived projects cannot be used or updated. + operationId: archive-project tags: - - Models - summary: Retrieve model + - Projects parameters: - - in: path - name: model + - name: project_id + in: path + description: The ID of the project. required: true schema: type: string - example: gpt-4o-mini - description: The ID of the model to use for this request responses: - '200': - description: OK + "200": + description: Project archived successfully. content: application/json: schema: - $ref: '#/components/schemas/Model' + $ref: "#/components/schemas/Project" x-oaiMeta: - name: Retrieve model - group: models - returns: >- - The [model](https://platform.openai.com/docs/api-reference/models/object) object matching the - specified ID. + name: Archive project + group: administration + returns: The archived [Project](/docs/api-reference/projects/object) object. examples: - response: | - { - "id": "VAR_chat_model_id", - "object": "model", - "created": 1686935002, - "owned_by": "openai" - } request: curl: | - curl https://api.openai.com/v1/models/VAR_chat_model_id \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - model = client.models.retrieve( - "gpt-4o-mini", - ) - print(model.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const model = await client.models.retrieve('gpt-4o-mini'); - - console.log(model.id); - csharp: | - using System; - using System.ClientModel; - - using OpenAI.Models; - - OpenAIModelClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - ClientResult model = client.GetModel("babbage-002"); - Console.WriteLine(model.Value.Id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - model, err := client.Models.Get(context.TODO(), "gpt-4o-mini") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", model.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.models.Model; - import com.openai.models.models.ModelRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Model model = client.models().retrieve("gpt-4o-mini"); - } + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/archive \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project DEF", + "created_at": 1711471533, + "archived_at": 1711471533, + "status": "archived" } - ruby: |- - require "openai" - openai = OpenAI::Client.new(api_key: "My API Key") - - model = openai.models.retrieve("gpt-4o-mini") - - puts(model) - description: >- - Retrieves a model instance, providing basic information about the model such as the owner and - permissioning. - delete: - operationId: deleteModel + /organization/projects/{project_id}/users: + get: + summary: Returns a list of users in the project. + operationId: list-project-users tags: - - Models - summary: Delete a fine-tuned model + - Projects parameters: - - in: path - name: model + - name: project_id + in: path + description: The ID of the project. required: true schema: type: string - example: ft:gpt-4o-mini:acemeco:suffix:abc123 - description: The model to delete + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string responses: - '200': - description: OK + "200": + description: Project users listed successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectUserListResponse" + "400": + description: Error response when project is archived. content: application/json: schema: - $ref: '#/components/schemas/DeleteModelResponse' + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Delete a fine-tuned model - group: models - returns: Deletion status. + name: List project users + group: administration + returns: A list of [ProjectUser](/docs/api-reference/project-users/object) objects. examples: - response: | - { - "id": "ft:gpt-4o-mini:acemeco:suffix:abc123", - "object": "model", - "deleted": true - } request: curl: | - curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \ - -X DELETE \ - -H "Authorization: Bearer $OPENAI_API_KEY" - python: |- - from openai import OpenAI + curl https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "first_id": "user-abc", + "last_id": "user-xyz", + "has_more": false + } + error_response: + content: | + { + "code": 400, + "message": "Project {name} is archived" + } - client = OpenAI( - api_key="My API Key", - ) - model_deleted = client.models.delete( - "ft:gpt-4o-mini:acemeco:suffix:abc123", - ) - print(model_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const modelDeleted = await client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123'); - - console.log(modelDeleted.id); - csharp: | - using System; - using System.ClientModel; - - using OpenAI.Models; - - OpenAIModelClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - ClientResult success = client.DeleteModel("ft:gpt-4o-mini:acemeco:suffix:abc123"); - Console.WriteLine(success); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - modelDeleted, err := client.Models.Delete(context.TODO(), "ft:gpt-4o-mini:acemeco:suffix:abc123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", modelDeleted.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.models.ModelDeleteParams; - import com.openai.models.models.ModelDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ModelDeleted modelDeleted = client.models().delete("ft:gpt-4o-mini:acemeco:suffix:abc123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - model_deleted = openai.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123") - - puts(model_deleted) - description: Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. - /moderations: post: - operationId: createModeration + summary: Adds a user to the project. Users must already be members of the organization to be added to a project. + operationId: create-project-user + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string tags: - - Moderations - summary: Create moderation + - Projects requestBody: + description: The project user create request payload. required: true content: application/json: schema: - $ref: '#/components/schemas/CreateModerationRequest' + $ref: "#/components/schemas/ProjectUserCreateRequest" responses: - '200': - description: OK + "200": + description: User added to project successfully. content: application/json: schema: - $ref: '#/components/schemas/CreateModerationResponse' + $ref: "#/components/schemas/ProjectUser" + "400": + description: Error response for various conditions. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Create moderation - group: moderations - returns: A [moderation](https://platform.openai.com/docs/api-reference/moderations/object) object. + name: Create project user + group: administration + returns: The created [ProjectUser](/docs/api-reference/project-users/object) object. examples: - - title: Single string - request: - curl: | - curl https://api.openai.com/v1/moderations \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "input": "I want to kill them." - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - moderation = client.moderations.create( - input="I want to kill them.", - ) - print(moderation.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const moderation = await client.moderations.create({ input: 'I want to kill them.' }); - - console.log(moderation.id); - csharp: | - using System; - using System.ClientModel; - - using OpenAI.Moderations; - - ModerationClient client = new( - model: "omni-moderation-latest", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - ClientResult moderation = client.ClassifyText("I want to kill them."); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{ - Input: openai.ModerationNewParamsInputUnion{ - OfString: openai.String("I want to kill them."), - }, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", moderation.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.moderations.ModerationCreateParams; - import com.openai.models.moderations.ModerationCreateResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ModerationCreateParams params = ModerationCreateParams.builder() - .input("I want to kill them.") - .build(); - ModerationCreateResponse moderation = client.moderations().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - moderation = openai.moderations.create(input: "I want to kill them.") - - puts(moderation) - response: | + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "user_id": "user_abc", + "role": "member" + }' + response: + content: | { - "id": "modr-AB8CjOTu2jiq12hp1AQPfeqFWaORR", - "model": "text-moderation-007", - "results": [ - { - "flagged": true, - "categories": { - "sexual": false, - "hate": false, - "harassment": true, - "self-harm": false, - "sexual/minors": false, - "hate/threatening": false, - "violence/graphic": false, - "self-harm/intent": false, - "self-harm/instructions": false, - "harassment/threatening": true, - "violence": true - }, - "category_scores": { - "sexual": 0.000011726012417057063, - "hate": 0.22706663608551025, - "harassment": 0.5215635299682617, - "self-harm": 2.227119921371923e-6, - "sexual/minors": 7.107352217872176e-8, - "hate/threatening": 0.023547329008579254, - "violence/graphic": 0.00003391829886822961, - "self-harm/intent": 1.646940972932498e-6, - "self-harm/instructions": 1.1198755256458526e-9, - "harassment/threatening": 0.5694745779037476, - "violence": 0.9971134662628174 - } - } - ] + "object": "organization.project.user", + "id": "user_abc", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 } - - title: Image and text - request: - curl: | - curl https://api.openai.com/v1/moderations \ - -X POST \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "omni-moderation-latest", - "input": [ - { "type": "text", "text": "...text to classify goes here..." }, - { - "type": "image_url", - "image_url": { - "url": "https://example.com/image.png" - } - } - ] - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - moderation = client.moderations.create( - input="I want to kill them.", - ) - print(moderation.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const moderation = await client.moderations.create({ input: 'I want to kill them.' }); - - console.log(moderation.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{ - Input: openai.ModerationNewParamsInputUnion{ - OfString: openai.String("I want to kill them."), - }, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", moderation.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.moderations.ModerationCreateParams; - import com.openai.models.moderations.ModerationCreateResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ModerationCreateParams params = ModerationCreateParams.builder() - .input("I want to kill them.") - .build(); - ModerationCreateResponse moderation = client.moderations().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - moderation = openai.moderations.create(input: "I want to kill them.") - - puts(moderation) - response: | + error_response: + content: | { - "id": "modr-0d9740456c391e43c445bf0f010940c7", - "model": "omni-moderation-latest", - "results": [ - { - "flagged": true, - "categories": { - "harassment": true, - "harassment/threatening": true, - "sexual": false, - "hate": false, - "hate/threatening": false, - "illicit": false, - "illicit/violent": false, - "self-harm/intent": false, - "self-harm/instructions": false, - "self-harm": false, - "sexual/minors": false, - "violence": true, - "violence/graphic": true - }, - "category_scores": { - "harassment": 0.8189693396524255, - "harassment/threatening": 0.804985420696006, - "sexual": 1.573112165348997e-6, - "hate": 0.007562942636942845, - "hate/threatening": 0.004208854591835476, - "illicit": 0.030535955153511665, - "illicit/violent": 0.008925306722380033, - "self-harm/intent": 0.00023023930975076432, - "self-harm/instructions": 0.0002293869201073356, - "self-harm": 0.012598046106750154, - "sexual/minors": 2.212566909570261e-8, - "violence": 0.9999992735124786, - "violence/graphic": 0.843064871157054 - }, - "category_applied_input_types": { - "harassment": [ - "text" - ], - "harassment/threatening": [ - "text" - ], - "sexual": [ - "text", - "image" - ], - "hate": [ - "text" - ], - "hate/threatening": [ - "text" - ], - "illicit": [ - "text" - ], - "illicit/violent": [ - "text" - ], - "self-harm/intent": [ - "text", - "image" - ], - "self-harm/instructions": [ - "text", - "image" - ], - "self-harm": [ - "text", - "image" - ], - "sexual/minors": [ - "text" - ], - "violence": [ - "text", - "image" - ], - "violence/graphic": [ - "text", - "image" - ] - } - } - ] + "code": 400, + "message": "Project {name} is archived" } - description: | - Classifies if text and/or image inputs are potentially harmful. Learn - more in the [moderation guide](https://platform.openai.com/docs/guides/moderation). - /organization/admin_api_keys: + + /organization/projects/{project_id}/users/{user_id}: get: - summary: List all organization and project API keys. - operationId: admin-api-keys-list - description: List organization API keys + summary: Retrieves a user in the project. + operationId: retrieve-project-user + tags: + - Projects parameters: - - in: query - name: after - required: false + - name: project_id + in: path + description: The ID of the project. + required: true schema: type: string - nullable: true - description: Return keys with IDs that come after this ID in the pagination order. - - in: query - name: order - required: false + - name: user_id + in: path + description: The ID of the user. + required: true schema: type: string - enum: - - asc - - desc - default: asc - description: Order results by creation time, ascending or descending. - - in: query - name: limit - required: false - schema: - type: integer - default: 20 - description: Maximum number of keys to return. responses: - '200': - description: A list of organization API keys. + "200": + description: Project user retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/ApiKeyList' + $ref: "#/components/schemas/ProjectUser" x-oaiMeta: - name: List all organization and project API keys. + name: Retrieve project user group: administration - returns: A list of admin and project API key objects. + returns: The [ProjectUser](/docs/api-reference/project-users/object) object matching the specified ID. examples: - response: | - { - "object": "list", - "data": [ - { - "object": "organization.admin_api_key", - "id": "key_abc", - "name": "Main Admin Key", - "redacted_value": "sk-admin...def", - "created_at": 1711471533, - "last_used_at": 1711471534, - "owner": { - "type": "service_account", - "object": "organization.service_account", - "id": "sa_456", - "name": "My Service Account", - "created_at": 1711471533, - "role": "member" - } - } - ], - "first_id": "key_abc", - "last_id": "key_abc", - "has_more": false - } request: curl: | - curl https://api.openai.com/v1/organization/admin_api_keys?after=key_abc&limit=20 \ + curl https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + post: - summary: Create admin API key - operationId: admin-api-keys-create - description: Create an organization admin API key + summary: Modifies a user's role in the project. + operationId: modify-project-user + tags: + - Projects requestBody: + description: The project user update request payload. required: true content: application/json: schema: - type: object - required: - - name - properties: - name: - type: string - example: New Admin Key + $ref: "#/components/schemas/ProjectUserUpdateRequest" responses: - '200': - description: The newly created admin API key. + "200": + description: Project user's role updated successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectUser" + "400": + description: Error response for various conditions. content: application/json: schema: - $ref: '#/components/schemas/AdminApiKey' + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Create admin API key + name: Modify project user group: administration - returns: >- - The created [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) - object. + returns: The updated [ProjectUser](/docs/api-reference/project-users/object) object. examples: - response: | - { - "object": "organization.admin_api_key", - "id": "key_xyz", - "name": "New Admin Key", - "redacted_value": "sk-admin...xyz", - "created_at": 1711471533, - "last_used_at": 1711471534, - "owner": { - "type": "user", - "object": "organization.user", - "id": "user_123", - "name": "John Doe", - "created_at": 1711471533, - "role": "owner" - }, - "value": "sk-admin-1234abcd" - } request: curl: | - curl -X POST https://api.openai.com/v1/organization/admin_api_keys \ + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ - "name": "New Admin Key" + "role": "owner" }' - /organization/admin_api_keys/{key_id}: - get: - summary: Retrieve admin API key - operationId: admin-api-keys-get - description: Retrieve a single organization API key + response: + content: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + + delete: + summary: Deletes a user from the project. + operationId: delete-project-user + tags: + - Projects parameters: - - in: path - name: key_id + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user. required: true schema: type: string - description: The ID of the API key. responses: - '200': - description: Details of the requested API key. + "200": + description: Project user deleted successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectUserDeleteResponse" + "400": + description: Error response for various conditions. content: application/json: schema: - $ref: '#/components/schemas/AdminApiKey' + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Retrieve admin API key + name: Delete project user group: administration - returns: >- - The requested [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) - object. + returns: Confirmation that project has been deleted or an error in case of an archived project, which has no users examples: - response: | - { - "object": "organization.admin_api_key", - "id": "key_abc", - "name": "Main Admin Key", - "redacted_value": "sk-admin...xyz", - "created_at": 1711471533, - "last_used_at": 1711471534, - "owner": { - "type": "user", - "object": "organization.user", - "id": "user_123", - "name": "John Doe", - "created_at": 1711471533, - "role": "owner" - } - } - request: - curl: | - curl https://api.openai.com/v1/organization/admin_api_keys/key_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - delete: - summary: Delete admin API key - operationId: admin-api-keys-delete - description: Delete an organization admin API key - parameters: - - in: path - name: key_id - required: true - schema: - type: string - description: The ID of the API key to be deleted. - responses: - '200': - description: Confirmation that the API key was deleted. - content: - application/json: - schema: - type: object - properties: - id: - type: string - example: key_abc - object: - type: string - example: organization.admin_api_key.deleted - deleted: - type: boolean - example: true - x-oaiMeta: - name: Delete admin API key - group: administration - returns: A confirmation object indicating the key was deleted. - examples: - response: | - { - "id": "key_abc", - "object": "organization.admin_api_key.deleted", - "deleted": true - } request: curl: | - curl -X DELETE https://api.openai.com/v1/organization/admin_api_keys/key_abc \ + curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" - /organization/audit_logs: + response: + content: | + { + "object": "organization.project.user.deleted", + "id": "user_abc", + "deleted": true + } + + /organization/projects/{project_id}/service_accounts: get: - summary: List audit logs - operationId: list-audit-logs + summary: Returns a list of service accounts in the project. + operationId: list-project-service-accounts tags: - - Audit Logs + - Projects parameters: - - name: effective_at - in: query - description: Return only events whose `effective_at` (Unix seconds) is in this range. - required: false - schema: - type: object - properties: - gt: - type: integer - description: Return only events whose `effective_at` (Unix seconds) is greater than this value. - gte: - type: integer - description: >- - Return only events whose `effective_at` (Unix seconds) is greater than or equal to this - value. - lt: - type: integer - description: Return only events whose `effective_at` (Unix seconds) is less than this value. - lte: - type: integer - description: Return only events whose `effective_at` (Unix seconds) is less than or equal to this value. - - name: project_ids[] - in: query - description: Return only events for these projects. - required: false - schema: - type: array - items: - type: string - - name: event_types[] - in: query - description: >- - Return only events with a `type` in one of these values. For example, `project.created`. For all - options, see the documentation for the [audit log - object](https://platform.openai.com/docs/api-reference/audit-logs/object). - required: false - schema: - type: array - items: - $ref: '#/components/schemas/AuditLogEventType' - - name: actor_ids[] - in: query - description: >- - Return only events performed by these actors. Can be a user ID, a service account ID, or an api - key tracking ID. - required: false - schema: - type: array - items: - type: string - - name: actor_emails[] - in: query - description: Return only events performed by users with these emails. - required: false - schema: - type: array - items: - type: string - - name: resource_ids[] - in: query - description: Return only events performed on these targets. For example, a project ID updated. - required: false - schema: - type: array - items: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. + - name: project_id + in: path + description: The ID of the project. + required: true schema: type: string - responses: - '200': - description: Audit logs listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ListAuditLogsResponse' - x-oaiMeta: - name: List audit logs - group: audit-logs - returns: >- - A list of paginated [Audit Log](https://platform.openai.com/docs/api-reference/audit-logs/object) - objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "audit_log-xxx_yyyymmdd", - "type": "project.archived", - "effective_at": 1722461446, - "actor": { - "type": "api_key", - "api_key": { - "type": "user", - "user": { - "id": "user-xxx", - "email": "user@example.com" - } - } - }, - "project.archived": { - "id": "proj_abc" - }, - }, - { - "id": "audit_log-yyy__20240101", - "type": "api_key.updated", - "effective_at": 1720804190, - "actor": { - "type": "session", - "session": { - "user": { - "id": "user-xxx", - "email": "user@example.com" - }, - "ip_address": "127.0.0.1", - "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", - "ja3": "a497151ce4338a12c4418c44d375173e", - "ja4": "q13d0313h3_55b375c5d22e_c7319ce65786", - "ip_address_details": { - "country": "US", - "city": "San Francisco", - "region": "California", - "region_code": "CA", - "asn": "1234", - "latitude": "37.77490", - "longitude": "-122.41940" - } - } - }, - "api_key.updated": { - "id": "key_xxxx", - "data": { - "scopes": ["resource_2.operation_2"] - } - }, - } - ], - "first_id": "audit_log-xxx__20240101", - "last_id": "audit_log_yyy__20240101", - "has_more": true - } - request: - curl: | - curl https://api.openai.com/v1/organization/audit_logs \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: List user actions and configuration changes within this organization. - /organization/certificates: - get: - summary: List organization certificates - operationId: listOrganizationCertificates - tags: - - Certificates - parameters: - name: limit in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. + description: *pagination_limit_param_description required: false schema: type: integer default: 20 - name: after in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. + description: *pagination_after_param_description required: false schema: type: string - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc responses: - '200': - description: Certificates listed successfully. + "200": + description: Project service accounts listed successfully. content: application/json: schema: - $ref: '#/components/schemas/ListCertificatesResponse' - x-oaiMeta: - name: List organization certificates - group: administration - returns: A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects. - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/certificates \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" - response: | - { - "object": "list", - "data": [ - { - "object": "organization.certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "active": true, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - ], - "first_id": "cert_abc", - "last_id": "cert_abc", - "has_more": false - } - description: List uploaded certificates for this organization. - post: - summary: Upload certificate - operationId: uploadCertificate - tags: - - Certificates - requestBody: - description: The certificate upload payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/UploadCertificateRequest' - responses: - '200': - description: Certificate uploaded successfully. + $ref: "#/components/schemas/ProjectServiceAccountListResponse" + "400": + description: Error response when project is archived. content: application/json: schema: - $ref: '#/components/schemas/Certificate' + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Upload certificate + name: List project service accounts group: administration - returns: A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object. + returns: A list of [ProjectServiceAccount](/docs/api-reference/project-service-accounts/object) objects. examples: request: curl: | - curl -X POST https://api.openai.com/v1/organization/certificates \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "My Example Certificate", - "certificate": "-----BEGIN CERTIFICATE-----\\nMIIDeT...\\n-----END CERTIFICATE-----" - }' - response: | - { - "object": "certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 + curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + ], + "first_id": "svc_acct_abc", + "last_id": "svc_acct_xyz", + "has_more": false } - } - description: | - Upload a certificate to the organization. This does **not** automatically activate the certificate. - Organizations can upload up to 50 certificates. - /organization/certificates/activate: post: - summary: Activate certificates for organization - operationId: activateOrganizationCertificates + summary: Creates a new service account in the project. This also returns an unredacted API key for the service account. + operationId: create-project-service-account tags: - - Certificates + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string requestBody: - description: The certificate activation payload. + description: The project service account create request payload. required: true content: application/json: schema: - $ref: '#/components/schemas/ToggleCertificatesRequest' + $ref: "#/components/schemas/ProjectServiceAccountCreateRequest" responses: - '200': - description: Certificates activated successfully. + "200": + description: Project service account created successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectServiceAccountCreateResponse" + "400": + description: Error response when project is archived. content: application/json: schema: - $ref: '#/components/schemas/ListCertificatesResponse' + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Activate certificates for organization + name: Create project service account group: administration - returns: >- - A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects - that were activated. + returns: The created [ProjectServiceAccount](/docs/api-reference/project-service-accounts/object) object. examples: request: curl: | - curl https://api.openai.com/v1/organization/certificates/activate \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "data": ["cert_abc", "cert_def"] - }' - response: | - { - "object": "organization.certificate.activation", - "data": [ - { - "object": "organization.certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "active": true, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - { - "object": "organization.certificate", - "id": "cert_def", - "name": "My Example Certificate 2", - "active": true, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - ], - } - description: | - Activate certificates at the organization level. - - You can atomically and idempotently activate up to 10 certificates at a time. - /organization/certificates/deactivate: - post: - summary: Deactivate certificates for organization - operationId: deactivateOrganizationCertificates - tags: - - Certificates - requestBody: - description: The certificate deactivation payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ToggleCertificatesRequest' - responses: - '200': - description: Certificates deactivated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ListCertificatesResponse' - x-oaiMeta: - name: Deactivate certificates for organization - group: administration - returns: >- - A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects - that were deactivated. - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/certificates/deactivate \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "data": ["cert_abc", "cert_def"] - }' - response: | - { - "object": "organization.certificate.deactivation", - "data": [ - { - "object": "organization.certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "active": false, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - { - "object": "organization.certificate", - "id": "cert_def", - "name": "My Example Certificate 2", - "active": false, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/service_accounts \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Production App" + }' + response: + content: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Production App", + "role": "member", + "created_at": 1711471533, + "api_key": { + "object": "organization.project.service_account.api_key", + "value": "sk-abcdefghijklmnop123", + "name": "Secret Key", + "created_at": 1711471533, + "id": "key_abc" } - }, - ], - } - description: | - Deactivate certificates at the organization level. + } - You can atomically and idempotently deactivate up to 10 certificates at a time. - /organization/certificates/{certificate_id}: + /organization/projects/{project_id}/service_accounts/{service_account_id}: get: - summary: Get certificate - operationId: getCertificate + summary: Retrieves a service account in the project. + operationId: retrieve-project-service-account tags: - - Certificates + - Projects parameters: - - name: certificate_id + - name: project_id in: path - description: Unique ID of the certificate to retrieve. + description: The ID of the project. required: true schema: type: string - - name: include - in: query - description: >- - A list of additional fields to include in the response. Currently the only supported value is - `content` to fetch the PEM content of the certificate. - required: false + - name: service_account_id + in: path + description: The ID of the service account. + required: true schema: - type: array - items: - type: string - enum: - - content + type: string responses: - '200': - description: Certificate retrieved successfully. + "200": + description: Project service account retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/Certificate' + $ref: "#/components/schemas/ProjectServiceAccount" x-oaiMeta: - name: Get certificate + name: Retrieve project service account group: administration - returns: A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object. + returns: The [ProjectServiceAccount](/docs/api-reference/project-service-accounts/object) object matching the specified ID. examples: request: curl: | - curl "https://api.openai.com/v1/organization/certificates/cert_abc?include[]=content" \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" - response: | - { - "object": "certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "created_at": 1234567, - "certificate_details": { - "valid_at": 1234567, - "expires_at": 12345678, - "content": "-----BEGIN CERTIFICATE-----MIIDeT...-----END CERTIFICATE-----" + curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 } - } - description: | - Get a certificate that has been uploaded to the organization. - You can get a certificate regardless of whether it is active or not. - post: - summary: Modify certificate - operationId: modifyCertificate - tags: - - Certificates - requestBody: - description: The certificate modification payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ModifyCertificateRequest' - responses: - '200': - description: Certificate modified successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Certificate' - x-oaiMeta: - name: Modify certificate - group: administration - returns: >- - The updated [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) - object. - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/certificates/cert_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Renamed Certificate" - }' - response: | - { - "object": "certificate", - "id": "cert_abc", - "name": "Renamed Certificate", - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - } - description: | - Modify a certificate. Note that only the name can be modified. delete: - summary: Delete certificate - operationId: deleteCertificate + summary: Deletes a service account from the project. + operationId: delete-project-service-account tags: - - Certificates + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: service_account_id + in: path + description: The ID of the service account. + required: true + schema: + type: string responses: - '200': - description: Certificate deleted successfully. + "200": + description: Project service account deleted successfully. content: application/json: schema: - $ref: '#/components/schemas/DeleteCertificateResponse' + $ref: "#/components/schemas/ProjectServiceAccountDeleteResponse" x-oaiMeta: - name: Delete certificate + name: Delete project service account group: administration - returns: A confirmation object indicating the certificate was deleted. + returns: Confirmation of service account being deleted, or an error in case of an archived project, which has no service accounts examples: request: curl: | - curl -X DELETE https://api.openai.com/v1/organization/certificates/cert_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" - response: | - { - "object": "certificate.deleted", - "id": "cert_abc" - } - description: | - Delete a certificate from the organization. + curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.service_account.deleted", + "id": "svc_acct_abc", + "deleted": true + } - The certificate must be inactive for the organization and all projects. - /organization/costs: + /organization/projects/{project_id}/api_keys: get: - summary: Costs - operationId: usage-costs + summary: Returns a list of API keys in the project. + operationId: list-project-api-keys tags: - - Usage + - Projects parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. + - name: project_id + in: path + description: The ID of the project. required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: Width of each time bucket in response. Currently only `1d` is supported, default to `1d`. - required: false schema: type: string - enum: - - 1d - default: 1d - - name: project_ids - in: query - description: Return only costs for these projects. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: >- - Group the costs by the specified fields. Support fields include `project_id`, `line_item` and any - combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - line_item - name: limit in: query - description: > - A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the - default is 7. + description: *pagination_limit_param_description required: false schema: type: integer - default: 7 - - name: page + default: 20 + - name: after in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. + description: *pagination_after_param_description + required: false schema: type: string responses: - '200': - description: Costs data retrieved successfully. + "200": + description: Project API keys listed successfully. content: application/json: schema: - $ref: '#/components/schemas/UsageResponse' + $ref: "#/components/schemas/ProjectApiKeyListResponse" + x-oaiMeta: - name: Costs - group: usage-costs - returns: >- - A list of paginated, time bucketed - [Costs](https://platform.openai.com/docs/api-reference/usage/costs_object) objects. + name: List project API keys + group: administration + returns: A list of [ProjectApiKey](/docs/api-reference/project-api-keys/object) objects. examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.costs.result", - "amount": { - "value": 0.06, - "currency": "usd" - }, - "line_item": null, - "project_id": null - } - ] - } - ], - "has_more": false, - "next_page": null - } request: curl: | - curl "https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1" \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Get costs details for the organization. - /organization/groups: + curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } + ], + "first_id": "key_abc", + "last_id": "key_xyz", + "has_more": false + } + error_response: + content: | + { + "code": 400, + "message": "Project {name} is archived" + } + + /organization/projects/{project_id}/api_keys/{key_id}: get: - summary: List groups - operationId: list-groups + summary: Retrieves an API key in the project. + operationId: retrieve-project-api-key tags: - - Groups + - Projects parameters: - - name: limit - in: query - description: > - A limit on the number of groups to be returned. Limit can range between 0 and 1000, and the - default is 100. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - default: 100 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is a group ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with group_abc, your - subsequent call can include `after=group_abc` in order to fetch the next page of the list. - required: false + - name: project_id + in: path + description: The ID of the project. + required: true schema: type: string - - name: order - in: query - description: Specifies the sort order of the returned groups. - required: false + - name: key_id + in: path + description: The ID of the API key. + required: true schema: type: string - enum: - - asc - - desc - default: asc responses: - '200': - description: Groups listed successfully. + "200": + description: Project API key retrieved successfully. content: application/json: schema: - $ref: '#/components/schemas/GroupListResource' + $ref: "#/components/schemas/ProjectApiKey" x-oaiMeta: - name: List groups + name: Retrieve project API key group: administration - returns: A list of [group objects](https://platform.openai.com/docs/api-reference/groups/object). + returns: The [ProjectApiKey](/docs/api-reference/project-api-keys/object) object matching the specified ID. examples: request: curl: | - curl https://api.openai.com/v1/organization/groups?limit=20&order=asc \ + curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "object": "group", - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "is_scim_managed": false - } - ], - "has_more": false, - "next": null - } - description: Lists all groups in the organization. - post: - summary: Create group - operationId: create-group + response: + content: | + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } + + delete: + summary: Deletes an API key from the project. + operationId: delete-project-api-key tags: - - Groups - requestBody: - description: Parameters for the group you want to create. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateGroupBody' + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: key_id + in: path + description: The ID of the API key. + required: true + schema: + type: string responses: - '200': - description: Group created successfully. + "200": + description: Project API key deleted successfully. content: application/json: schema: - $ref: '#/components/schemas/GroupResponse' + $ref: "#/components/schemas/ProjectApiKeyDeleteResponse" + "400": + description: Error response for various conditions. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorResponse" x-oaiMeta: - name: Create group + name: Delete project API key group: administration - returns: The created [group object](https://platform.openai.com/docs/api-reference/groups/object). + returns: Confirmation of the key's deletion or an error if the key belonged to a service account examples: request: curl: | - curl -X POST https://api.openai.com/v1/organization/groups \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Support Team" - }' - response: | - { - "object": "group", - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "is_scim_managed": false - } - description: Creates a new group in the organization. - /organization/groups/{group_id}: - post: - summary: Update group - operationId: update-group - tags: - - Groups - parameters: - - name: group_id - in: path - description: The ID of the group to update. - required: true - schema: - type: string - requestBody: - description: New attributes to set on the group. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/UpdateGroupBody' - responses: - '200': - description: Group updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/GroupResourceWithSuccess' - x-oaiMeta: - name: Update group - group: administration - returns: The updated [group object](https://platform.openai.com/docs/api-reference/groups/object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Escalations" - }' - response: | - { - "id": "group_01J1F8ABCDXYZ", - "name": "Escalations", - "created_at": 1711471533, - "is_scim_managed": false - } - description: Updates a group's information. - delete: - summary: Delete group - operationId: delete-group - tags: - - Groups - parameters: - - name: group_id - in: path - description: The ID of the group to delete. - required: true - schema: - type: string - responses: - '200': - description: Group deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/GroupDeletedResource' - x-oaiMeta: - name: Delete group - group: administration - returns: Confirmation of the deleted group. - examples: - request: - curl: | - curl -X DELETE https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "group.deleted", - "id": "group_01J1F8ABCDXYZ", - "deleted": true - } - description: Deletes a group from the organization. - /organization/groups/{group_id}/roles: - get: - summary: List group organization role assignments - operationId: list-group-role-assignments - tags: - - Group organization role assignments - parameters: - - name: group_id - in: path - description: The ID of the group whose organization role assignments you want to list. - required: true - schema: - type: string - - name: limit - in: query - description: A limit on the number of organization role assignments to return. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - - name: after - in: query - description: >- - Cursor for pagination. Provide the value from the previous response's `next` field to continue - listing organization roles. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned organization roles. - required: false - schema: - type: string - enum: - - asc - - desc - responses: - '200': - description: Group organization role assignments listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RoleListResource' - x-oaiMeta: - name: List group organization role assignments - group: administration - returns: A list of [role objects](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false, - "description": "Allows managing organization groups", - "created_at": 1711471533, - "updated_at": 1711472599, - "created_by": "user_abc123", - "created_by_user_obj": { - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com" - }, - "metadata": {} - } - ], - "has_more": false, - "next": null - } - description: Lists the organization roles assigned to a group within the organization. - post: - summary: Assign organization role to group - operationId: assign-group-role - tags: - - Group organization role assignments - parameters: - - name: group_id - in: path - description: The ID of the group that should receive the organization role. - required: true - schema: - type: string - requestBody: - description: Identifies the organization role to assign to the group. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' - responses: - '200': - description: Organization role assigned to the group successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/GroupRoleAssignment' - x-oaiMeta: - name: Assign organization role to group - group: administration - returns: >- - The created [group role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/group). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_id": "role_01J1F8ROLE01" - }' - response: | - { - "object": "group.role", - "group": { - "object": "group", - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "scim_managed": false - }, - "role": { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - } - description: Assigns an organization role to a group within the organization. - /organization/groups/{group_id}/roles/{role_id}: - delete: - summary: Unassign organization role from group - operationId: unassign-group-role - tags: - - Group organization role assignments - parameters: - - name: group_id - in: path - description: The ID of the group to modify. - required: true - schema: - type: string - - name: role_id - in: path - description: The ID of the organization role to remove from the group. - required: true - schema: - type: string - responses: - '200': - description: Organization role unassigned from the group successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedRoleAssignmentResource' - x-oaiMeta: - name: Unassign organization role from group - group: administration - returns: >- - Confirmation of the deleted [group role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/group). - examples: - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/roles/role_01J1F8ROLE01 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "group.role.deleted", - "deleted": true - } - description: Unassigns an organization role from a group within the organization. - /organization/groups/{group_id}/users: - get: - summary: List group users - operationId: list-group-users - tags: - - Group users - parameters: - - name: group_id - in: path - description: The ID of the group to inspect. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of users to be returned. Limit can range between 0 and 1000, and the default - is 100. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - default: 100 - - name: after - in: query - description: > - A cursor for use in pagination. Provide the ID of the last user from the previous list response to - retrieve the next page. - required: false - schema: - type: string - - name: order - in: query - description: Specifies the sort order of users in the list. - required: false - schema: - type: string - enum: - - asc - - desc - default: desc - responses: - '200': - description: Group users listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UserListResource' - x-oaiMeta: - name: List group users - group: administration - returns: A list of [user objects](https://platform.openai.com/docs/api-reference/users/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/users?limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "object": "organization.user", - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com", - "role": "owner", - "added_at": 1711471533 - } - ], - "has_more": false, - "next": null - } - description: Lists the users assigned to a group. - post: - summary: Add group user - operationId: add-group-user - tags: - - Group users - parameters: - - name: group_id - in: path - description: The ID of the group to update. - required: true - schema: - type: string - requestBody: - description: Identifies the user that should be added to the group. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateGroupUserBody' - responses: - '200': - description: User added to the group successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/GroupUserAssignment' - x-oaiMeta: - name: Add group user - group: administration - returns: >- - The created [group user - object](https://platform.openai.com/docs/api-reference/groups/users/assignment-object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/users \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "user_id": "user_abc123" - }' - response: | - { - "object": "group.user", - "user_id": "user_abc123", - "group_id": "group_01J1F8ABCDXYZ" - } - description: Adds a user to a group. - /organization/groups/{group_id}/users/{user_id}: - delete: - summary: Remove group user - operationId: remove-group-user - tags: - - Group users - parameters: - - name: group_id - in: path - description: The ID of the group to update. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user to remove from the group. - required: true - schema: - type: string - responses: - '200': - description: User removed from the group successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/GroupUserDeletedResource' - x-oaiMeta: - name: Remove group user - group: administration - returns: >- - Confirmation of the deleted [group user - object](https://platform.openai.com/docs/api-reference/groups/users/assignment-object). - examples: - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/users/user_abc123 \ + curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" - response: | - { - "object": "group.user.deleted", - "deleted": true - } - description: Removes a user from a group. - /organization/invites: - get: - summary: List invites - operationId: list-invites - tags: - - Invites - parameters: - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - responses: - '200': - description: Invites listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/InviteListResponse' - x-oaiMeta: - name: List invites - group: administration - returns: A list of [Invite](https://platform.openai.com/docs/api-reference/invite/object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "organization.invite", - "id": "invite-abc", - "email": "user@example.com", - "role": "owner", - "status": "accepted", - "invited_at": 1711471533, - "expires_at": 1711471533, - "accepted_at": 1711471533 - } - ], - "first_id": "invite-abc", - "last_id": "invite-abc", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Returns a list of invites in the organization. - post: - summary: Create invite - operationId: inviteUser - tags: - - Invites - requestBody: - description: The invite request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/InviteRequest' - responses: - '200': - description: User invited successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Invite' - x-oaiMeta: - name: Create invite - group: administration - returns: The created [Invite](https://platform.openai.com/docs/api-reference/invite/object) object. - examples: - response: | - { - "object": "organization.invite", - "id": "invite-def", - "email": "anotheruser@example.com", - "role": "reader", - "status": "pending", - "invited_at": 1711471533, - "expires_at": 1711471533, - "accepted_at": null, - "projects": [ - { - "id": "project-xyz", - "role": "member" - }, - { - "id": "project-abc", - "role": "owner" - } - ] - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/invites \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "email": "anotheruser@example.com", - "role": "reader", - "projects": [ - { - "id": "project-xyz", - "role": "member" - }, - { - "id": "project-abc", - "role": "owner" - } - ] - }' - description: >- - Create an invite for a user to the organization. The invite must be accepted by the user before they - have access to the organization. - /organization/invites/{invite_id}: - get: - summary: Retrieve invite - operationId: retrieve-invite - tags: - - Invites - parameters: - - in: path - name: invite_id - required: true - schema: - type: string - description: The ID of the invite to retrieve. - responses: - '200': - description: Invite retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Invite' - x-oaiMeta: - name: Retrieve invite - group: administration - returns: >- - The [Invite](https://platform.openai.com/docs/api-reference/invite/object) object matching the - specified ID. - examples: - response: | - { - "object": "organization.invite", - "id": "invite-abc", - "email": "user@example.com", - "role": "owner", - "status": "accepted", - "invited_at": 1711471533, - "expires_at": 1711471533, - "accepted_at": 1711471533 - } - request: - curl: | - curl https://api.openai.com/v1/organization/invites/invite-abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Retrieves an invite. - delete: - summary: Delete invite - operationId: delete-invite - tags: - - Invites - parameters: - - in: path - name: invite_id - required: true - schema: - type: string - description: The ID of the invite to delete. - responses: - '200': - description: Invite deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/InviteDeleteResponse' - x-oaiMeta: - name: Delete invite - group: administration - returns: Confirmation that the invite has been deleted - examples: - response: | - { - "object": "organization.invite.deleted", - "id": "invite-abc", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/organization/invites/invite-abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Delete an invite. If the invite has already been accepted, it cannot be deleted. - /organization/projects: - get: - summary: List projects - operationId: list-projects - tags: - - Projects - parameters: - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - - name: include_archived - in: query - schema: - type: boolean - default: false - description: >- - If `true` returns all projects including those that have been `archived`. Archived projects are - not included by default. - responses: - '200': - description: Projects listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectListResponse' - x-oaiMeta: - name: List projects - group: administration - returns: A list of [Project](https://platform.openai.com/docs/api-reference/projects/object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "proj_abc", - "object": "organization.project", - "name": "Project example", - "created_at": 1711471533, - "archived_at": null, - "status": "active" - } - ], - "first_id": "proj-abc", - "last_id": "proj-xyz", - "has_more": false - } - request: - curl: > - curl - https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Returns a list of projects. - post: - summary: Create project - operationId: create-project - tags: - - Projects - requestBody: - description: The project create request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectCreateRequest' - responses: - '200': - description: Project created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Project' - x-oaiMeta: - name: Create project - group: administration - returns: The created [Project](https://platform.openai.com/docs/api-reference/projects/object) object. - examples: - response: | - { - "id": "proj_abc", - "object": "organization.project", - "name": "Project ABC", - "created_at": 1711471533, - "archived_at": null, - "status": "active" - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Project ABC" - }' - description: Create a new project in the organization. Projects can be created and archived, but cannot be deleted. - /organization/projects/{project_id}: - get: - summary: Retrieve project - operationId: retrieve-project - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - responses: - '200': - description: Project retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Project' - x-oaiMeta: - name: Retrieve project - group: administration - description: Retrieve a project. - returns: >- - The [Project](https://platform.openai.com/docs/api-reference/projects/object) object matching the - specified ID. - examples: - response: | - { - "id": "proj_abc", - "object": "organization.project", - "name": "Project example", - "created_at": 1711471533, - "archived_at": null, - "status": "active" - } - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Retrieves a project. - post: - summary: Modify project - operationId: modify-project - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - requestBody: - description: The project update request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUpdateRequest' - responses: - '200': - description: Project updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Project' - '400': - description: Error response when updating the default project. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Modify project - group: administration - returns: The updated [Project](https://platform.openai.com/docs/api-reference/projects/object) object. - examples: - response: '' - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Project DEF" - }' - description: Modifies a project in the organization. - /organization/projects/{project_id}/api_keys: - get: - summary: List project API keys - operationId: list-project-api-keys - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - responses: - '200': - description: Project API keys listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectApiKeyListResponse' - x-oaiMeta: - name: List project API keys - group: administration - returns: >- - A list of [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) - objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "organization.project.api_key", - "redacted_value": "sk-abc...def", - "name": "My API Key", - "created_at": 1711471533, - "last_used_at": 1711471534, - "id": "key_abc", - "owner": { - "type": "user", - "user": { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - } - } - ], - "first_id": "key_abc", - "last_id": "key_xyz", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Returns a list of API keys in the project. - /organization/projects/{project_id}/api_keys/{key_id}: - get: - summary: Retrieve project API key - operationId: retrieve-project-api-key - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: key_id - in: path - description: The ID of the API key. - required: true - schema: - type: string - responses: - '200': - description: Project API key retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectApiKey' - x-oaiMeta: - name: Retrieve project API key - group: administration - returns: >- - The [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) object - matching the specified ID. - examples: - response: | - { - "object": "organization.project.api_key", - "redacted_value": "sk-abc...def", - "name": "My API Key", - "created_at": 1711471533, - "last_used_at": 1711471534, - "id": "key_abc", - "owner": { - "type": "user", - "user": { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - } - } - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Retrieves an API key in the project. - delete: - summary: Delete project API key - operationId: delete-project-api-key - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: key_id - in: path - description: The ID of the API key. - required: true - schema: - type: string - responses: - '200': - description: Project API key deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectApiKeyDeleteResponse' - '400': - description: Error response for various conditions. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Delete project API key - group: administration - returns: Confirmation of the key's deletion or an error if the key belonged to a service account - examples: - response: | - { - "object": "organization.project.api_key.deleted", - "id": "key_abc", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Deletes an API key from the project. - /organization/projects/{project_id}/archive: - post: - summary: Archive project - operationId: archive-project - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - responses: - '200': - description: Project archived successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Project' - x-oaiMeta: - name: Archive project - group: administration - returns: The archived [Project](https://platform.openai.com/docs/api-reference/projects/object) object. - examples: - response: | - { - "id": "proj_abc", - "object": "organization.project", - "name": "Project DEF", - "created_at": 1711471533, - "archived_at": 1711471533, - "status": "archived" - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/archive \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Archives a project in the organization. Archived projects cannot be used or updated. - /organization/projects/{project_id}/certificates: - get: - summary: List project certificates - operationId: listProjectCertificates - tags: - - Certificates - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - responses: - '200': - description: Certificates listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ListCertificatesResponse' - x-oaiMeta: - name: List project certificates - group: administration - returns: A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects. - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/certificates \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" - response: | - { - "object": "list", - "data": [ - { - "object": "organization.project.certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "active": true, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - ], - "first_id": "cert_abc", - "last_id": "cert_abc", - "has_more": false - } - description: List certificates for this project. - /organization/projects/{project_id}/certificates/activate: - post: - summary: Activate certificates for project - operationId: activateProjectCertificates - tags: - - Certificates - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - requestBody: - description: The certificate activation payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ToggleCertificatesRequest' - responses: - '200': - description: Certificates activated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ListCertificatesResponse' - x-oaiMeta: - name: Activate certificates for project - group: administration - returns: >- - A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects - that were activated. - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/activate \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "data": ["cert_abc", "cert_def"] - }' - response: | - { - "object": "organization.project.certificate.activation", - "data": [ - { - "object": "organization.project.certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "active": true, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - { - "object": "organization.project.certificate", - "id": "cert_def", - "name": "My Example Certificate 2", - "active": true, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - ], - } - description: | - Activate certificates at the project level. - - You can atomically and idempotently activate up to 10 certificates at a time. - /organization/projects/{project_id}/certificates/deactivate: - post: - summary: Deactivate certificates for project - operationId: deactivateProjectCertificates - tags: - - Certificates - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - requestBody: - description: The certificate deactivation payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ToggleCertificatesRequest' - responses: - '200': - description: Certificates deactivated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ListCertificatesResponse' - x-oaiMeta: - name: Deactivate certificates for project - group: administration - returns: >- - A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects - that were deactivated. - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/deactivate \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "data": ["cert_abc", "cert_def"] - }' - response: | - { - "object": "organization.project.certificate.deactivation", - "data": [ - { - "object": "organization.project.certificate", - "id": "cert_abc", - "name": "My Example Certificate", - "active": false, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - { - "object": "organization.project.certificate", - "id": "cert_def", - "name": "My Example Certificate 2", - "active": false, - "created_at": 1234567, - "certificate_details": { - "valid_at": 12345667, - "expires_at": 12345678 - } - }, - ], - } - description: | - Deactivate certificates at the project level. You can atomically and - idempotently deactivate up to 10 certificates at a time. - /organization/projects/{project_id}/groups: - get: - summary: List project groups - operationId: list-project-groups - tags: - - Project groups - parameters: - - name: project_id - in: path - description: The ID of the project to inspect. - required: true - schema: - type: string - - name: limit - in: query - description: A limit on the number of project groups to return. Defaults to 20. - required: false - schema: - type: integer - minimum: 0 - maximum: 100 - default: 20 - - name: after - in: query - description: >- - Cursor for pagination. Provide the ID of the last group from the previous response to fetch the - next page. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned groups. - required: false - schema: - type: string - enum: - - asc - - desc - default: asc - responses: - '200': - description: Project groups listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectGroupListResource' - x-oaiMeta: - name: List project groups - group: administration - returns: >- - A list of [project group - objects](https://platform.openai.com/docs/api-reference/project-groups/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc123/groups?limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "object": "project.group", - "project_id": "proj_abc123", - "group_id": "group_01J1F8ABCDXYZ", - "group_name": "Support Team", - "created_at": 1711471533 - } - ], - "has_more": false, - "next": null - } - description: Lists the groups that have access to a project. - post: - summary: Add project group - operationId: add-project-group - tags: - - Project groups - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - requestBody: - description: Identifies the group and role to assign to the project. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/InviteProjectGroupBody' - responses: - '200': - description: Group granted access to the project successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectGroup' - x-oaiMeta: - name: Add project group - group: administration - returns: >- - The created [project group - object](https://platform.openai.com/docs/api-reference/project-groups/object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc123/groups \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "group_id": "group_01J1F8ABCDXYZ", - "role": "role_01J1F8PROJ" - }' - response: | - { - "object": "project.group", - "project_id": "proj_abc123", - "group_id": "group_01J1F8ABCDXYZ", - "group_name": "Support Team", - "created_at": 1711471533 - } - description: Grants a group access to a project. - /organization/projects/{project_id}/groups/{group_id}: - delete: - summary: Remove project group - operationId: remove-project-group - tags: - - Project groups - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - - name: group_id - in: path - description: The ID of the group to remove from the project. - required: true - schema: - type: string - responses: - '200': - description: Group removed from the project successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectGroupDeletedResource' - x-oaiMeta: - name: Remove project group - group: administration - returns: Confirmation of the deleted project group. - examples: - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/organization/projects/proj_abc123/groups/group_01J1F8ABCDXYZ \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "project.group.deleted", - "deleted": true - } - description: Revokes a group's access to a project. - /organization/projects/{project_id}/rate_limits: - get: - summary: List project rate limits - operationId: list-project-rate-limits - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: limit - in: query - description: | - A limit on the number of objects to be returned. The default is 100. - required: false - schema: - type: integer - default: 100 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, beginning with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - required: false - schema: - type: string - responses: - '200': - description: Project rate limits listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectRateLimitListResponse' - x-oaiMeta: - name: List project rate limits - group: administration - returns: >- - A list of - [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) - objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "project.rate_limit", - "id": "rl-ada", - "model": "ada", - "max_requests_per_1_minute": 600, - "max_tokens_per_1_minute": 150000, - "max_images_per_1_minute": 10 - } - ], - "first_id": "rl-ada", - "last_id": "rl-ada", - "has_more": false - } - request: - curl: > - curl https://api.openai.com/v1/organization/projects/proj_abc/rate_limits?after=rl_xxx&limit=20 - \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - error_response: | - { - "code": 404, - "message": "The project {project_id} was not found" - } - description: Returns the rate limits per model for a project. - /organization/projects/{project_id}/rate_limits/{rate_limit_id}: - post: - summary: Modify project rate limit - operationId: update-project-rate-limits - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: rate_limit_id - in: path - description: The ID of the rate limit. - required: true - schema: - type: string - requestBody: - description: The project rate limit update request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectRateLimitUpdateRequest' - responses: - '200': - description: Project rate limit updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectRateLimit' - '400': - description: Error response for various conditions. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Modify project rate limit - group: administration - returns: >- - The updated - [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) - object. - examples: - response: | - { - "object": "project.rate_limit", - "id": "rl-ada", - "model": "ada", - "max_requests_per_1_minute": 600, - "max_tokens_per_1_minute": 150000, - "max_images_per_1_minute": 10 - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/rate_limits/rl_xxx \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "max_requests_per_1_minute": 500 - }' - error_response: | - { - "code": 404, - "message": "The project {project_id} was not found" - } - description: Updates a project rate limit. - /organization/projects/{project_id}/service_accounts: - get: - summary: List project service accounts - operationId: list-project-service-accounts - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - responses: - '200': - description: Project service accounts listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectServiceAccountListResponse' - '400': - description: Error response when project is archived. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: List project service accounts - group: administration - returns: >- - A list of - [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) - objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "organization.project.service_account", - "id": "svc_acct_abc", - "name": "Service Account", - "role": "owner", - "created_at": 1711471533 - } - ], - "first_id": "svc_acct_abc", - "last_id": "svc_acct_xyz", - "has_more": false - } - request: - curl: > - curl - https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 - \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Returns a list of service accounts in the project. - post: - summary: Create project service account - operationId: create-project-service-account - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - requestBody: - description: The project service account create request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectServiceAccountCreateRequest' - responses: - '200': - description: Project service account created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectServiceAccountCreateResponse' - '400': - description: Error response when project is archived. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Create project service account - group: administration - returns: >- - The created - [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) - object. - examples: - response: | - { - "object": "organization.project.service_account", - "id": "svc_acct_abc", - "name": "Production App", - "role": "member", - "created_at": 1711471533, - "api_key": { - "object": "organization.project.service_account.api_key", - "value": "sk-abcdefghijklmnop123", - "name": "Secret Key", - "created_at": 1711471533, - "id": "key_abc" - } - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/service_accounts \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Production App" - }' - description: >- - Creates a new service account in the project. This also returns an unredacted API key for the service - account. - /organization/projects/{project_id}/service_accounts/{service_account_id}: - get: - summary: Retrieve project service account - operationId: retrieve-project-service-account - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: service_account_id - in: path - description: The ID of the service account. - required: true - schema: - type: string - responses: - '200': - description: Project service account retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectServiceAccount' - x-oaiMeta: - name: Retrieve project service account - group: administration - returns: >- - The - [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) - object matching the specified ID. - examples: - response: | - { - "object": "organization.project.service_account", - "id": "svc_acct_abc", - "name": "Service Account", - "role": "owner", - "created_at": 1711471533 - } - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Retrieves a service account in the project. - delete: - summary: Delete project service account - operationId: delete-project-service-account - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: service_account_id - in: path - description: The ID of the service account. - required: true - schema: - type: string - responses: - '200': - description: Project service account deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectServiceAccountDeleteResponse' - x-oaiMeta: - name: Delete project service account - group: administration - returns: >- - Confirmation of service account being deleted, or an error in case of an archived project, which has - no service accounts - examples: - response: | - { - "object": "organization.project.service_account.deleted", - "id": "svc_acct_abc", - "deleted": true - } - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Deletes a service account from the project. - /organization/projects/{project_id}/users: - get: - summary: List project users - operationId: list-project-users - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - responses: - '200': - description: Project users listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUserListResponse' - '400': - description: Error response when project is archived. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: List project users - group: administration - returns: >- - A list of [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) - objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - ], - "first_id": "user-abc", - "last_id": "user-xyz", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Returns a list of users in the project. - post: - summary: Create project user - operationId: create-project-user - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - tags: - - Projects - requestBody: - description: The project user create request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUserCreateRequest' - responses: - '200': - description: User added to project successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUser' - '400': - description: Error response for various conditions. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Create project user - group: administration - returns: >- - The created [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) - object. - examples: - response: | - { - "object": "organization.project.user", - "id": "user_abc", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "user_id": "user_abc", - "role": "member" - }' - description: >- - Adds a user to the project. Users must already be members of the organization to be added to a - project. - /organization/projects/{project_id}/users/{user_id}: - get: - summary: Retrieve project user - operationId: retrieve-project-user - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user. - required: true - schema: - type: string - responses: - '200': - description: Project user retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUser' - x-oaiMeta: - name: Retrieve project user - group: administration - returns: >- - The [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object - matching the specified ID. - examples: - response: | - { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - request: - curl: | - curl https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Retrieves a user in the project. - post: - summary: Modify project user - operationId: modify-project-user - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user. - required: true - schema: - type: string - requestBody: - description: The project user update request payload. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUserUpdateRequest' - responses: - '200': - description: Project user's role updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUser' - '400': - description: Error response for various conditions. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Modify project user - group: administration - returns: >- - The updated [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) - object. - examples: - response: | - { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role": "owner" - }' - description: Modifies a user's role in the project. - delete: - summary: Delete project user - operationId: delete-project-user - tags: - - Projects - parameters: - - name: project_id - in: path - description: The ID of the project. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user. - required: true - schema: - type: string - responses: - '200': - description: Project user deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/ProjectUserDeleteResponse' - '400': - description: Error response for various conditions. - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - x-oaiMeta: - name: Delete project user - group: administration - returns: >- - Confirmation that project has been deleted or an error in case of an archived project, which has no - users - examples: - response: | - { - "object": "organization.project.user.deleted", - "id": "user_abc", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Deletes a user from the project. - /organization/roles: - get: - summary: List organization roles - operationId: list-roles - tags: - - Roles - parameters: - - name: limit - in: query - description: A limit on the number of roles to return. Defaults to 1000. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - default: 1000 - - name: after - in: query - description: >- - Cursor for pagination. Provide the value from the previous response's `next` field to continue - listing roles. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned roles. - required: false - schema: - type: string - enum: - - asc - - desc - default: asc - responses: - '200': - description: Roles listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/PublicRoleListResource' - x-oaiMeta: - name: List organization roles - group: administration - returns: A list of [role objects](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/roles?limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - ], - "has_more": false, - "next": null - } - description: Lists the roles configured for the organization. - post: - summary: Create organization role - operationId: create-role - tags: - - Roles - requestBody: - description: Parameters for the role you want to create. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicCreateOrganizationRoleBody' - responses: - '200': - description: Role created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Role' - x-oaiMeta: - name: Create organization role - group: administration - returns: The created [role object](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "description": "Allows managing organization groups" - }' - response: | - { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - description: Creates a custom role for the organization. - /organization/roles/{role_id}: - post: - summary: Update organization role - operationId: update-role - tags: - - Roles - parameters: - - name: role_id - in: path - description: The ID of the role to update. - required: true - schema: - type: string - requestBody: - description: Fields to update on the role. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicUpdateOrganizationRoleBody' - responses: - '200': - description: Role updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Role' - x-oaiMeta: - name: Update organization role - group: administration - returns: The updated [role object](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/roles/role_01J1F8ROLE01 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "description": "Allows managing organization groups" - }' - response: | - { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - description: Updates an existing organization role. - delete: - summary: Delete organization role - operationId: delete-role - tags: - - Roles - parameters: - - name: role_id - in: path - description: The ID of the role to delete. - required: true - schema: - type: string - responses: - '200': - description: Role deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RoleDeletedResource' - x-oaiMeta: - name: Delete organization role - group: administration - returns: Confirmation of the deleted role. - examples: - request: - curl: | - curl -X DELETE https://api.openai.com/v1/organization/roles/role_01J1F8ROLE01 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "role.deleted", - "id": "role_01J1F8ROLE01", - "deleted": true - } - description: Deletes a custom role from the organization. - /organization/usage/audio_speeches: - get: - summary: Audio speeches - operationId: usage-audio-speeches - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: user_ids - in: query - description: Return only usage for these users. - required: false - schema: - type: array - items: - type: string - - name: api_key_ids - in: query - description: Return only usage for these API keys. - required: false - schema: - type: array - items: - type: string - - name: models - in: query - description: Return only usage for these models. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: >- - Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, - `api_key_id`, `model` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - user_id - - api_key_id - - model - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Audio speeches - group: usage-audio-speeches - returns: >- - A list of paginated, time bucketed [Audio speeches - usage](https://platform.openai.com/docs/api-reference/usage/audio_speeches_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.audio_speeches.result", - "characters": 45, - "num_model_requests": 1, - "project_id": null, - "user_id": null, - "api_key_id": null, - "model": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: > - curl "https://api.openai.com/v1/organization/usage/audio_speeches?start_time=1730419200&limit=1" - \ - - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - - -H "Content-Type: application/json" - description: Get audio speeches usage details for the organization. - /organization/usage/audio_transcriptions: - get: - summary: Audio transcriptions - operationId: usage-audio-transcriptions - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: user_ids - in: query - description: Return only usage for these users. - required: false - schema: - type: array - items: - type: string - - name: api_key_ids - in: query - description: Return only usage for these API keys. - required: false - schema: - type: array - items: - type: string - - name: models - in: query - description: Return only usage for these models. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: >- - Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, - `api_key_id`, `model` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - user_id - - api_key_id - - model - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Audio transcriptions - group: usage-audio-transcriptions - returns: >- - A list of paginated, time bucketed [Audio transcriptions - usage](https://platform.openai.com/docs/api-reference/usage/audio_transcriptions_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.audio_transcriptions.result", - "seconds": 20, - "num_model_requests": 1, - "project_id": null, - "user_id": null, - "api_key_id": null, - "model": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: > - curl - "https://api.openai.com/v1/organization/usage/audio_transcriptions?start_time=1730419200&limit=1" - \ - - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - - -H "Content-Type: application/json" - description: Get audio transcriptions usage details for the organization. - /organization/usage/code_interpreter_sessions: - get: - summary: Code interpreter sessions - operationId: usage-code-interpreter-sessions - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: Group the usage data by the specified fields. Support fields include `project_id`. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Code interpreter sessions - group: usage-code-interpreter-sessions - returns: >- - A list of paginated, time bucketed [Code interpreter sessions - usage](https://platform.openai.com/docs/api-reference/usage/code_interpreter_sessions_object) - objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.code_interpreter_sessions.result", - "num_sessions": 1, - "project_id": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: > - curl - "https://api.openai.com/v1/organization/usage/code_interpreter_sessions?start_time=1730419200&limit=1" - \ - - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - - -H "Content-Type: application/json" - description: Get code interpreter sessions usage details for the organization. - /organization/usage/completions: - get: - summary: Completions - operationId: usage-completions - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: user_ids - in: query - description: Return only usage for these users. - required: false - schema: - type: array - items: - type: string - - name: api_key_ids - in: query - description: Return only usage for these API keys. - required: false - schema: - type: array - items: - type: string - - name: models - in: query - description: Return only usage for these models. - required: false - schema: - type: array - items: - type: string - - name: batch - in: query - description: > - If `true`, return batch jobs only. If `false`, return non-batch jobs only. By default, return - both. - required: false - schema: - type: boolean - - name: group_by - in: query - description: >- - Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, - `api_key_id`, `model`, `batch`, `service_tier` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - user_id - - api_key_id - - model - - batch - - service_tier - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Completions - group: usage-completions - returns: >- - A list of paginated, time bucketed [Completions - usage](https://platform.openai.com/docs/api-reference/usage/completions_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.completions.result", - "input_tokens": 1000, - "output_tokens": 500, - "input_cached_tokens": 800, - "input_audio_tokens": 0, - "output_audio_tokens": 0, - "num_model_requests": 5, - "project_id": null, - "user_id": null, - "api_key_id": null, - "model": null, - "batch": null, - "service_tier": null - } - ] - } - ], - "has_more": true, - "next_page": "page_AAAAAGdGxdEiJdKOAAAAAGcqsYA=" - } - request: - curl: | - curl "https://api.openai.com/v1/organization/usage/completions?start_time=1730419200&limit=1" \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Get completions usage details for the organization. - /organization/usage/embeddings: - get: - summary: Embeddings - operationId: usage-embeddings - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: user_ids - in: query - description: Return only usage for these users. - required: false - schema: - type: array - items: - type: string - - name: api_key_ids - in: query - description: Return only usage for these API keys. - required: false - schema: - type: array - items: - type: string - - name: models - in: query - description: Return only usage for these models. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: >- - Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, - `api_key_id`, `model` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - user_id - - api_key_id - - model - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Embeddings - group: usage-embeddings - returns: >- - A list of paginated, time bucketed [Embeddings - usage](https://platform.openai.com/docs/api-reference/usage/embeddings_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.embeddings.result", - "input_tokens": 16, - "num_model_requests": 2, - "project_id": null, - "user_id": null, - "api_key_id": null, - "model": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: | - curl "https://api.openai.com/v1/organization/usage/embeddings?start_time=1730419200&limit=1" \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Get embeddings usage details for the organization. - /organization/usage/images: - get: - summary: Images - operationId: usage-images - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: sources - in: query - description: >- - Return only usages for these sources. Possible values are `image.generation`, `image.edit`, - `image.variation` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - image.generation - - image.edit - - image.variation - - name: sizes - in: query - description: >- - Return only usages for these image sizes. Possible values are `256x256`, `512x512`, `1024x1024`, - `1792x1792`, `1024x1792` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - 256x256 - - 512x512 - - 1024x1024 - - 1792x1792 - - 1024x1792 - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: user_ids - in: query - description: Return only usage for these users. - required: false - schema: - type: array - items: - type: string - - name: api_key_ids - in: query - description: Return only usage for these API keys. - required: false - schema: - type: array - items: - type: string - - name: models - in: query - description: Return only usage for these models. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: >- - Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, - `api_key_id`, `model`, `size`, `source` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - user_id - - api_key_id - - model - - size - - source - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Images - group: usage-images - returns: >- - A list of paginated, time bucketed [Images - usage](https://platform.openai.com/docs/api-reference/usage/images_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.images.result", - "images": 2, - "num_model_requests": 2, - "size": null, - "source": null, - "project_id": null, - "user_id": null, - "api_key_id": null, - "model": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: | - curl "https://api.openai.com/v1/organization/usage/images?start_time=1730419200&limit=1" \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Get images usage details for the organization. - /organization/usage/moderations: - get: - summary: Moderations - operationId: usage-moderations - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: user_ids - in: query - description: Return only usage for these users. - required: false - schema: - type: array - items: - type: string - - name: api_key_ids - in: query - description: Return only usage for these API keys. - required: false - schema: - type: array - items: - type: string - - name: models - in: query - description: Return only usage for these models. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: >- - Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, - `api_key_id`, `model` or any combination of them. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - user_id - - api_key_id - - model - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Moderations - group: usage-moderations - returns: >- - A list of paginated, time bucketed [Moderations - usage](https://platform.openai.com/docs/api-reference/usage/moderations_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.moderations.result", - "input_tokens": 16, - "num_model_requests": 2, - "project_id": null, - "user_id": null, - "api_key_id": null, - "model": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: | - curl "https://api.openai.com/v1/organization/usage/moderations?start_time=1730419200&limit=1" \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Get moderations usage details for the organization. - /organization/usage/vector_stores: - get: - summary: Vector stores - operationId: usage-vector-stores - tags: - - Usage - parameters: - - name: start_time - in: query - description: Start time (Unix seconds) of the query time range, inclusive. - required: true - schema: - type: integer - - name: end_time - in: query - description: End time (Unix seconds) of the query time range, exclusive. - required: false - schema: - type: integer - - name: bucket_width - in: query - description: >- - Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to - `1d`. - required: false - schema: - type: string - enum: - - 1m - - 1h - - 1d - default: 1d - - name: project_ids - in: query - description: Return only usage for these projects. - required: false - schema: - type: array - items: - type: string - - name: group_by - in: query - description: Group the usage data by the specified fields. Support fields include `project_id`. - required: false - schema: - type: array - items: - type: string - enum: - - project_id - - name: limit - in: query - description: | - Specifies the number of buckets to return. - - `bucket_width=1d`: default: 7, max: 31 - - `bucket_width=1h`: default: 24, max: 168 - - `bucket_width=1m`: default: 60, max: 1440 - required: false - schema: - type: integer - - name: page - in: query - description: A cursor for use in pagination. Corresponding to the `next_page` field from the previous response. - schema: - type: string - responses: - '200': - description: Usage data retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UsageResponse' - x-oaiMeta: - name: Vector stores - group: usage-vector-stores - returns: >- - A list of paginated, time bucketed [Vector stores - usage](https://platform.openai.com/docs/api-reference/usage/vector_stores_object) objects. - examples: - response: | - { - "object": "page", - "data": [ - { - "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, - "results": [ - { - "object": "organization.usage.vector_stores.result", - "usage_bytes": 1024, - "project_id": null - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: > - curl "https://api.openai.com/v1/organization/usage/vector_stores?start_time=1730419200&limit=1" - \ - - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - - -H "Content-Type: application/json" - description: Get vector stores usage details for the organization. - /organization/users: - get: - summary: List users - operationId: list-users - tags: - - Users - parameters: - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - required: false - schema: - type: string - - name: emails - in: query - description: Filter by the email address of users. - required: false - schema: - type: array - items: - type: string - responses: - '200': - description: Users listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UserListResponse' - x-oaiMeta: - name: List users - group: administration - returns: A list of [User](https://platform.openai.com/docs/api-reference/users/object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "object": "organization.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - ], - "first_id": "user-abc", - "last_id": "user-xyz", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/organization/users?after=user_abc&limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Lists all of the users in the organization. - /organization/users/{user_id}: - get: - summary: Retrieve user - operationId: retrieve-user - tags: - - Users - parameters: - - name: user_id - in: path - description: The ID of the user. - required: true - schema: - type: string - responses: - '200': - description: User retrieved successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/User' - x-oaiMeta: - name: Retrieve user - group: administration - returns: >- - The [User](https://platform.openai.com/docs/api-reference/users/object) object matching the - specified ID. - examples: - response: | - { - "object": "organization.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - request: - curl: | - curl https://api.openai.com/v1/organization/users/user_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Retrieves a user by their identifier. - post: - summary: Modify user - operationId: modify-user - tags: - - Users - parameters: - - name: user_id - in: path - description: The ID of the user. - required: true - schema: - type: string - requestBody: - description: The new user role to modify. This must be one of `owner` or `member`. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/UserRoleUpdateRequest' - responses: - '200': - description: User role updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/User' - x-oaiMeta: - name: Modify user - group: administration - returns: The updated [User](https://platform.openai.com/docs/api-reference/users/object) object. - examples: - response: | - { - "object": "organization.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/users/user_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role": "owner" - }' - description: Modifies a user's role in the organization. - delete: - summary: Delete user - operationId: delete-user - tags: - - Users - parameters: - - name: user_id - in: path - description: The ID of the user. - required: true - schema: - type: string - responses: - '200': - description: User deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UserDeleteResponse' - x-oaiMeta: - name: Delete user - group: administration - returns: Confirmation of the deleted user - examples: - response: | - { - "object": "organization.user.deleted", - "id": "user_abc", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/organization/users/user_abc \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - description: Deletes a user from the organization. - /organization/users/{user_id}/roles: - get: - summary: List user organization role assignments - operationId: list-user-role-assignments - tags: - - User organization role assignments - parameters: - - name: user_id - in: path - description: The ID of the user to inspect. - required: true - schema: - type: string - - name: limit - in: query - description: A limit on the number of organization role assignments to return. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - - name: after - in: query - description: >- - Cursor for pagination. Provide the value from the previous response's `next` field to continue - listing organization roles. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned organization roles. - required: false - schema: - type: string - enum: - - asc - - desc - responses: - '200': - description: User organization role assignments listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RoleListResource' - x-oaiMeta: - name: List user organization role assignments - group: administration - returns: A list of [role objects](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/organization/users/user_abc123/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false, - "description": "Allows managing organization groups", - "created_at": 1711471533, - "updated_at": 1711472599, - "created_by": "user_abc123", - "created_by_user_obj": { - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com" - }, - "metadata": {} - } - ], - "has_more": false, - "next": null - } - description: Lists the organization roles assigned to a user within the organization. - post: - summary: Assign organization role to user - operationId: assign-user-role - tags: - - User organization role assignments - parameters: - - name: user_id - in: path - description: The ID of the user that should receive the organization role. - required: true - schema: - type: string - requestBody: - description: Identifies the organization role to assign to the user. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' - responses: - '200': - description: Organization role assigned to the user successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UserRoleAssignment' - x-oaiMeta: - name: Assign organization role to user - group: administration - returns: >- - The created [user role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/user). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/organization/users/user_abc123/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_id": "role_01J1F8ROLE01" - }' - response: | - { - "object": "user.role", - "user": { - "object": "organization.user", - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com", - "role": "owner", - "added_at": 1711470000 - }, - "role": { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - } - description: Assigns an organization role to a user within the organization. - /organization/users/{user_id}/roles/{role_id}: - delete: - summary: Unassign organization role from user - operationId: unassign-user-role - tags: - - User organization role assignments - parameters: - - name: user_id - in: path - description: The ID of the user to modify. - required: true - schema: - type: string - - name: role_id - in: path - description: The ID of the organization role to remove from the user. - required: true - schema: - type: string - responses: - '200': - description: Organization role unassigned from the user successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedRoleAssignmentResource' - x-oaiMeta: - name: Unassign organization role from user - group: administration - returns: >- - Confirmation of the deleted [user role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/user). - examples: - request: - curl: > - curl -X DELETE https://api.openai.com/v1/organization/users/user_abc123/roles/role_01J1F8ROLE01 - \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "user.role.deleted", - "deleted": true - } - description: Unassigns an organization role from a user within the organization. - /projects/{project_id}/groups/{group_id}/roles: - get: - summary: List project group role assignments - operationId: list-project-group-role-assignments - tags: - - Project group role assignments - parameters: - - name: project_id - in: path - description: The ID of the project to inspect. - required: true - schema: - type: string - - name: group_id - in: path - description: The ID of the group to inspect. - required: true - schema: - type: string - - name: limit - in: query - description: A limit on the number of project role assignments to return. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - - name: after - in: query - description: >- - Cursor for pagination. Provide the value from the previous response's `next` field to continue - listing project roles. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned project roles. - required: false - schema: - type: string - enum: - - asc - - desc - responses: - '200': - description: Project group role assignments listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RoleListResource' - x-oaiMeta: - name: List project group role assignments - group: administration - returns: A list of [role objects](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/projects/proj_abc123/groups/group_01J1F8ABCDXYZ/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false, - "description": "Allows managing API keys for the project", - "created_at": 1711471533, - "updated_at": 1711472599, - "created_by": "user_abc123", - "created_by_user_obj": { - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com" - }, - "metadata": {} - } - ], - "has_more": false, - "next": null - } - description: Lists the project roles assigned to a group within a project. - post: - summary: Assign project role to group - operationId: assign-project-group-role - tags: - - Project group role assignments - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - - name: group_id - in: path - description: The ID of the group that should receive the project role. - required: true - schema: - type: string - requestBody: - description: Identifies the project role to assign to the group. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' - responses: - '200': - description: Project role assigned to the group successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/GroupRoleAssignment' - x-oaiMeta: - name: Assign project role to group - group: administration - returns: >- - The created [group role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/group). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/projects/proj_abc123/groups/group_01J1F8ABCDXYZ/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_id": "role_01J1F8PROJ" - }' - response: | - { - "object": "group.role", - "group": { - "object": "group", - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "scim_managed": false - }, - "role": { - "object": "role", - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "description": "Allows managing API keys for the project", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false - } - } - description: Assigns a project role to a group within a project. - /projects/{project_id}/groups/{group_id}/roles/{role_id}: - delete: - summary: Unassign project role from group - operationId: unassign-project-group-role - tags: - - Project group role assignments - parameters: - - name: project_id - in: path - description: The ID of the project to modify. - required: true - schema: - type: string - - name: group_id - in: path - description: The ID of the group whose project role assignment should be removed. - required: true - schema: - type: string - - name: role_id - in: path - description: The ID of the project role to remove from the group. - required: true - schema: - type: string - responses: - '200': - description: Project role unassigned from the group successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedRoleAssignmentResource' - x-oaiMeta: - name: Unassign project role from group - group: administration - returns: >- - Confirmation of the deleted [group role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/group). - examples: - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/projects/proj_abc123/groups/group_01J1F8ABCDXYZ/roles/role_01J1F8PROJ - \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "group.role.deleted", - "deleted": true - } - description: Unassigns a project role from a group within a project. - /projects/{project_id}/roles: - get: - summary: List project roles - operationId: list-project-roles - tags: - - Roles - parameters: - - name: project_id - in: path - description: The ID of the project to inspect. - required: true - schema: - type: string - - name: limit - in: query - description: A limit on the number of roles to return. Defaults to 1000. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - default: 1000 - - name: after - in: query - description: >- - Cursor for pagination. Provide the value from the previous response's `next` field to continue - listing roles. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned roles. - required: false - schema: - type: string - enum: - - asc - - desc - default: asc - responses: - '200': - description: Project roles listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/PublicRoleListResource' - x-oaiMeta: - name: List project roles - group: administration - returns: >- - A list of [role objects](https://platform.openai.com/docs/api-reference/roles/object) configured on - the project. - examples: - request: - curl: | - curl https://api.openai.com/v1/projects/proj_abc123/roles?limit=20 \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "object": "role", - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "description": "Allows managing API keys for the project", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false - } - ], - "has_more": false, - "next": null - } - description: Lists the roles configured for a project. - post: - summary: Create project role - operationId: create-project-role - tags: - - Roles - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - requestBody: - description: Parameters for the project role you want to create. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicCreateOrganizationRoleBody' - responses: - '200': - description: Project role created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Role' - x-oaiMeta: - name: Create project role - group: administration - returns: The created [role object](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/projects/proj_abc123/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_name": "API Project Key Manager", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "description": "Allows managing API keys for the project" - }' - response: | - { - "object": "role", - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "description": "Allows managing API keys for the project", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false - } - description: Creates a custom role for a project. - /projects/{project_id}/roles/{role_id}: - post: - summary: Update project role - operationId: update-project-role - tags: - - Roles - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - - name: role_id - in: path - description: The ID of the role to update. - required: true - schema: - type: string - requestBody: - description: Fields to update on the project role. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicUpdateOrganizationRoleBody' - responses: - '200': - description: Project role updated successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/Role' - x-oaiMeta: - name: Update project role - group: administration - returns: The updated [role object](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/projects/proj_abc123/roles/role_01J1F8PROJ \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_name": "API Project Key Manager", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "description": "Allows managing API keys for the project" - }' - response: | - { - "object": "role", - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "description": "Allows managing API keys for the project", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false - } - description: Updates an existing project role. - delete: - summary: Delete project role - operationId: delete-project-role - tags: - - Roles - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - - name: role_id - in: path - description: The ID of the role to delete. - required: true - schema: - type: string - responses: - '200': - description: Project role deleted successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RoleDeletedResource' - x-oaiMeta: - name: Delete project role - group: administration - returns: Confirmation of the deleted role. - examples: - request: - curl: | - curl -X DELETE https://api.openai.com/v1/projects/proj_abc123/roles/role_01J1F8PROJ \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "role.deleted", - "id": "role_01J1F8PROJ", - "deleted": true - } - description: Deletes a custom role from a project. - /projects/{project_id}/users/{user_id}/roles: - get: - summary: List project user role assignments - operationId: list-project-user-role-assignments - tags: - - Project user role assignments - parameters: - - name: project_id - in: path - description: The ID of the project to inspect. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user to inspect. - required: true - schema: - type: string - - name: limit - in: query - description: A limit on the number of project role assignments to return. - required: false - schema: - type: integer - minimum: 0 - maximum: 1000 - - name: after - in: query - description: >- - Cursor for pagination. Provide the value from the previous response's `next` field to continue - listing project roles. - required: false - schema: - type: string - - name: order - in: query - description: Sort order for the returned project roles. - required: false - schema: - type: string - enum: - - asc - - desc - responses: - '200': - description: Project user role assignments listed successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RoleListResource' - x-oaiMeta: - name: List project user role assignments - group: administration - returns: A list of [role objects](https://platform.openai.com/docs/api-reference/roles/object). - examples: - request: - curl: | - curl https://api.openai.com/v1/projects/proj_abc123/users/user_abc123/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "list", - "data": [ - { - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false, - "description": "Allows managing API keys for the project", - "created_at": 1711471533, - "updated_at": 1711472599, - "created_by": "user_abc123", - "created_by_user_obj": { - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com" - }, - "metadata": {} - } - ], - "has_more": false, - "next": null - } - description: Lists the project roles assigned to a user within a project. - post: - summary: Assign project role to user - operationId: assign-project-user-role - tags: - - Project user role assignments - parameters: - - name: project_id - in: path - description: The ID of the project to update. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user that should receive the project role. - required: true - schema: - type: string - requestBody: - description: Identifies the project role to assign to the user. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' - responses: - '200': - description: Project role assigned to the user successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/UserRoleAssignment' - x-oaiMeta: - name: Assign project role to user - group: administration - returns: >- - The created [user role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/user). - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/projects/proj_abc123/users/user_abc123/roles \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "role_id": "role_01J1F8PROJ" - }' - response: | - { - "object": "user.role", - "user": { - "object": "organization.user", - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com", - "role": "owner", - "added_at": 1711470000 - }, - "role": { - "object": "role", - "id": "role_01J1F8PROJ", - "name": "API Project Key Manager", - "description": "Allows managing API keys for the project", - "permissions": [ - "api.organization.projects.api_keys.read", - "api.organization.projects.api_keys.write" - ], - "resource_type": "api.project", - "predefined_role": false - } - } - description: Assigns a project role to a user within a project. - /projects/{project_id}/users/{user_id}/roles/{role_id}: - delete: - summary: Unassign project role from user - operationId: unassign-project-user-role - tags: - - Project user role assignments - parameters: - - name: project_id - in: path - description: The ID of the project to modify. - required: true - schema: - type: string - - name: user_id - in: path - description: The ID of the user whose project role assignment should be removed. - required: true - schema: - type: string - - name: role_id - in: path - description: The ID of the project role to remove from the user. - required: true - schema: - type: string - responses: - '200': - description: Project role unassigned from the user successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedRoleAssignmentResource' - x-oaiMeta: - name: Unassign project role from user - group: administration - returns: >- - Confirmation of the deleted [user role - object](https://platform.openai.com/docs/api-reference/role-assignments/objects/user). - examples: - request: - curl: > - curl -X DELETE - https://api.openai.com/v1/projects/proj_abc123/users/user_abc123/roles/role_01J1F8PROJ \ - -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ - -H "Content-Type: application/json" - response: | - { - "object": "user.role.deleted", - "deleted": true - } - description: Unassigns a project role from a user within a project. - /realtime/calls: - post: - summary: Create call - operationId: create-realtime-call - tags: - - Realtime - requestBody: - required: true - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/RealtimeCallCreateRequest' - encoding: - sdp: - contentType: application/sdp - session: - contentType: application/json - application/sdp: - schema: - type: string - description: |- - WebRTC SDP offer. Use this variant when you have previously created an - ephemeral **session token** and are authenticating the request with it. - Realtime session parameters will be retrieved from the session token. - responses: - '201': - description: Realtime call created successfully. - headers: - Location: - description: Relative URL containing the call ID for subsequent control requests. - schema: - type: string - content: - application/sdp: - schema: - type: string - description: SDP answer produced by OpenAI for the peer connection. - x-oaiMeta: - name: Create call - group: realtime - returns: |- - Returns `201 Created` with the SDP answer in the response body. The - `Location` response header includes the call ID for follow-up requests, - e.g., establishing a monitoring WebSocket or hanging up the call. - examples: - response: >- - v=0 - - o=- 4227147428 1719357865 IN IP4 127.0.0.1 - - s=- - - c=IN IP4 0.0.0.0 - - t=0 0 - - a=group:BUNDLE 0 1 - - a=msid-semantic:WMS * - - a=fingerprint:sha-256 - CA:92:52:51:B4:91:3B:34:DD:9C:0B:FB:76:19:7E:3B:F1:21:0F:32:2C:38:01:72:5D:3F:78:C7:5F:8B:C7:36 - - m=audio 9 UDP/TLS/RTP/SAVPF 111 0 8 - - a=mid:0 - - a=ice-ufrag:kZ2qkHXX/u11 - - a=ice-pwd:uoD16Di5OGx3VbqgA3ymjEQV2kwiOjw6 - - a=setup:active - - a=rtcp-mux - - a=rtpmap:111 opus/48000/2 - - a=candidate:993865896 1 udp 2130706431 4.155.146.196 3478 typ host ufrag kZ2qkHXX/u11 - - a=candidate:1432411780 1 tcp 1671430143 4.155.146.196 443 typ host tcptype passive ufrag - kZ2qkHXX/u11 - - m=application 9 UDP/DTLS/SCTP webrtc-datachannel - - a=mid:1 - - a=sctp-port:5000 - request: - curl: |- - curl -X POST https://api.openai.com/v1/realtime/calls \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F "sdp=- - The identifier for the call provided in the - - [`realtime.call.incoming`](https://platform.openai.com/docs/api-reference/webhook-events/realtime/call/incoming) - - webhook. - requestBody: - required: true - description: Session configuration to apply before the caller is bridged to the model. - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' - responses: - '200': - description: Call accepted successfully. - x-oaiMeta: - name: Accept call - group: realtime-calls - returns: |- - Returns `200 OK` once OpenAI starts ringing the SIP leg with the supplied - session configuration. - examples: - response: '' - request: - curl: |- - curl -X POST https://api.openai.com/v1/realtime/calls/$CALL_ID/accept \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "type": "realtime", - "model": "gpt-realtime", - "instructions": "You are Alex, a friendly concierge for Example Corp.", - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.realtime.calls.accept('call_id', { type: 'realtime' }); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - client.realtime.calls.accept( - call_id="call_id", - type="realtime", - ) - go: | - package main - - import ( - "context" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/realtime" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Realtime.Calls.Accept( - context.TODO(), - "call_id", - realtime.CallAcceptParams{ - RealtimeSessionCreateRequest: realtime.RealtimeSessionCreateRequestParam{ - - }, - }, - ) - if err != nil { - panic(err.Error()) - } - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.realtime.RealtimeSessionCreateRequest; - import com.openai.models.realtime.calls.CallAcceptParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - CallAcceptParams params = CallAcceptParams.builder() - .callId("call_id") - .realtimeSessionCreateRequest(RealtimeSessionCreateRequest.builder().build()) - .build(); - client.realtime().calls().accept(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - result = openai.realtime.calls.accept("call_id", type: :realtime) - - puts(result) - description: |- - Accept an incoming SIP call and configure the realtime session that will - handle it. - /realtime/calls/{call_id}/hangup: - post: - summary: Hang up call - operationId: hangup-realtime-call - tags: - - Realtime - parameters: - - in: path - name: call_id - required: true - schema: - type: string - description: >- - The identifier for the call. For SIP calls, use the value provided in the - - [`realtime.call.incoming`](https://platform.openai.com/docs/api-reference/webhook-events/realtime/call/incoming) - - webhook. For WebRTC sessions, reuse the call ID returned in the `Location` - - header when creating the call with - - [`POST /v1/realtime/calls`](https://platform.openai.com/docs/api-reference/realtime/create-call). - responses: - '200': - description: Call hangup initiated successfully. - x-oaiMeta: - name: Hang up call - group: realtime-calls - returns: Returns `200 OK` when OpenAI begins terminating the realtime call. - examples: - response: '' - request: - curl: |- - curl -X POST https://api.openai.com/v1/realtime/calls/$CALL_ID/hangup \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.realtime.calls.hangup('call_id'); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - client.realtime.calls.hangup( - "call_id", - ) - go: | - package main - - import ( - "context" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Realtime.Calls.Hangup(context.TODO(), "call_id") - if err != nil { - panic(err.Error()) - } - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.realtime.calls.CallHangupParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - client.realtime().calls().hangup("call_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - result = openai.realtime.calls.hangup("call_id") - - puts(result) - description: |- - End an active Realtime API call, whether it was initiated over SIP or - WebRTC. - /realtime/calls/{call_id}/refer: - post: - summary: Refer call - operationId: refer-realtime-call - tags: - - Realtime - parameters: - - in: path - name: call_id - required: true - schema: - type: string - description: >- - The identifier for the call provided in the - - [`realtime.call.incoming`](https://platform.openai.com/docs/api-reference/webhook-events/realtime/call/incoming) - - webhook. - requestBody: - required: true - description: Destination URI for the REFER request. - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeCallReferRequest' - responses: - '200': - description: Call referred successfully. - x-oaiMeta: - name: Refer call - group: realtime-calls - returns: Returns `200 OK` once the REFER is handed off to your SIP provider. - examples: - response: '' - request: - curl: |- - curl -X POST https://api.openai.com/v1/realtime/calls/$CALL_ID/refer \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"target_uri": "tel:+14155550123"}' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.realtime.calls.refer('call_id', { target_uri: 'tel:+14155550123' }); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - client.realtime.calls.refer( - call_id="call_id", - target_uri="tel:+14155550123", - ) - go: | - package main - - import ( - "context" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/realtime" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Realtime.Calls.Refer( - context.TODO(), - "call_id", - realtime.CallReferParams{ - TargetUri: "tel:+14155550123", - }, - ) - if err != nil { - panic(err.Error()) - } - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.realtime.calls.CallReferParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - CallReferParams params = CallReferParams.builder() - .callId("call_id") - .targetUri("tel:+14155550123") - .build(); - client.realtime().calls().refer(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - result = openai.realtime.calls.refer("call_id", target_uri: "tel:+14155550123") - - puts(result) - description: Transfer an active SIP call to a new destination using the SIP REFER verb. - /realtime/calls/{call_id}/reject: - post: - summary: Reject call - operationId: reject-realtime-call - tags: - - Realtime - parameters: - - in: path - name: call_id - required: true - schema: - type: string - description: >- - The identifier for the call provided in the - - [`realtime.call.incoming`](https://platform.openai.com/docs/api-reference/webhook-events/realtime/call/incoming) - - webhook. - requestBody: - required: false - description: |- - Provide an optional SIP status code. When omitted the API responds with - `603 Decline`. - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeCallRejectRequest' - responses: - '200': - description: Call rejected successfully. - x-oaiMeta: - name: Reject call - group: realtime-calls - returns: Returns `200 OK` after OpenAI sends the SIP status code to the caller. - examples: - response: '' - request: - curl: |- - curl -X POST https://api.openai.com/v1/realtime/calls/$CALL_ID/reject \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"status_code": 486}' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.realtime.calls.reject('call_id'); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - client.realtime.calls.reject( - call_id="call_id", - ) - go: | - package main - - import ( - "context" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/realtime" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Realtime.Calls.Reject( - context.TODO(), - "call_id", - realtime.CallRejectParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.realtime.calls.CallRejectParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - client.realtime().calls().reject("call_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - result = openai.realtime.calls.reject("call_id") - - puts(result) - description: Decline an incoming SIP call by returning a SIP status code to the caller. - /realtime/client_secrets: - post: - summary: Create client secret - operationId: create-realtime-client-secret - tags: - - Realtime - requestBody: - description: Create a client secret with the given session configuration. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeCreateClientSecretRequest' - responses: - '200': - description: Client secret created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeCreateClientSecretResponse' - x-oaiMeta: - name: Create client secret - group: realtime - returns: >- - The created client secret and the effective session object. The client secret is a string that looks - like `ek_1234`. - examples: - response: | - { - "value": "ek_68af296e8e408191a1120ab6383263c2", - "expires_at": 1756310470, - "session": { - "type": "realtime", - "object": "realtime.session", - "id": "sess_C9CiUVUzUzYIssh3ELY1d", - "model": "gpt-realtime", - "output_modalities": [ - "audio" - ], - "instructions": "You are a friendly assistant.", - "tools": [], - "tool_choice": "auto", - "max_output_tokens": "inf", - "tracing": null, - "truncation": "auto", - "prompt": null, - "expires_at": 0, - "audio": { - "input": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "transcription": null, - "noise_reduction": null, - "turn_detection": { - "type": "server_vad", - } - }, - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "alloy", - "speed": 1.0 - } - }, - "include": null - } - } - request: - curl: | - curl -X POST https://api.openai.com/v1/realtime/client_secrets \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "expires_after": { - "anchor": "created_at", - "seconds": 600 - }, - "session": { - "type": "realtime", - "model": "gpt-realtime", - "instructions": "You are a friendly assistant." - } - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const clientSecret = await client.realtime.clientSecrets.create(); - - console.log(clientSecret.expires_at); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - client_secret = client.realtime.client_secrets.create() - print(client_secret.expires_at) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/realtime" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - clientSecret, err := client.Realtime.ClientSecrets.New(context.TODO(), realtime.ClientSecretNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", clientSecret.ExpiresAt) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.realtime.clientsecrets.ClientSecretCreateParams; - import com.openai.models.realtime.clientsecrets.ClientSecretCreateResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ClientSecretCreateResponse clientSecret = client.realtime().clientSecrets().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - client_secret = openai.realtime.client_secrets.create - - puts(client_secret) - description: | - Create a Realtime client secret with an associated session configuration. - /realtime/sessions: - post: - summary: Create session - operationId: create-realtime-session - tags: - - Realtime - requestBody: - description: Create an ephemeral API key with the given session configuration. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeSessionCreateRequest' - responses: - '200': - description: Session created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeSessionCreateResponse' - x-oaiMeta: - name: Create session - group: realtime - returns: The created Realtime session object, plus an ephemeral key - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/realtime/sessions \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "model": "gpt-realtime", - "modalities": ["audio", "text"], - "instructions": "You are a friendly assistant." - }' - response: | - { - "id": "sess_001", - "object": "realtime.session", - "model": "gpt-realtime-2025-08-25", - "modalities": ["audio", "text"], - "instructions": "You are a friendly assistant.", - "voice": "alloy", - "input_audio_format": "pcm16", - "output_audio_format": "pcm16", - "input_audio_transcription": { - "model": "whisper-1" - }, - "turn_detection": null, - "tools": [], - "tool_choice": "none", - "temperature": 0.7, - "max_response_output_tokens": 200, - "speed": 1.1, - "tracing": "auto", - "client_secret": { - "value": "ek_abc123", - "expires_at": 1234567890 - } - } - description: | - Create an ephemeral API token for use in client-side applications with the - Realtime API. Can be configured with the same session parameters as the - `session.update` client event. - - It responds with a session object, plus a `client_secret` key which contains - a usable ephemeral API token that can be used to authenticate browser clients - for the Realtime API. - /realtime/transcription_sessions: - post: - summary: Create transcription session - operationId: create-realtime-transcription-session - tags: - - Realtime - requestBody: - description: Create an ephemeral API key with the given session configuration. - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' - responses: - '200': - description: Session created successfully. - content: - application/json: - schema: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' - x-oaiMeta: - name: Create transcription session - group: realtime - returns: >- - The created [Realtime transcription session - object](https://platform.openai.com/docs/api-reference/realtime-sessions/transcription_session_object), - plus an ephemeral key - examples: - request: - curl: | - curl -X POST https://api.openai.com/v1/realtime/transcription_sessions \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{}' - response: | - { - "id": "sess_BBwZc7cFV3XizEyKGDCGL", - "object": "realtime.transcription_session", - "modalities": ["audio", "text"], - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200 - }, - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "language": null, - "prompt": "" - }, - "client_secret": null - } - description: | - Create an ephemeral API token for use in client-side applications with the - Realtime API specifically for realtime transcriptions. - Can be configured with the same session parameters as the `transcription_session.update` client event. - - It responds with a session object, plus a `client_secret` key which contains - a usable ephemeral API token that can be used to authenticate browser clients - for the Realtime API. - /responses: - post: - operationId: createResponse - tags: - - Responses - summary: Create a model response - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateResponse' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Response' - text/event-stream: - schema: - $ref: '#/components/schemas/ResponseStreamEvent' - x-oaiMeta: - name: Create a model response - group: responses - returns: | - Returns a [Response](https://platform.openai.com/docs/api-reference/responses/object) object. - path: create - examples: - - title: Text input - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "input": "Tell me a three sentence bedtime story about a unicorn." - }' - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "gpt-4.1", - input: "Tell me a three sentence bedtime story about a unicorn." - }); - - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - csharp: > - using System; - - using OpenAI.Responses; - - - OpenAIResponseClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - - OpenAIResponse response = client.CreateResponse("Tell me a three sentence bedtime story about - a unicorn."); - - - Console.WriteLine(response.GetOutputText()); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b", - "object": "response", - "created_at": 1741476542, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4.1-2025-04-14", - "output": [ - { - "type": "message", - "id": "msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.", - "annotations": [] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 36, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 87, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 123 - }, - "user": null, - "metadata": {} - } - - title: Image input - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "input": [ - { - "role": "user", - "content": [ - {"type": "input_text", "text": "what is in this image?"}, - { - "type": "input_image", - "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" - } - ] - } - ] - }' - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "gpt-4.1", - input: [ - { - role: "user", - content: [ - { type: "input_text", text: "what is in this image?" }, - { - type: "input_image", - image_url: - "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", - }, - ], - }, - ], - }); - - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - csharp: | - using System; - using System.Collections.Generic; - - using OpenAI.Responses; - - OpenAIResponseClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - List inputItems = - [ - ResponseItem.CreateUserMessageItem( - [ - ResponseContentPart.CreateInputTextPart("What is in this image?"), - ResponseContentPart.CreateInputImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) - ] - ) - ]; - - OpenAIResponse response = client.CreateResponse(inputItems); - - Console.WriteLine(response.GetOutputText()); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41", - "object": "response", - "created_at": 1741476777, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4.1-2025-04-14", - "output": [ - { - "type": "message", - "id": "msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.", - "annotations": [] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 328, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 52, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 380 - }, - "user": null, - "metadata": {} - } - - title: File input - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "input": [ - { - "role": "user", - "content": [ - {"type": "input_text", "text": "what is in this file?"}, - { - "type": "input_file", - "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf" - } - ] - } - ] - }' - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "gpt-4.1", - input: [ - { - role: "user", - content: [ - { type: "input_text", text: "what is in this file?" }, - { - type: "input_file", - file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf", - }, - ], - }, - ], - }); - - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_686eef60237881a2bd1180bb8b13de430e34c516d176ff86", - "object": "response", - "created_at": 1752100704, - "status": "completed", - "background": false, - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "max_tool_calls": null, - "model": "gpt-4.1-2025-04-14", - "output": [ - { - "id": "msg_686eef60d3e081a29283bdcbc4322fd90e34c516d176ff86", - "type": "message", - "status": "completed", - "content": [ - { - "type": "output_text", - "annotations": [], - "logprobs": [], - "text": "The file seems to contain excerpts from a letter to the shareholders of Berkshire Hathaway Inc., likely written by Warren Buffett. It covers several topics:\n\n1. **Communication Philosophy**: Buffett emphasizes the importance of transparency and candidness in reporting mistakes and successes to shareholders.\n\n2. **Mistakes and Learnings**: The letter acknowledges past mistakes in business assessments and management hires, highlighting the importance of correcting errors promptly.\n\n3. **CEO Succession**: Mention of Greg Abel stepping in as the new CEO and continuing the tradition of honest communication.\n\n4. **Pete Liegl Story**: A detailed account of acquiring Forest River and the relationship with its founder, highlighting trust and effective business decisions.\n\n5. **2024 Performance**: Overview of business performance, particularly in insurance and investment activities, with a focus on GEICO's improvement.\n\n6. **Tax Contributions**: Discussion of significant tax payments to the U.S. Treasury, credited to shareholders' reinvestments.\n\n7. **Investment Strategy**: A breakdown of Berkshire\u2019s investments in both controlled subsidiaries and marketable equities, along with a focus on long-term holding strategies.\n\n8. **American Capitalism**: Reflections on America\u2019s economic development and Berkshire\u2019s role within it.\n\n9. **Property-Casualty Insurance**: Insights into the P/C insurance business model and its challenges and benefits.\n\n10. **Japanese Investments**: Information about Berkshire\u2019s investments in Japanese companies and future plans.\n\n11. **Annual Meeting**: Details about the upcoming annual gathering in Omaha, including schedule changes and new book releases.\n\n12. **Personal Anecdotes**: Light-hearted stories about family and interactions, conveying Buffett's personable approach.\n\n13. **Financial Performance Data**: Tables comparing Berkshire\u2019s annual performance to the S&P 500, showing impressive long-term gains.\n\nOverall, the letter reinforces Berkshire Hathaway's commitment to transparency, investment in both its businesses and the wider economy, and emphasizes strong leadership and prudent financial management." - } - ], - "role": "assistant" - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "service_tier": "default", - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_logprobs": 0, - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 8438, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 398, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 8836 - }, - "user": null, - "metadata": {} - } - - title: Web search - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "tools": [{ "type": "web_search_preview" }], - "input": "What was a positive news story from today?" - }' - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "gpt-4.1", - tools: [{ type: "web_search_preview" }], - input: "What was a positive news story from today?", - }); - - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - csharp: | - using System; - - using OpenAI.Responses; - - OpenAIResponseClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - string userInputText = "What was a positive news story from today?"; - - ResponseCreationOptions options = new() - { - Tools = - { - ResponseTool.CreateWebSearchTool() - }, - }; - - OpenAIResponse response = client.CreateResponse(userInputText, options); - - Console.WriteLine(response.GetOutputText()); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_67ccf18ef5fc8190b16dbee19bc54e5f087bb177ab789d5c", - "object": "response", - "created_at": 1741484430, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4.1-2025-04-14", - "output": [ - { - "type": "web_search_call", - "id": "ws_67ccf18f64008190a39b619f4c8455ef087bb177ab789d5c", - "status": "completed" - }, - { - "type": "message", - "id": "msg_67ccf190ca3881909d433c50b1f6357e087bb177ab789d5c", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "As of today, March 9, 2025, one notable positive news story...", - "annotations": [ - { - "type": "url_citation", - "start_index": 442, - "end_index": 557, - "url": "https://.../?utm_source=chatgpt.com", - "title": "..." - }, - { - "type": "url_citation", - "start_index": 962, - "end_index": 1077, - "url": "https://.../?utm_source=chatgpt.com", - "title": "..." - }, - { - "type": "url_citation", - "start_index": 1336, - "end_index": 1451, - "url": "https://.../?utm_source=chatgpt.com", - "title": "..." - } - ] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [ - { - "type": "web_search_preview", - "domains": [], - "search_context_size": "medium", - "user_location": { - "type": "approximate", - "city": null, - "country": "US", - "region": null, - "timezone": null - } - } - ], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 328, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 356, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 684 - }, - "user": null, - "metadata": {} - } - - title: File search - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "tools": [{ - "type": "file_search", - "vector_store_ids": ["vs_1234567890"], - "max_num_results": 20 - }], - "input": "What are the attributes of an ancient brown dragon?" - }' - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "gpt-4.1", - tools: [{ - type: "file_search", - vector_store_ids: ["vs_1234567890"], - max_num_results: 20 - }], - input: "What are the attributes of an ancient brown dragon?", - }); - - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - csharp: | - using System; - - using OpenAI.Responses; - - OpenAIResponseClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - string userInputText = "What are the attributes of an ancient brown dragon?"; - - ResponseCreationOptions options = new() - { - Tools = - { - ResponseTool.CreateFileSearchTool( - vectorStoreIds: ["vs_1234567890"], - maxResultCount: 20 - ) - }, - }; - - OpenAIResponse response = client.CreateResponse(userInputText, options); - - Console.WriteLine(response.GetOutputText()); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_67ccf4c55fc48190b71bd0463ad3306d09504fb6872380d7", - "object": "response", - "created_at": 1741485253, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4.1-2025-04-14", - "output": [ - { - "type": "file_search_call", - "id": "fs_67ccf4c63cd08190887ef6464ba5681609504fb6872380d7", - "status": "completed", - "queries": [ - "attributes of an ancient brown dragon" - ], - "results": null - }, - { - "type": "message", - "id": "msg_67ccf4c93e5c81909d595b369351a9d309504fb6872380d7", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "The attributes of an ancient brown dragon include...", - "annotations": [ - { - "type": "file_citation", - "index": 320, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 576, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 815, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 815, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 1030, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 1030, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 1156, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - }, - { - "type": "file_citation", - "index": 1225, - "file_id": "file-4wDz5b167pAf72nx1h9eiN", - "filename": "dragons.pdf" - } - ] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [ - { - "type": "file_search", - "filters": null, - "max_num_results": 20, - "ranking_options": { - "ranker": "auto", - "score_threshold": 0.0 - }, - "vector_store_ids": [ - "vs_1234567890" - ] - } - ], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 18307, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 348, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 18655 - }, - "user": null, - "metadata": {} - } - - title: Streaming - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "instructions": "You are a helpful assistant.", - "input": "Hello!", - "stream": true - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "gpt-4.1", - instructions: "You are a helpful assistant.", - input: "Hello!", - stream: true, - }); - - for await (const event of response) { - console.log(event); - } - csharp: > - using System; - - using System.ClientModel; - - using System.Threading.Tasks; - - - using OpenAI.Responses; - - - OpenAIResponseClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - - string userInputText = "Hello!"; - - - ResponseCreationOptions options = new() - - { - Instructions = "You are a helpful assistant.", - }; - - - AsyncCollectionResult responseUpdates = - client.CreateResponseStreamingAsync(userInputText, options); - - - await foreach (StreamingResponseUpdate responseUpdate in responseUpdates) - - { - if (responseUpdate is StreamingResponseOutputTextDeltaUpdate outputTextDeltaUpdate) - { - Console.Write(outputTextDeltaUpdate.Delta); - } - } - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: > - event: response.created - - data: - {"type":"response.created","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You - are a helpful - assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}} - - - event: response.in_progress - - data: - {"type":"response.in_progress","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You - are a helpful - assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}} - - - event: response.output_item.added - - data: - {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"in_progress","role":"assistant","content":[]}} - - - event: response.content_part.added - - data: - {"type":"response.content_part.added","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}} - - - event: response.output_text.delta - - data: - {"type":"response.output_text.delta","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"delta":"Hi"} - - - ... - - - event: response.output_text.done - - data: - {"type":"response.output_text.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"text":"Hi - there! How can I assist you today?"} - - - event: response.content_part.done - - data: - {"type":"response.content_part.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Hi - there! How can I assist you today?","annotations":[]}} - - - event: response.output_item.done - - data: - {"type":"response.output_item.done","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi - there! How can I assist you today?","annotations":[]}]}} - - - event: response.completed - - data: - {"type":"response.completed","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"completed","error":null,"incomplete_details":null,"instructions":"You - are a helpful - assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi - there! How can I assist you - today?","annotations":[]}]}],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":{"input_tokens":37,"output_tokens":11,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":48},"user":null,"metadata":{}}} - - title: Functions - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-4.1", - "input": "What is the weather like in Boston today?", - "tools": [ - { - "type": "function", - "name": "get_current_weather", - "description": "Get the current weather in a given location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"] - } - }, - "required": ["location", "unit"] - } - } - ], - "tool_choice": "auto" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - javascript: | - import OpenAI from "openai"; - - const openai = new OpenAI(); - - const tools = [ - { - type: "function", - name: "get_current_weather", - description: "Get the current weather in a given location", - parameters: { - type: "object", - properties: { - location: { - type: "string", - description: "The city and state, e.g. San Francisco, CA", - }, - unit: { type: "string", enum: ["celsius", "fahrenheit"] }, - }, - required: ["location", "unit"], - }, - }, - ]; - - const response = await openai.responses.create({ - model: "gpt-4.1", - tools: tools, - input: "What is the weather like in Boston today?", - tool_choice: "auto", - }); - - console.log(response); - csharp: | - using System; - using OpenAI.Responses; - - OpenAIResponseClient client = new( - model: "gpt-4.1", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - ResponseTool getCurrentWeatherFunctionTool = ResponseTool.CreateFunctionTool( - functionName: "get_current_weather", - functionDescription: "Get the current weather in a given location", - functionParameters: BinaryData.FromString(""" - { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} - }, - "required": ["location", "unit"] - } - """ - ) - ); - - string userInputText = "What is the weather like in Boston today?"; - - ResponseCreationOptions options = new() - { - Tools = - { - getCurrentWeatherFunctionTool - }, - ToolChoice = ResponseToolChoice.CreateAutoChoice(), - }; - - OpenAIResponse response = client.CreateResponse(userInputText, options); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_67ca09c5efe0819096d0511c92b8c890096610f474011cc0", - "object": "response", - "created_at": 1741294021, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4.1-2025-04-14", - "output": [ - { - "type": "function_call", - "id": "fc_67ca09c6bedc8190a7abfec07b1a1332096610f474011cc0", - "call_id": "call_unLAR8MvFNptuiZK6K6HCy5k", - "name": "get_current_weather", - "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}", - "status": "completed" - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [ - { - "type": "function", - "description": "Get the current weather in a given location", - "name": "get_current_weather", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": [ - "celsius", - "fahrenheit" - ] - } - }, - "required": [ - "location", - "unit" - ] - }, - "strict": true - } - ], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 291, - "output_tokens": 23, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 314 - }, - "user": null, - "metadata": {} - } - - title: Reasoning - request: - curl: | - curl https://api.openai.com/v1/responses \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "o3-mini", - "input": "How much wood would a woodchuck chuck?", - "reasoning": { - "effort": "high" - } - }' - javascript: | - import OpenAI from "openai"; - const openai = new OpenAI(); - - const response = await openai.responses.create({ - model: "o3-mini", - input: "How much wood would a woodchuck chuck?", - reasoning: { - effort: "high" - } - }); - - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.create() - print(response.id) - csharp: | - using System; - using OpenAI.Responses; - - OpenAIResponseClient client = new( - model: "o3-mini", - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - string userInputText = "How much wood would a woodchuck chuck?"; - - ResponseCreationOptions options = new() - { - ReasoningOptions = new() - { - ReasoningEffortLevel = ResponseReasoningEffortLevel.High, - }, - }; - - OpenAIResponse response = client.CreateResponse(userInputText, options); - - Console.WriteLine(response.GetOutputText()); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.create(); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.create - - puts(response) - response: | - { - "id": "resp_67ccd7eca01881908ff0b5146584e408072912b2993db808", - "object": "response", - "created_at": 1741477868, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "o1-2024-12-17", - "output": [ - { - "type": "message", - "id": "msg_67ccd7f7b5848190a6f3e95d809f6b44072912b2993db808", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "The classic tongue twister...", - "annotations": [] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": "high", - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 81, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 1035, - "output_tokens_details": { - "reasoning_tokens": 832 - }, - "total_tokens": 1116 - }, - "user": null, - "metadata": {} - } - description: > - Creates a model response. Provide [text](https://platform.openai.com/docs/guides/text) or - - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) - - or [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have the model call - - your own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in - - [tools](https://platform.openai.com/docs/guides/tools) like [web - search](https://platform.openai.com/docs/guides/tools-web-search) - - or [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data - - as input for the model's response. - /responses/{response_id}: - get: - operationId: getResponse - tags: - - Responses - summary: Get a model response - parameters: - - in: path - name: response_id - required: true - schema: - type: string - example: resp_677efb5139a88190b512bc3fef8e535d - description: The ID of the response to retrieve. - - in: query - name: include - schema: - type: array - items: - $ref: '#/components/schemas/IncludeEnum' - description: | - Additional fields to include in the response. See the `include` - parameter for Response creation above for more information. - - in: query - name: stream - schema: - type: boolean - description: > - If set to true, the model response data will be streamed to the client - - as it is generated using [server-sent - events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - - See the [Streaming section - below](https://platform.openai.com/docs/api-reference/responses-streaming) - - for more information. - - in: query - name: starting_after - schema: - type: integer - description: | - The sequence number of the event after which to start streaming. - - in: query - name: include_obfuscation - schema: - type: boolean - description: | - When true, stream obfuscation will be enabled. Stream obfuscation adds - random characters to an `obfuscation` field on streaming delta events - to normalize payload sizes as a mitigation to certain side-channel - attacks. These obfuscation fields are included by default, but add a - small amount of overhead to the data stream. You can set - `include_obfuscation` to false to optimize for bandwidth if you trust - the network links between your application and the OpenAI API. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Response' - x-oaiMeta: - name: Get a model response - group: responses - returns: | - The [Response](https://platform.openai.com/docs/api-reference/responses/object) object matching the - specified ID. - examples: - response: | - { - "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44", - "object": "response", - "created_at": 1741386163, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-2024-08-06", - "output": [ - { - "type": "message", - "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.", - "annotations": [] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 32, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 18, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 50 - }, - "user": null, - "metadata": {} - } - request: - curl: | - curl https://api.openai.com/v1/responses/resp_123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const response = await client.responses.retrieve("resp_123"); - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.retrieve( - response_id="resp_677efb5139a88190b512bc3fef8e535d", - ) - print(response.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.retrieve('resp_677efb5139a88190b512bc3fef8e535d'); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.Get( - context.TODO(), - "resp_677efb5139a88190b512bc3fef8e535d", - responses.ResponseGetParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().retrieve("resp_677efb5139a88190b512bc3fef8e535d"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.retrieve("resp_677efb5139a88190b512bc3fef8e535d") - - puts(response) - description: | - Retrieves a model response with the given ID. - delete: - operationId: deleteResponse - tags: - - Responses - summary: Delete a model response - parameters: - - in: path - name: response_id - required: true - schema: - type: string - example: resp_677efb5139a88190b512bc3fef8e535d - description: The ID of the response to delete. - responses: - '200': - description: OK - '404': - description: Not Found - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - x-oaiMeta: - name: Delete a model response - group: responses - returns: | - A success message. - examples: - response: | - { - "id": "resp_6786a1bec27481909a17d673315b29f6", - "object": "response", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/responses/resp_123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const response = await client.responses.delete("resp_123"); - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - client.responses.delete( - "resp_677efb5139a88190b512bc3fef8e535d", - ) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - await client.responses.delete('resp_677efb5139a88190b512bc3fef8e535d'); - go: | - package main - - import ( - "context" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - err := client.Responses.Delete(context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d") - if err != nil { - panic(err.Error()) - } - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.ResponseDeleteParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - client.responses().delete("resp_677efb5139a88190b512bc3fef8e535d"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - result = openai.responses.delete("resp_677efb5139a88190b512bc3fef8e535d") - - puts(result) - description: | - Deletes a model response with the given ID. - /responses/{response_id}/cancel: - post: - operationId: cancelResponse - tags: - - Responses - summary: Cancel a response - parameters: - - in: path - name: response_id - required: true - schema: - type: string - example: resp_677efb5139a88190b512bc3fef8e535d - description: The ID of the response to cancel. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Response' - '404': - description: Not Found - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - x-oaiMeta: - name: Cancel a response - group: responses - returns: | - A [Response](https://platform.openai.com/docs/api-reference/responses/object) object. - examples: - response: | - { - "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44", - "object": "response", - "created_at": 1741386163, - "status": "completed", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-2024-08-06", - "output": [ - { - "type": "message", - "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.", - "annotations": [] - } - ] - } - ], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1.0, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1.0, - "truncation": "disabled", - "usage": { - "input_tokens": 32, - "input_tokens_details": { - "cached_tokens": 0 - }, - "output_tokens": 18, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 50 - }, - "user": null, - "metadata": {} - } - request: - curl: | - curl -X POST https://api.openai.com/v1/responses/resp_123/cancel \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const response = await client.responses.cancel("resp_123"); - console.log(response); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.cancel( - "resp_677efb5139a88190b512bc3fef8e535d", - ) - print(response.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.cancel('resp_677efb5139a88190b512bc3fef8e535d'); - - console.log(response.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.Cancel(context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.Response; - import com.openai.models.responses.ResponseCancelParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Response response = client.responses().cancel("resp_677efb5139a88190b512bc3fef8e535d"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.cancel("resp_677efb5139a88190b512bc3fef8e535d") - - puts(response) - description: | - Cancels a model response with the given ID. Only responses created with - the `background` parameter set to `true` can be cancelled. - [Learn more](https://platform.openai.com/docs/guides/background). - /responses/{response_id}/input_items: - get: - operationId: listInputItems - tags: - - Responses - summary: List input items - parameters: - - in: path - name: response_id - required: true - schema: - type: string - description: The ID of the response to retrieve input items for. - - name: limit - in: query - description: | - A limit on the number of objects to be returned. Limit can range between - 1 and 100, and the default is 20. - required: false - schema: - type: integer - default: 20 - - in: query - name: order - schema: - type: string - enum: - - asc - - desc - description: | - 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. - - in: query - name: after - schema: - type: string - description: | - An item ID to list items after, used in pagination. - - in: query - name: include - schema: - type: array - items: - $ref: '#/components/schemas/IncludeEnum' - description: | - Additional fields to include in the response. See the `include` - parameter for Response creation above for more information. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ResponseItemList' - x-oaiMeta: - name: List input items - group: responses - returns: A list of input item objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "msg_abc123", - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "Tell me a three sentence bedtime story about a unicorn." - } - ] - } - ], - "first_id": "msg_abc123", - "last_id": "msg_abc123", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/responses/resp_abc123/input_items \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const response = await client.responses.inputItems.list("resp_123"); - console.log(response.data); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.responses.input_items.list( - response_id="response_id", - ) - page = page.data[0] - print(page) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const responseItem of client.responses.inputItems.list('response_id')) { - console.log(responseItem); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Responses.InputItems.List( - context.TODO(), - "response_id", - responses.InputItemListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.inputitems.InputItemListPage; - import com.openai.models.responses.inputitems.InputItemListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - InputItemListPage page = client.responses().inputItems().list("response_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.responses.input_items.list("response_id") - - puts(page) - description: Returns a list of input items for a given response. - /threads: - post: - operationId: createThread - tags: - - Assistants - summary: Create thread - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/CreateThreadRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ThreadObject' - x-oaiMeta: - name: Create thread - group: threads - beta: true - returns: A [thread](https://platform.openai.com/docs/api-reference/threads) object. - examples: - - title: Empty - request: - curl: | - curl https://api.openai.com/v1/threads \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - thread = client.beta.threads.create() - print(thread.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const thread = await client.beta.threads.create(); - - console.log(thread.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", thread.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.Thread; - import com.openai.models.beta.threads.ThreadCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Thread thread = client.beta().threads().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - thread = openai.beta.threads.create - - puts(thread) - response: | - { - "id": "thread_abc123", - "object": "thread", - "created_at": 1699012949, - "metadata": {}, - "tool_resources": {} - } - - title: Messages - request: - curl: | - curl https://api.openai.com/v1/threads \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "messages": [{ - "role": "user", - "content": "Hello, what is AI?" - }, { - "role": "user", - "content": "How does AI work? Explain it in simple terms." - }] - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - thread = client.beta.threads.create() - print(thread.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const thread = await client.beta.threads.create(); - - console.log(thread.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", thread.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.Thread; - import com.openai.models.beta.threads.ThreadCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Thread thread = client.beta().threads().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - thread = openai.beta.threads.create - - puts(thread) - response: | - { - "id": "thread_abc123", - "object": "thread", - "created_at": 1699014083, - "metadata": {}, - "tool_resources": {} - } - description: Create a thread. - /threads/runs: - post: - operationId: createThreadAndRun - tags: - - Assistants - summary: Create thread and run - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateThreadAndRunRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunObject' - x-oaiMeta: - name: Create thread and run - group: threads - beta: true - returns: A [run](https://platform.openai.com/docs/api-reference/runs/object) object. - examples: - - title: Default - request: - curl: | - curl https://api.openai.com/v1/threads/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "assistant_id": "asst_abc123", - "thread": { - "messages": [ - {"role": "user", "content": "Explain deep learning to a 5 year old."} - ] - } - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.create_and_run( - assistant_id="assistant_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{ - AssistantID: "assistant_id", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.ThreadCreateAndRunParams; - import com.openai.models.beta.threads.runs.Run; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() - .assistantId("assistant_id") - .build(); - Run run = client.beta().threads().createAndRun(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.create_and_run(assistant_id: "assistant_id") - - puts(run) - response: | - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1699076792, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "queued", - "started_at": null, - "expires_at": 1699077392, - "cancelled_at": null, - "failed_at": null, - "completed_at": null, - "required_action": null, - "last_error": null, - "model": "gpt-4o", - "instructions": "You are a helpful assistant.", - "tools": [], - "tool_resources": {}, - "metadata": {}, - "temperature": 1.0, - "top_p": 1.0, - "max_completion_tokens": null, - "max_prompt_tokens": null, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "incomplete_details": null, - "usage": null, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - - title: Streaming - request: - curl: | - curl https://api.openai.com/v1/threads/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "assistant_id": "asst_123", - "thread": { - "messages": [ - {"role": "user", "content": "Hello"} - ] - }, - "stream": true - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.create_and_run( - assistant_id="assistant_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{ - AssistantID: "assistant_id", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.ThreadCreateAndRunParams; - import com.openai.models.beta.threads.runs.Run; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() - .assistantId("assistant_id") - .build(); - Run run = client.beta().threads().createAndRun(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.create_and_run(assistant_id: "assistant_id") - - puts(run) - response: > - event: thread.created - - data: {"id":"thread_123","object":"thread","created_at":1710348075,"metadata":{}} - - - event: thread.run.created - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - - - event: thread.run.queued - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - - - event: thread.run.in_progress - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - - - event: thread.run.step.created - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - - - event: thread.run.step.in_progress - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - - - event: thread.message.created - - data: - {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], - "metadata":{}} - - - event: thread.message.in_progress - - data: - {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], - "metadata":{}} - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} - - - ... - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" - today"}}]}} - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} - - - event: thread.message.completed - - data: - {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! - How can I assist you today?","annotations":[]}}], "metadata":{}} - - - event: thread.run.step.completed - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} - - - event: thread.run.completed - - {"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} - - - event: done - - data: [DONE] - - title: Streaming with Functions - request: - curl: | - curl https://api.openai.com/v1/threads/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "assistant_id": "asst_abc123", - "thread": { - "messages": [ - {"role": "user", "content": "What is the weather like in San Francisco?"} - ] - }, - "tools": [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather in a given location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"] - } - }, - "required": ["location"] - } - } - } - ], - "stream": true - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.create_and_run( - assistant_id="assistant_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{ - AssistantID: "assistant_id", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.ThreadCreateAndRunParams; - import com.openai.models.beta.threads.runs.Run; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() - .assistantId("assistant_id") - .build(); - Run run = client.beta().threads().createAndRun(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.create_and_run(assistant_id: "assistant_id") - - puts(run) - response: > - event: thread.created - - data: {"id":"thread_123","object":"thread","created_at":1710351818,"metadata":{}} - - - event: thread.run.created - - data: - {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.queued - - data: - {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.in_progress - - data: - {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.step.created - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} - - - event: thread.run.step.in_progress - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} - - - event: thread.run.step.delta - - data: - {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"","output":null}}]}}} - - - event: thread.run.step.delta - - data: - {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"{\""}}]}}} - - - event: thread.run.step.delta - - data: - {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"location"}}]}}} - - - ... - - - event: thread.run.step.delta - - data: - {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"ahrenheit"}}]}}} - - - event: thread.run.step.delta - - data: - {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"\"}"}}]}}} - - - event: thread.run.requires_action - - data: - {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San - Francisco, - CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: done - - data: [DONE] - description: Create a thread and run it in one request. - /threads/{thread_id}: - get: - operationId: getThread - tags: - - Assistants - summary: Retrieve thread - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to retrieve. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ThreadObject' - x-oaiMeta: - name: Retrieve thread - group: threads - beta: true - returns: >- - The [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the - specified ID. - examples: - response: | - { - "id": "thread_abc123", - "object": "thread", - "created_at": 1699014083, - "metadata": {}, - "tool_resources": { - "code_interpreter": { - "file_ids": [] - } - } - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - thread = client.beta.threads.retrieve( - "thread_id", - ) - print(thread.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const thread = await client.beta.threads.retrieve('thread_id'); - - console.log(thread.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - thread, err := client.Beta.Threads.Get(context.TODO(), "thread_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", thread.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.Thread; - import com.openai.models.beta.threads.ThreadRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Thread thread = client.beta().threads().retrieve("thread_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - thread = openai.beta.threads.retrieve("thread_id") - - puts(thread) - description: Retrieves a thread. - post: - operationId: modifyThread - tags: - - Assistants - summary: Modify thread - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to modify. Only the `metadata` can be modified. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ModifyThreadRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ThreadObject' - x-oaiMeta: - name: Modify thread - group: threads - beta: true - returns: >- - The modified [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching - the specified ID. - examples: - response: | - { - "id": "thread_abc123", - "object": "thread", - "created_at": 1699014083, - "metadata": { - "modified": "true", - "user": "abc123" - }, - "tool_resources": {} - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "metadata": { - "modified": "true", - "user": "abc123" - } - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - thread = client.beta.threads.update( - thread_id="thread_id", - ) - print(thread.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const thread = await client.beta.threads.update('thread_id'); - - console.log(thread.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - thread, err := client.Beta.Threads.Update( - context.TODO(), - "thread_id", - openai.BetaThreadUpdateParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", thread.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.Thread; - import com.openai.models.beta.threads.ThreadUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Thread thread = client.beta().threads().update("thread_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - thread = openai.beta.threads.update("thread_id") - - puts(thread) - description: Modifies a thread. - delete: - operationId: deleteThread - tags: - - Assistants - summary: Delete thread - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to delete. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/DeleteThreadResponse' - x-oaiMeta: - name: Delete thread - group: threads - beta: true - returns: Deletion status - examples: - response: | - { - "id": "thread_abc123", - "object": "thread.deleted", - "deleted": true - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -X DELETE - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - thread_deleted = client.beta.threads.delete( - "thread_id", - ) - print(thread_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const threadDeleted = await client.beta.threads.delete('thread_id'); - - console.log(threadDeleted.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - threadDeleted, err := client.Beta.Threads.Delete(context.TODO(), "thread_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", threadDeleted.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.ThreadDeleteParams; - import com.openai.models.beta.threads.ThreadDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadDeleted threadDeleted = client.beta().threads().delete("thread_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - thread_deleted = openai.beta.threads.delete("thread_id") - - puts(thread_deleted) - description: Delete a thread. - /threads/{thread_id}/messages: - get: - operationId: listMessages - tags: - - Assistants - summary: List messages - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: >- - The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) the messages belong - to. - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - - name: run_id - in: query - description: | - Filter messages by the run ID that generated them. - schema: - type: string - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListMessagesResponse' - x-oaiMeta: - name: List messages - group: threads - beta: true - returns: A list of [message](https://platform.openai.com/docs/api-reference/messages) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "msg_abc123", - "object": "thread.message", - "created_at": 1699016383, - "assistant_id": null, - "thread_id": "thread_abc123", - "run_id": null, - "role": "user", - "content": [ - { - "type": "text", - "text": { - "value": "How does AI work? Explain it in simple terms.", - "annotations": [] - } - } - ], - "attachments": [], - "metadata": {} - }, - { - "id": "msg_abc456", - "object": "thread.message", - "created_at": 1699016383, - "assistant_id": null, - "thread_id": "thread_abc123", - "run_id": null, - "role": "user", - "content": [ - { - "type": "text", - "text": { - "value": "Hello, what is AI?", - "annotations": [] - } - } - ], - "attachments": [], - "metadata": {} - } - ], - "first_id": "msg_abc123", - "last_id": "msg_abc456", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/messages \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.beta.threads.messages.list( - thread_id="thread_id", - ) - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const message of client.beta.threads.messages.list('thread_id')) { - console.log(message.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Beta.Threads.Messages.List( - context.TODO(), - "thread_id", - openai.BetaThreadMessageListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.messages.MessageListPage; - import com.openai.models.beta.threads.messages.MessageListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - MessageListPage page = client.beta().threads().messages().list("thread_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.beta.threads.messages.list("thread_id") - - puts(page) - description: Returns a list of messages for a given thread. - post: - operationId: createMessage - tags: - - Assistants - summary: Create message - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: >- - The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to create a message - for. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateMessageRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/MessageObject' - x-oaiMeta: - name: Create message - group: threads - beta: true - returns: A [message](https://platform.openai.com/docs/api-reference/messages/object) object. - examples: - response: | - { - "id": "msg_abc123", - "object": "thread.message", - "created_at": 1713226573, - "assistant_id": null, - "thread_id": "thread_abc123", - "run_id": null, - "role": "user", - "content": [ - { - "type": "text", - "text": { - "value": "How does AI work? Explain it in simple terms.", - "annotations": [] - } - } - ], - "attachments": [], - "metadata": {} - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/messages \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "role": "user", - "content": "How does AI work? Explain it in simple terms." - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - message = client.beta.threads.messages.create( - thread_id="thread_id", - content="string", - role="user", - ) - print(message.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const message = await client.beta.threads.messages.create('thread_id', { content: 'string', - role: 'user' }); - - - console.log(message.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - message, err := client.Beta.Threads.Messages.New( - context.TODO(), - "thread_id", - openai.BetaThreadMessageNewParams{ - Content: openai.BetaThreadMessageNewParamsContentUnion{ - OfString: openai.String("string"), - }, - Role: openai.BetaThreadMessageNewParamsRoleUser, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", message.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.messages.Message; - import com.openai.models.beta.threads.messages.MessageCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - MessageCreateParams params = MessageCreateParams.builder() - .threadId("thread_id") - .content("string") - .role(MessageCreateParams.Role.USER) - .build(); - Message message = client.beta().threads().messages().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - message = openai.beta.threads.messages.create("thread_id", content: "string", role: :user) - - puts(message) - description: Create a message. - /threads/{thread_id}/messages/{message_id}: - get: - operationId: getMessage - tags: - - Assistants - summary: Retrieve message - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: >- - The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this - message belongs. - - in: path - name: message_id - required: true - schema: - type: string - description: The ID of the message to retrieve. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/MessageObject' - x-oaiMeta: - name: Retrieve message - group: threads - beta: true - returns: >- - The [message](https://platform.openai.com/docs/api-reference/messages/object) object matching the - specified ID. - examples: - response: | - { - "id": "msg_abc123", - "object": "thread.message", - "created_at": 1699017614, - "assistant_id": null, - "thread_id": "thread_abc123", - "run_id": null, - "role": "user", - "content": [ - { - "type": "text", - "text": { - "value": "How does AI work? Explain it in simple terms.", - "annotations": [] - } - } - ], - "attachments": [], - "metadata": {} - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - message = client.beta.threads.messages.retrieve( - message_id="message_id", - thread_id="thread_id", - ) - print(message.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const message = await client.beta.threads.messages.retrieve('message_id', { thread_id: - 'thread_id' }); - - - console.log(message.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - message, err := client.Beta.Threads.Messages.Get( - context.TODO(), - "thread_id", - "message_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", message.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.messages.Message; - import com.openai.models.beta.threads.messages.MessageRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - MessageRetrieveParams params = MessageRetrieveParams.builder() - .threadId("thread_id") - .messageId("message_id") - .build(); - Message message = client.beta().threads().messages().retrieve(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - message = openai.beta.threads.messages.retrieve("message_id", thread_id: "thread_id") - - puts(message) - description: Retrieve a message. - post: - operationId: modifyMessage - tags: - - Assistants - summary: Modify message - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to which this message belongs. - - in: path - name: message_id - required: true - schema: - type: string - description: The ID of the message to modify. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ModifyMessageRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/MessageObject' - x-oaiMeta: - name: Modify message - group: threads - beta: true - returns: The modified [message](https://platform.openai.com/docs/api-reference/messages/object) object. - examples: - response: | - { - "id": "msg_abc123", - "object": "thread.message", - "created_at": 1699017614, - "assistant_id": null, - "thread_id": "thread_abc123", - "run_id": null, - "role": "user", - "content": [ - { - "type": "text", - "text": { - "value": "How does AI work? Explain it in simple terms.", - "annotations": [] - } - } - ], - "file_ids": [], - "metadata": { - "modified": "true", - "user": "abc123" - } - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "metadata": { - "modified": "true", - "user": "abc123" - } - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - message = client.beta.threads.messages.update( - message_id="message_id", - thread_id="thread_id", - ) - print(message.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const message = await client.beta.threads.messages.update('message_id', { thread_id: 'thread_id' - }); - - - console.log(message.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - message, err := client.Beta.Threads.Messages.Update( - context.TODO(), - "thread_id", - "message_id", - openai.BetaThreadMessageUpdateParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", message.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.messages.Message; - import com.openai.models.beta.threads.messages.MessageUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - MessageUpdateParams params = MessageUpdateParams.builder() - .threadId("thread_id") - .messageId("message_id") - .build(); - Message message = client.beta().threads().messages().update(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - message = openai.beta.threads.messages.update("message_id", thread_id: "thread_id") - - puts(message) - description: Modifies a message. - delete: - operationId: deleteMessage - tags: - - Assistants - summary: Delete message - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to which this message belongs. - - in: path - name: message_id - required: true - schema: - type: string - description: The ID of the message to delete. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/DeleteMessageResponse' - x-oaiMeta: - name: Delete message - group: threads - beta: true - returns: Deletion status - examples: - response: | - { - "id": "msg_abc123", - "object": "thread.message.deleted", - "deleted": true - } - request: - curl: | - curl -X DELETE https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - message_deleted = client.beta.threads.messages.delete( - message_id="message_id", - thread_id="thread_id", - ) - print(message_deleted.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const messageDeleted = await client.beta.threads.messages.delete('message_id', { thread_id: - 'thread_id' }); - - - console.log(messageDeleted.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - messageDeleted, err := client.Beta.Threads.Messages.Delete( - context.TODO(), - "thread_id", - "message_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", messageDeleted.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.messages.MessageDeleteParams; - import com.openai.models.beta.threads.messages.MessageDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - MessageDeleteParams params = MessageDeleteParams.builder() - .threadId("thread_id") - .messageId("message_id") - .build(); - MessageDeleted messageDeleted = client.beta().threads().messages().delete(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - message_deleted = openai.beta.threads.messages.delete("message_id", thread_id: "thread_id") - - puts(message_deleted) - description: Deletes a message. - /threads/{thread_id}/runs: - get: - operationId: listRuns - tags: - - Assistants - summary: List runs - parameters: - - name: thread_id - in: path - required: true - schema: - type: string - description: The ID of the thread the run belongs to. - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListRunsResponse' - x-oaiMeta: - name: List runs - group: threads - beta: true - returns: A list of [run](https://platform.openai.com/docs/api-reference/runs/object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1699075072, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "completed", - "started_at": 1699075072, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699075073, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "incomplete_details": null, - "tools": [ - { - "type": "code_interpreter" - } - ], - "tool_resources": { - "code_interpreter": { - "file_ids": [ - "file-abc123", - "file-abc456" - ] - } - }, - "metadata": {}, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - }, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - }, - { - "id": "run_abc456", - "object": "thread.run", - "created_at": 1699063290, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "completed", - "started_at": 1699063290, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699063291, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "incomplete_details": null, - "tools": [ - { - "type": "code_interpreter" - } - ], - "tool_resources": { - "code_interpreter": { - "file_ids": [ - "file-abc123", - "file-abc456" - ] - } - }, - "metadata": {}, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - }, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - ], - "first_id": "run_abc123", - "last_id": "run_abc456", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.beta.threads.runs.list( - thread_id="thread_id", - ) - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const run of client.beta.threads.runs.list('thread_id')) { - console.log(run.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Beta.Threads.Runs.List( - context.TODO(), - "thread_id", - openai.BetaThreadRunListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.RunListPage; - import com.openai.models.beta.threads.runs.RunListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunListPage page = client.beta().threads().runs().list("thread_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.beta.threads.runs.list("thread_id") - - puts(page) - description: Returns a list of runs belonging to a thread. - post: - operationId: createRun - tags: - - Assistants - summary: Create run - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to run. - - name: include[] - in: query - description: > - A list of additional fields to include in the response. Currently the only supported value is - `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result - content. - - - See the [file search tool - documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - for more information. - schema: - type: array - items: - type: string - enum: - - step_details.tool_calls[*].file_search.results[*].content - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateRunRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunObject' - x-oaiMeta: - name: Create run - group: threads - beta: true - returns: A [run](https://platform.openai.com/docs/api-reference/runs/object) object. - examples: - - title: Default - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "assistant_id": "asst_abc123" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.create( - thread_id="thread_id", - assistant_id="assistant_id", - ) - print(run.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' - }); - - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.New( - context.TODO(), - "thread_id", - openai.BetaThreadRunNewParams{ - AssistantID: "assistant_id", - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunCreateParams params = RunCreateParams.builder() - .threadId("thread_id") - .assistantId("assistant_id") - .build(); - Run run = client.beta().threads().runs().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id") - - puts(run) - response: | - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1699063290, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "queued", - "started_at": 1699063290, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699063291, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "incomplete_details": null, - "tools": [ - { - "type": "code_interpreter" - } - ], - "metadata": {}, - "usage": null, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - - title: Streaming - request: - curl: | - curl https://api.openai.com/v1/threads/thread_123/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "assistant_id": "asst_123", - "stream": true - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.create( - thread_id="thread_id", - assistant_id="assistant_id", - ) - print(run.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' - }); - - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.New( - context.TODO(), - "thread_id", - openai.BetaThreadRunNewParams{ - AssistantID: "assistant_id", - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunCreateParams params = RunCreateParams.builder() - .threadId("thread_id") - .assistantId("assistant_id") - .build(); - Run run = client.beta().threads().runs().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id") - - puts(run) - response: > - event: thread.run.created - - data: - {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.queued - - data: - {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.in_progress - - data: - {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.step.created - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - - - event: thread.run.step.in_progress - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - - - event: thread.message.created - - data: - {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - - - event: thread.message.in_progress - - data: - {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} - - - ... - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" - today"}}]}} - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} - - - event: thread.message.completed - - data: - {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710330642,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! - How can I assist you today?","annotations":[]}}],"metadata":{}} - - - event: thread.run.step.completed - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710330642,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} - - - event: thread.run.completed - - data: - {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: done - - data: [DONE] - - title: Streaming with Functions - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "assistant_id": "asst_abc123", - "tools": [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather in a given location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"] - } - }, - "required": ["location"] - } - } - } - ], - "stream": true - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.create( - thread_id="thread_id", - assistant_id="assistant_id", - ) - print(run.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' - }); - - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.New( - context.TODO(), - "thread_id", - openai.BetaThreadRunNewParams{ - AssistantID: "assistant_id", - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunCreateParams params = RunCreateParams.builder() - .threadId("thread_id") - .assistantId("assistant_id") - .build(); - Run run = client.beta().threads().runs().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id") - - puts(run) - response: > - event: thread.run.created - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.queued - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.in_progress - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.step.created - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - - - event: thread.run.step.in_progress - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} - - - event: thread.message.created - - data: - {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - - - event: thread.message.in_progress - - data: - {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} - - - ... - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" - today"}}]}} - - - event: thread.message.delta - - data: - {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} - - - event: thread.message.completed - - data: - {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! - How can I assist you today?","annotations":[]}}],"metadata":{}} - - - event: thread.run.step.completed - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} - - - event: thread.run.completed - - data: - {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: done - - data: [DONE] - description: Create a run. - /threads/{thread_id}/runs/{run_id}: - get: - operationId: getRun - tags: - - Assistants - summary: Retrieve run - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. - - in: path - name: run_id - required: true - schema: - type: string - description: The ID of the run to retrieve. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunObject' - x-oaiMeta: - name: Retrieve run - group: threads - beta: true - returns: >- - The [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified - ID. - examples: - response: | - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1699075072, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "completed", - "started_at": 1699075072, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699075073, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "incomplete_details": null, - "tools": [ - { - "type": "code_interpreter" - } - ], - "metadata": {}, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - }, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.retrieve( - run_id="run_id", - thread_id="thread_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.runs.retrieve('run_id', { thread_id: 'thread_id' }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.Get( - context.TODO(), - "thread_id", - "run_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunRetrieveParams params = RunRetrieveParams.builder() - .threadId("thread_id") - .runId("run_id") - .build(); - Run run = client.beta().threads().runs().retrieve(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.runs.retrieve("run_id", thread_id: "thread_id") - - puts(run) - description: Retrieves a run. - post: - operationId: modifyRun - tags: - - Assistants - summary: Modify run - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. - - in: path - name: run_id - required: true - schema: - type: string - description: The ID of the run to modify. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/ModifyRunRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunObject' - x-oaiMeta: - name: Modify run - group: threads - beta: true - returns: >- - The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the - specified ID. - examples: - response: | - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1699075072, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "completed", - "started_at": 1699075072, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699075073, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "incomplete_details": null, - "tools": [ - { - "type": "code_interpreter" - } - ], - "tool_resources": { - "code_interpreter": { - "file_ids": [ - "file-abc123", - "file-abc456" - ] - } - }, - "metadata": { - "user_id": "user_abc123" - }, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - }, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "metadata": { - "user_id": "user_abc123" - } - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.update( - run_id="run_id", - thread_id="thread_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.runs.update('run_id', { thread_id: 'thread_id' }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.Update( - context.TODO(), - "thread_id", - "run_id", - openai.BetaThreadRunUpdateParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunUpdateParams params = RunUpdateParams.builder() - .threadId("thread_id") - .runId("run_id") - .build(); - Run run = client.beta().threads().runs().update(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.runs.update("run_id", thread_id: "thread_id") - - puts(run) - description: Modifies a run. - /threads/{thread_id}/runs/{run_id}/cancel: - post: - operationId: cancelRun - tags: - - Assistants - summary: Cancel a run - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to which this run belongs. - - in: path - name: run_id - required: true - schema: - type: string - description: The ID of the run to cancel. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunObject' - x-oaiMeta: - name: Cancel a run - group: threads - beta: true - returns: >- - The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the - specified ID. - examples: - response: | - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1699076126, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "cancelling", - "started_at": 1699076126, - "expires_at": 1699076726, - "cancelled_at": null, - "failed_at": null, - "completed_at": null, - "last_error": null, - "model": "gpt-4o", - "instructions": "You summarize books.", - "tools": [ - { - "type": "file_search" - } - ], - "tool_resources": { - "file_search": { - "vector_store_ids": ["vs_123"] - } - }, - "metadata": {}, - "usage": null, - "temperature": 1.0, - "top_p": 1.0, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/cancel \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: assistants=v2" \ - -X POST - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.cancel( - run_id="run_id", - thread_id="thread_id", - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.runs.cancel('run_id', { thread_id: 'thread_id' }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.Cancel( - context.TODO(), - "thread_id", - "run_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunCancelParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunCancelParams params = RunCancelParams.builder() - .threadId("thread_id") - .runId("run_id") - .build(); - Run run = client.beta().threads().runs().cancel(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - run = openai.beta.threads.runs.cancel("run_id", thread_id: "thread_id") - - puts(run) - description: Cancels a run that is `in_progress`. - /threads/{thread_id}/runs/{run_id}/steps: - get: - operationId: listRunSteps - tags: - - Assistants - summary: List run steps - parameters: - - name: thread_id - in: path - required: true - schema: - type: string - description: The ID of the thread the run and run steps belong to. - - name: run_id - in: path - required: true - schema: - type: string - description: The ID of the run the run steps belong to. - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - - name: include[] - in: query - description: > - A list of additional fields to include in the response. Currently the only supported value is - `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result - content. - - - See the [file search tool - documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - for more information. - schema: - type: array - items: - type: string - enum: - - step_details.tool_calls[*].file_search.results[*].content - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListRunStepsResponse' - x-oaiMeta: - name: List run steps - group: threads - beta: true - returns: A list of [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "step_abc123", - "object": "thread.run.step", - "created_at": 1699063291, - "run_id": "run_abc123", - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "type": "message_creation", - "status": "completed", - "cancelled_at": null, - "completed_at": 1699063291, - "expired_at": null, - "failed_at": null, - "last_error": null, - "step_details": { - "type": "message_creation", - "message_creation": { - "message_id": "msg_abc123" - } - }, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - } - } - ], - "first_id": "step_abc123", - "last_id": "step_abc456", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.beta.threads.runs.steps.list( - run_id="run_id", - thread_id="thread_id", - ) - page = page.data[0] - print(page.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - // Automatically fetches more pages as needed. - - for await (const runStep of client.beta.threads.runs.steps.list('run_id', { thread_id: - 'thread_id' })) { - console.log(runStep.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Beta.Threads.Runs.Steps.List( - context.TODO(), - "thread_id", - "run_id", - openai.BetaThreadRunStepListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.steps.StepListPage; - import com.openai.models.beta.threads.runs.steps.StepListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - StepListParams params = StepListParams.builder() - .threadId("thread_id") - .runId("run_id") - .build(); - StepListPage page = client.beta().threads().runs().steps().list(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.beta.threads.runs.steps.list("run_id", thread_id: "thread_id") - - puts(page) - description: Returns a list of run steps belonging to a run. - /threads/{thread_id}/runs/{run_id}/steps/{step_id}: - get: - operationId: getRunStep - tags: - - Assistants - summary: Retrieve run step - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: The ID of the thread to which the run and run step belongs. - - in: path - name: run_id - required: true - schema: - type: string - description: The ID of the run to which the run step belongs. - - in: path - name: step_id - required: true - schema: - type: string - description: The ID of the run step to retrieve. - - name: include[] - in: query - description: > - A list of additional fields to include in the response. Currently the only supported value is - `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result - content. - - - See the [file search tool - documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - for more information. - schema: - type: array - items: - type: string - enum: - - step_details.tool_calls[*].file_search.results[*].content - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunStepObject' - x-oaiMeta: - name: Retrieve run step - group: threads - beta: true - returns: >- - The [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) object matching - the specified ID. - examples: - response: | - { - "id": "step_abc123", - "object": "thread.run.step", - "created_at": 1699063291, - "run_id": "run_abc123", - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "type": "message_creation", - "status": "completed", - "cancelled_at": null, - "completed_at": 1699063291, - "expired_at": null, - "failed_at": null, - "last_error": null, - "step_details": { - "type": "message_creation", - "message_creation": { - "message_id": "msg_abc123" - } - }, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - } - } - request: - curl: | - curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run_step = client.beta.threads.runs.steps.retrieve( - step_id="step_id", - thread_id="thread_id", - run_id="run_id", - ) - print(run_step.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const runStep = await client.beta.threads.runs.steps.retrieve('step_id', { - thread_id: 'thread_id', - run_id: 'run_id', - }); - - console.log(runStep.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - runStep, err := client.Beta.Threads.Runs.Steps.Get( - context.TODO(), - "thread_id", - "run_id", - "step_id", - openai.BetaThreadRunStepGetParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", runStep.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.steps.RunStep; - import com.openai.models.beta.threads.runs.steps.StepRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - StepRetrieveParams params = StepRetrieveParams.builder() - .threadId("thread_id") - .runId("run_id") - .stepId("step_id") - .build(); - RunStep runStep = client.beta().threads().runs().steps().retrieve(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - run_step = openai.beta.threads.runs.steps.retrieve("step_id", thread_id: "thread_id", run_id: - "run_id") - - - puts(run_step) - description: Retrieves a run step. - /threads/{thread_id}/runs/{run_id}/submit_tool_outputs: - post: - operationId: submitToolOuputsToRun - tags: - - Assistants - summary: Submit tool outputs to run - parameters: - - in: path - name: thread_id - required: true - schema: - type: string - description: >- - The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this run - belongs. - - in: path - name: run_id - required: true - schema: - type: string - description: The ID of the run that requires the tool output submission. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/SubmitToolOutputsRunRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/RunObject' - x-oaiMeta: - name: Submit tool outputs to run - group: threads - beta: true - returns: >- - The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the - specified ID. - examples: - - title: Default - request: - curl: | - curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "tool_outputs": [ - { - "tool_call_id": "call_001", - "output": "70 degrees and sunny." - } - ] - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.submit_tool_outputs( - run_id="run_id", - thread_id="thread_id", - tool_outputs=[{}], - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.runs.submitToolOutputs('run_id', { - thread_id: 'thread_id', - tool_outputs: [{}], - }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.SubmitToolOutputs( - context.TODO(), - "thread_id", - "run_id", - openai.BetaThreadRunSubmitToolOutputsParams{ - ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{ - - }}, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder() - .threadId("thread_id") - .runId("run_id") - .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build()) - .build(); - Run run = client.beta().threads().runs().submitToolOutputs(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - run = openai.beta.threads.runs.submit_tool_outputs("run_id", thread_id: "thread_id", - tool_outputs: [{}]) - - - puts(run) - response: | - { - "id": "run_123", - "object": "thread.run", - "created_at": 1699075592, - "assistant_id": "asst_123", - "thread_id": "thread_123", - "status": "queued", - "started_at": 1699075592, - "expires_at": 1699076192, - "cancelled_at": null, - "failed_at": null, - "completed_at": null, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "tools": [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather in a given location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"] - } - }, - "required": ["location"] - } - } - } - ], - "metadata": {}, - "usage": null, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - - title: Streaming - request: - curl: | - curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "tool_outputs": [ - { - "tool_call_id": "call_001", - "output": "70 degrees and sunny." - } - ], - "stream": true - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - run = client.beta.threads.runs.submit_tool_outputs( - run_id="run_id", - thread_id="thread_id", - tool_outputs=[{}], - ) - print(run.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const run = await client.beta.threads.runs.submitToolOutputs('run_id', { - thread_id: 'thread_id', - tool_outputs: [{}], - }); - - console.log(run.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - run, err := client.Beta.Threads.Runs.SubmitToolOutputs( - context.TODO(), - "thread_id", - "run_id", - openai.BetaThreadRunSubmitToolOutputsParams{ - ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{ - - }}, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", run.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.threads.runs.Run; - import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder() - .threadId("thread_id") - .runId("run_id") - .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build()) - .build(); - Run run = client.beta().threads().runs().submitToolOutputs(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - run = openai.beta.threads.runs.submit_tool_outputs("run_id", thread_id: "thread_id", - tool_outputs: [{}]) - - - puts(run) - response: > - event: thread.run.step.completed - - data: - {"id":"step_001","object":"thread.run.step","created_at":1710352449,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"completed","cancelled_at":null,"completed_at":1710352475,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[{"id":"call_iWr0kQ2EaYMaxNdl0v3KYkx7","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San - Francisco, CA\",\"unit\":\"fahrenheit\"}","output":"70 degrees and - sunny."}}]},"usage":{"prompt_tokens":291,"completion_tokens":24,"total_tokens":315}} - - - event: thread.run.queued - - data: - {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.in_progress - - data: - {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: thread.run.step.created - - data: - {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} - - - event: thread.run.step.in_progress - - data: - {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} - - - event: thread.message.created - - data: - {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - - - event: thread.message.in_progress - - data: - {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} - - - event: thread.message.delta - - data: - {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"The","annotations":[]}}]}} - - - event: thread.message.delta - - data: - {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" - current"}}]}} - - - event: thread.message.delta - - data: - {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" - weather"}}]}} - - - ... - - - event: thread.message.delta - - data: - {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" - sunny"}}]}} - - - event: thread.message.delta - - data: - {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"."}}]}} - - - event: thread.message.completed - - data: - {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710352477,"role":"assistant","content":[{"type":"text","text":{"value":"The - current weather in San Francisco, CA is 70 degrees Fahrenheit and - sunny.","annotations":[]}}],"metadata":{}} - - - event: thread.run.step.completed - - data: - {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710352477,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":{"prompt_tokens":329,"completion_tokens":18,"total_tokens":347}} - - - event: thread.run.completed - - data: - {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get - the current weather in a given - location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The - city and state, e.g. San Francisco, - CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} - - - event: done - - data: [DONE] - description: > - When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, - this endpoint can be used to submit the outputs from the tool calls once they're all completed. All - outputs must be submitted in a single request. - /uploads: - post: - operationId: createUpload - tags: - - Uploads - summary: Create upload - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateUploadRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Upload' - x-oaiMeta: - name: Create upload - group: uploads - returns: >- - The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status - `pending`. - examples: - response: | - { - "id": "upload_abc123", - "object": "upload", - "bytes": 2147483648, - "created_at": 1719184911, - "filename": "training_examples.jsonl", - "purpose": "fine-tune", - "status": "pending", - "expires_at": 1719127296 - } - request: - curl: | - curl https://api.openai.com/v1/uploads \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "purpose": "fine-tune", - "filename": "training_examples.jsonl", - "bytes": 2147483648, - "mime_type": "text/jsonl", - "expires_after": { - "anchor": "created_at", - "seconds": 3600 - } - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const upload = await client.uploads.create({ - bytes: 0, - filename: 'filename', - mime_type: 'mime_type', - purpose: 'assistants', - }); - - console.log(upload.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - upload = client.uploads.create( - bytes=0, - filename="filename", - mime_type="mime_type", - purpose="assistants", - ) - print(upload.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - upload, err := client.Uploads.New(context.TODO(), openai.UploadNewParams{ - Bytes: 0, - Filename: "filename", - MimeType: "mime_type", - Purpose: openai.FilePurposeAssistants, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", upload.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.files.FilePurpose; - import com.openai.models.uploads.Upload; - import com.openai.models.uploads.UploadCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - UploadCreateParams params = UploadCreateParams.builder() - .bytes(0L) - .filename("filename") - .mimeType("mime_type") - .purpose(FilePurpose.ASSISTANTS) - .build(); - Upload upload = client.uploads().create(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - upload = openai.uploads.create(bytes: 0, filename: "filename", mime_type: "mime_type", purpose: - :assistants) - - - puts(upload) - description: > - Creates an intermediate [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object - - that you can add [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. - - Currently, an Upload can accept at most 8 GB in total and expires after an - - hour after you create it. - - - Once you complete the Upload, we will create a - - [File](https://platform.openai.com/docs/api-reference/files/object) object that contains all the parts - - you uploaded. This File is usable in the rest of our platform as a regular - - File object. - - - For certain `purpose` values, the correct `mime_type` must be specified. - - Please refer to documentation for the - - [supported MIME types for your use - case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). - - - For guidance on the proper filename extensions for each purpose, please - - follow the documentation on [creating a - - File](https://platform.openai.com/docs/api-reference/files/create). - /uploads/{upload_id}/cancel: - post: - operationId: cancelUpload - tags: - - Uploads - summary: Cancel upload - parameters: - - in: path - name: upload_id - required: true - schema: - type: string - example: upload_abc123 - description: | - The ID of the Upload. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Upload' - x-oaiMeta: - name: Cancel upload - group: uploads - returns: >- - The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status - `cancelled`. - examples: - response: | - { - "id": "upload_abc123", - "object": "upload", - "bytes": 2147483648, - "created_at": 1719184911, - "filename": "training_examples.jsonl", - "purpose": "fine-tune", - "status": "cancelled", - "expires_at": 1719127296 - } - request: - curl: | - curl https://api.openai.com/v1/uploads/upload_abc123/cancel - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const upload = await client.uploads.cancel('upload_abc123'); - - console.log(upload.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - upload = client.uploads.cancel( - "upload_abc123", - ) - print(upload.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - upload, err := client.Uploads.Cancel(context.TODO(), "upload_abc123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", upload.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.uploads.Upload; - import com.openai.models.uploads.UploadCancelParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Upload upload = client.uploads().cancel("upload_abc123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - upload = openai.uploads.cancel("upload_abc123") - - puts(upload) - description: | - Cancels the Upload. No Parts may be added after an Upload is cancelled. - /uploads/{upload_id}/complete: - post: - operationId: completeUpload - tags: - - Uploads - summary: Complete upload - parameters: - - in: path - name: upload_id - required: true - schema: - type: string - example: upload_abc123 - description: | - The ID of the Upload. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CompleteUploadRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Upload' - x-oaiMeta: - name: Complete upload - group: uploads - returns: >- - The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status - `completed` with an additional `file` property containing the created usable File object. - examples: - response: | - { - "id": "upload_abc123", - "object": "upload", - "bytes": 2147483648, - "created_at": 1719184911, - "filename": "training_examples.jsonl", - "purpose": "fine-tune", - "status": "completed", - "expires_at": 1719127296, - "file": { - "id": "file-xyz321", - "object": "file", - "bytes": 2147483648, - "created_at": 1719186911, - "expires_at": 1719127296, - "filename": "training_examples.jsonl", - "purpose": "fine-tune", - } - } - request: - curl: | - curl https://api.openai.com/v1/uploads/upload_abc123/complete - -d '{ - "part_ids": ["part_def456", "part_ghi789"] - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const upload = await client.uploads.complete('upload_abc123', { part_ids: ['string'] }); - - console.log(upload.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - upload = client.uploads.complete( - upload_id="upload_abc123", - part_ids=["string"], - ) - print(upload.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - upload, err := client.Uploads.Complete( - context.TODO(), - "upload_abc123", - openai.UploadCompleteParams{ - PartIDs: []string{"string"}, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", upload.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.uploads.Upload; - import com.openai.models.uploads.UploadCompleteParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - UploadCompleteParams params = UploadCompleteParams.builder() - .uploadId("upload_abc123") - .addPartId("string") - .build(); - Upload upload = client.uploads().complete(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - upload = openai.uploads.complete("upload_abc123", part_ids: ["string"]) - - puts(upload) - description: > - Completes the [Upload](https://platform.openai.com/docs/api-reference/uploads/object). - - - Within the returned Upload object, there is a nested - [File](https://platform.openai.com/docs/api-reference/files/object) object that is ready to use in the - rest of the platform. - - - You can specify the order of the Parts by passing in an ordered list of the Part IDs. - - - The number of bytes uploaded upon completion must match the number of bytes initially specified when - creating the Upload object. No Parts may be added after an Upload is completed. - /uploads/{upload_id}/parts: - post: - operationId: addUploadPart - tags: - - Uploads - summary: Add upload part - parameters: - - in: path - name: upload_id - required: true - schema: - type: string - example: upload_abc123 - description: | - The ID of the Upload. - requestBody: - required: true - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/AddUploadPartRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/UploadPart' - x-oaiMeta: - name: Add upload part - group: uploads - returns: The upload [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) object. - examples: - response: | - { - "id": "part_def456", - "object": "upload.part", - "created_at": 1719185911, - "upload_id": "upload_abc123" - } - request: - curl: | - curl https://api.openai.com/v1/uploads/upload_abc123/parts - -F data="aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz..." - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const uploadPart = await client.uploads.parts.create('upload_abc123', { - data: fs.createReadStream('path/to/file'), - }); - - console.log(uploadPart.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - upload_part = client.uploads.parts.create( - upload_id="upload_abc123", - data=b"raw file contents", - ) - print(upload_part.id) - go: | - package main - - import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - uploadPart, err := client.Uploads.Parts.New( - context.TODO(), - "upload_abc123", - openai.UploadPartNewParams{ - Data: io.Reader(bytes.NewBuffer([]byte("some file contents"))), - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", uploadPart.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.uploads.parts.PartCreateParams; - import com.openai.models.uploads.parts.UploadPart; - import java.io.ByteArrayInputStream; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - PartCreateParams params = PartCreateParams.builder() - .uploadId("upload_abc123") - .data(ByteArrayInputStream("some content".getBytes())) - .build(); - UploadPart uploadPart = client.uploads().parts().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - upload_part = openai.uploads.parts.create("upload_abc123", data: Pathname(__FILE__)) - - puts(upload_part) - description: > - Adds a [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an - [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. A Part represents a - chunk of bytes from the file you are trying to upload. - - - Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. - - - It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when - you [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). - /vector_stores: - get: - operationId: listVectorStores - tags: - - Vector stores - summary: List vector stores - parameters: - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListVectorStoresResponse' - x-oaiMeta: - name: List vector stores - group: vector_stores - returns: >- - A list of [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "vs_abc123", - "object": "vector_store", - "created_at": 1699061776, - "name": "Support FAQ", - "description": "Contains commonly asked questions and answers, organized by topic.", - "bytes": 139920, - "file_counts": { - "in_progress": 0, - "completed": 3, - "failed": 0, - "cancelled": 0, - "total": 3 - } - }, - { - "id": "vs_abc456", - "object": "vector_store", - "created_at": 1699061776, - "name": "Support FAQ v2", - "description": null, - "bytes": 139920, - "file_counts": { - "in_progress": 0, - "completed": 3, - "failed": 0, - "cancelled": 0, - "total": 3 - } - } - ], - "first_id": "vs_abc123", - "last_id": "vs_abc456", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.vector_stores.list() - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const vectorStore of client.vectorStores.list()) { - console.log(vectorStore.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.VectorStores.List(context.TODO(), openai.VectorStoreListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.VectorStoreListPage; - import com.openai.models.vectorstores.VectorStoreListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStoreListPage page = client.vectorStores().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.vector_stores.list - - puts(page) - description: Returns a list of vector stores. - post: - operationId: createVectorStore - tags: - - Vector stores - summary: Create vector store - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateVectorStoreRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreObject' - x-oaiMeta: - name: Create vector store - group: vector_stores - returns: A [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object. - examples: - response: | - { - "id": "vs_abc123", - "object": "vector_store", - "created_at": 1699061776, - "name": "Support FAQ", - "description": "Contains commonly asked questions and answers, organized by topic.", - "bytes": 139920, - "file_counts": { - "in_progress": 0, - "completed": 3, - "failed": 0, - "cancelled": 0, - "total": 3 - } - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "name": "Support FAQ" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store = client.vector_stores.create() - print(vector_store.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStore = await client.vectorStores.create(); - - console.log(vectorStore.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStore, err := client.VectorStores.New(context.TODO(), openai.VectorStoreNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStore.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.VectorStore; - import com.openai.models.vectorstores.VectorStoreCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStore vectorStore = client.vectorStores().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store = openai.vector_stores.create - - puts(vector_store) - description: Create a vector store. - /vector_stores/{vector_store_id}: - get: - operationId: getVectorStore - tags: - - Vector stores - summary: Retrieve vector store - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - description: The ID of the vector store to retrieve. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreObject' - x-oaiMeta: - name: Retrieve vector store - group: vector_stores - returns: >- - The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object - matching the specified ID. - examples: - response: | - { - "id": "vs_abc123", - "object": "vector_store", - "created_at": 1699061776 - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store = client.vector_stores.retrieve( - "vector_store_id", - ) - print(vector_store.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStore = await client.vectorStores.retrieve('vector_store_id'); - - console.log(vectorStore.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStore, err := client.VectorStores.Get(context.TODO(), "vector_store_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStore.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.VectorStore; - import com.openai.models.vectorstores.VectorStoreRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStore vectorStore = client.vectorStores().retrieve("vector_store_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store = openai.vector_stores.retrieve("vector_store_id") - - puts(vector_store) - description: Retrieves a vector store. - post: - operationId: modifyVectorStore - tags: - - Vector stores - summary: Modify vector store - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - description: The ID of the vector store to modify. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/UpdateVectorStoreRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreObject' - x-oaiMeta: - name: Modify vector store - group: vector_stores - returns: >- - The modified [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - object. - examples: - response: | - { - "id": "vs_abc123", - "object": "vector_store", - "created_at": 1699061776, - "name": "Support FAQ", - "description": "Contains commonly asked questions and answers, organized by topic.", - "bytes": 139920, - "file_counts": { - "in_progress": 0, - "completed": 3, - "failed": 0, - "cancelled": 0, - "total": 3 - } - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - -d '{ - "name": "Support FAQ" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store = client.vector_stores.update( - vector_store_id="vector_store_id", - ) - print(vector_store.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStore = await client.vectorStores.update('vector_store_id'); - - console.log(vectorStore.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStore, err := client.VectorStores.Update( - context.TODO(), - "vector_store_id", - openai.VectorStoreUpdateParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStore.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.VectorStore; - import com.openai.models.vectorstores.VectorStoreUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStore vectorStore = client.vectorStores().update("vector_store_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store = openai.vector_stores.update("vector_store_id") - - puts(vector_store) - description: Modifies a vector store. - delete: - operationId: deleteVectorStore - tags: - - Vector stores - summary: Delete vector store - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - description: The ID of the vector store to delete. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/DeleteVectorStoreResponse' - x-oaiMeta: - name: Delete vector store - group: vector_stores - returns: Deletion status - examples: - response: | - { - id: "vs_abc123", - object: "vector_store.deleted", - deleted: true - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -X DELETE - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_deleted = client.vector_stores.delete( - "vector_store_id", - ) - print(vector_store_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreDeleted = await client.vectorStores.delete('vector_store_id'); - - console.log(vectorStoreDeleted.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreDeleted, err := client.VectorStores.Delete(context.TODO(), "vector_store_id") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreDeleted.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.VectorStoreDeleteParams; - import com.openai.models.vectorstores.VectorStoreDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStoreDeleted vectorStoreDeleted = client.vectorStores().delete("vector_store_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store_deleted = openai.vector_stores.delete("vector_store_id") - - puts(vector_store_deleted) - description: Delete a vector store. - /vector_stores/{vector_store_id}/file_batches: - post: - operationId: createVectorStoreFileBatch - tags: - - Vector stores - summary: Create vector store file batch - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: | - The ID of the vector store for which to create a File Batch. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateVectorStoreFileBatchRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileBatchObject' - x-oaiMeta: - name: Create vector store file batch - group: vector_stores - returns: >- - A [vector store file - batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) - object. - examples: - response: | - { - "id": "vsfb_abc123", - "object": "vector_store.file_batch", - "created_at": 1699061776, - "vector_store_id": "vs_abc123", - "status": "in_progress", - "file_counts": { - "in_progress": 1, - "completed": 1, - "failed": 0, - "cancelled": 0, - "total": 0, - } - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/file_batches \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "files": [ - { - "file_id": "file-abc123", - "attributes": {"category": "finance"} - }, - { - "file_id": "file-abc456", - "chunking_strategy": { - "type": "static", - "max_chunk_size_tokens": 1200, - "chunk_overlap_tokens": 200 - } - } - ] - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file_batch = client.vector_stores.file_batches.create( - vector_store_id="vs_abc123", - ) - print(vector_store_file_batch.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreFileBatch = await client.vectorStores.fileBatches.create('vs_abc123'); - - console.log(vectorStoreFileBatch.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFileBatch, err := client.VectorStores.FileBatches.New( - context.TODO(), - "vs_abc123", - openai.VectorStoreFileBatchNewParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFileBatch.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.filebatches.FileBatchCreateParams; - import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().create("vs_abc123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store_file_batch = openai.vector_stores.file_batches.create("vs_abc123") - - puts(vector_store_file_batch) - description: Create a vector store file batch. - /vector_stores/{vector_store_id}/file_batches/{batch_id}: - get: - operationId: getVectorStoreFileBatch - tags: - - Vector stores - summary: Retrieve vector store file batch - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: The ID of the vector store that the file batch belongs to. - - in: path - name: batch_id - required: true - schema: - type: string - example: vsfb_abc123 - description: The ID of the file batch being retrieved. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileBatchObject' - x-oaiMeta: - name: Retrieve vector store file batch - group: vector_stores - returns: >- - The [vector store file - batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) - object. - examples: - response: | - { - "id": "vsfb_abc123", - "object": "vector_store.file_batch", - "created_at": 1699061776, - "vector_store_id": "vs_abc123", - "status": "in_progress", - "file_counts": { - "in_progress": 1, - "completed": 1, - "failed": 0, - "cancelled": 0, - "total": 0, - } - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file_batch = client.vector_stores.file_batches.retrieve( - batch_id="vsfb_abc123", - vector_store_id="vs_abc123", - ) - print(vector_store_file_batch.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreFileBatch = await client.vectorStores.fileBatches.retrieve('vsfb_abc123', { - vector_store_id: 'vs_abc123', - }); - - console.log(vectorStoreFileBatch.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFileBatch, err := client.VectorStores.FileBatches.Get( - context.TODO(), - "vs_abc123", - "vsfb_abc123", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFileBatch.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams; - import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileBatchRetrieveParams params = FileBatchRetrieveParams.builder() - .vectorStoreId("vs_abc123") - .batchId("vsfb_abc123") - .build(); - VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().retrieve(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - vector_store_file_batch = openai.vector_stores.file_batches.retrieve("vsfb_abc123", - vector_store_id: "vs_abc123") - - - puts(vector_store_file_batch) - description: Retrieves a vector store file batch. - /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel: - post: - operationId: cancelVectorStoreFileBatch - tags: - - Vector stores - summary: Cancel vector store file batch - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - description: The ID of the vector store that the file batch belongs to. - - in: path - name: batch_id - required: true - schema: - type: string - description: The ID of the file batch to cancel. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileBatchObject' - x-oaiMeta: - name: Cancel vector store file batch - group: vector_stores - returns: The modified vector store file batch object. - examples: - response: | - { - "id": "vsfb_abc123", - "object": "vector_store.file_batch", - "created_at": 1699061776, - "vector_store_id": "vs_abc123", - "status": "in_progress", - "file_counts": { - "in_progress": 12, - "completed": 3, - "failed": 0, - "cancelled": 0, - "total": 15, - } - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/cancel \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -X POST - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file_batch = client.vector_stores.file_batches.cancel( - batch_id="batch_id", - vector_store_id="vector_store_id", - ) - print(vector_store_file_batch.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreFileBatch = await client.vectorStores.fileBatches.cancel('batch_id', { - vector_store_id: 'vector_store_id', - }); - - console.log(vectorStoreFileBatch.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFileBatch, err := client.VectorStores.FileBatches.Cancel( - context.TODO(), - "vector_store_id", - "batch_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFileBatch.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.filebatches.FileBatchCancelParams; - import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileBatchCancelParams params = FileBatchCancelParams.builder() - .vectorStoreId("vector_store_id") - .batchId("batch_id") - .build(); - VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().cancel(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - vector_store_file_batch = openai.vector_stores.file_batches.cancel("batch_id", vector_store_id: - "vector_store_id") - - - puts(vector_store_file_batch) - description: >- - Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as - soon as possible. - /vector_stores/{vector_store_id}/file_batches/{batch_id}/files: - get: - operationId: listFilesInVectorStoreBatch - tags: - - Vector stores - summary: List vector store files in a batch - parameters: - - name: vector_store_id - in: path - description: The ID of the vector store that the files belong to. - required: true - schema: - type: string - - name: batch_id - in: path - description: The ID of the file batch that the files belong to. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - - name: filter - in: query - description: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. - schema: - type: string - enum: - - in_progress - - completed - - failed - - cancelled - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListVectorStoreFilesResponse' - x-oaiMeta: - name: List vector store files in a batch - group: vector_stores - returns: >- - A list of [vector store - file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "file-abc123", - "object": "vector_store.file", - "created_at": 1699061776, - "vector_store_id": "vs_abc123" - }, - { - "id": "file-abc456", - "object": "vector_store.file", - "created_at": 1699061776, - "vector_store_id": "vs_abc123" - } - ], - "first_id": "file-abc123", - "last_id": "file-abc456", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/files \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.vector_stores.file_batches.list_files( - batch_id="batch_id", - vector_store_id="vector_store_id", - ) - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const vectorStoreFile of client.vectorStores.fileBatches.listFiles('batch_id', { - vector_store_id: 'vector_store_id', - })) { - console.log(vectorStoreFile.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.VectorStores.FileBatches.ListFiles( - context.TODO(), - "vector_store_id", - "batch_id", - openai.VectorStoreFileBatchListFilesParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.filebatches.FileBatchListFilesPage; - import com.openai.models.vectorstores.filebatches.FileBatchListFilesParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileBatchListFilesParams params = FileBatchListFilesParams.builder() - .vectorStoreId("vector_store_id") - .batchId("batch_id") - .build(); - FileBatchListFilesPage page = client.vectorStores().fileBatches().listFiles(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - page = openai.vector_stores.file_batches.list_files("batch_id", vector_store_id: - "vector_store_id") - - - puts(page) - description: Returns a list of vector store files in a batch. - /vector_stores/{vector_store_id}/files: - get: - operationId: listVectorStoreFiles - tags: - - Vector stores - summary: List vector store files - parameters: - - name: vector_store_id - in: path - description: The ID of the vector store that the files belong to. - required: true - schema: - type: string - - name: limit - in: query - description: > - A limit on the number of objects to be returned. Limit can range between 1 and 100, and the - default is 20. - required: false - schema: - type: integer - default: 20 - - name: order - in: query - description: > - Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for - descending order. - schema: - type: string - default: desc - enum: - - asc - - desc - - name: after - in: query - description: > - A cursor for use in pagination. `after` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent - call can include after=obj_foo in order to fetch the next page of the list. - schema: - type: string - - name: before - in: query - description: > - A cursor for use in pagination. `before` is an object ID that defines your place in the list. For - instance, if you make a list request and receive 100 objects, starting with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - schema: - type: string - - name: filter - in: query - description: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. - schema: - type: string - enum: - - in_progress - - completed - - failed - - cancelled - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ListVectorStoreFilesResponse' - x-oaiMeta: - name: List vector store files - group: vector_stores - returns: >- - A list of [vector store - file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects. - examples: - response: | - { - "object": "list", - "data": [ - { - "id": "file-abc123", - "object": "vector_store.file", - "created_at": 1699061776, - "vector_store_id": "vs_abc123" - }, - { - "id": "file-abc456", - "object": "vector_store.file", - "created_at": 1699061776, - "vector_store_id": "vs_abc123" - } - ], - "first_id": "file-abc123", - "last_id": "file-abc456", - "has_more": false - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.vector_stores.files.list( - vector_store_id="vector_store_id", - ) - page = page.data[0] - print(page.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const vectorStoreFile of client.vectorStores.files.list('vector_store_id')) { - console.log(vectorStoreFile.id); - } - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.VectorStores.Files.List( - context.TODO(), - "vector_store_id", - openai.VectorStoreFileListParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.files.FileListPage; - import com.openai.models.vectorstores.files.FileListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileListPage page = client.vectorStores().files().list("vector_store_id"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.vector_stores.files.list("vector_store_id") - - puts(page) - description: Returns a list of vector store files. - post: - operationId: createVectorStoreFile - tags: - - Vector stores - summary: Create vector store file - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: | - The ID of the vector store for which to create a File. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/CreateVectorStoreFileRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileObject' - x-oaiMeta: - name: Create vector store file - group: vector_stores - returns: >- - A [vector store - file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object. - examples: - response: | - { - "id": "file-abc123", - "object": "vector_store.file", - "created_at": 1699061776, - "usage_bytes": 1234, - "vector_store_id": "vs_abcd", - "status": "completed", - "last_error": null - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -d '{ - "file_id": "file-abc123" - }' - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file = client.vector_stores.files.create( - vector_store_id="vs_abc123", - file_id="file_id", - ) - print(vector_store_file.id) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const vectorStoreFile = await client.vectorStores.files.create('vs_abc123', { file_id: 'file_id' - }); - - - console.log(vectorStoreFile.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFile, err := client.VectorStores.Files.New( - context.TODO(), - "vs_abc123", - openai.VectorStoreFileNewParams{ - FileID: "file_id", - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFile.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.files.FileCreateParams; - import com.openai.models.vectorstores.files.VectorStoreFile; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileCreateParams params = FileCreateParams.builder() - .vectorStoreId("vs_abc123") - .fileId("file_id") - .build(); - VectorStoreFile vectorStoreFile = client.vectorStores().files().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store_file = openai.vector_stores.files.create("vs_abc123", file_id: "file_id") - - puts(vector_store_file) - description: >- - Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) - to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). - /vector_stores/{vector_store_id}/files/{file_id}: - get: - operationId: getVectorStoreFile - tags: - - Vector stores - summary: Retrieve vector store file - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: The ID of the vector store that the file belongs to. - - in: path - name: file_id - required: true - schema: - type: string - example: file-abc123 - description: The ID of the file being retrieved. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileObject' - x-oaiMeta: - name: Retrieve vector store file - group: vector_stores - returns: >- - The [vector store - file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object. - examples: - response: | - { - "id": "file-abc123", - "object": "vector_store.file", - "created_at": 1699061776, - "vector_store_id": "vs_abcd", - "status": "completed", - "last_error": null - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file = client.vector_stores.files.retrieve( - file_id="file-abc123", - vector_store_id="vs_abc123", - ) - print(vector_store_file.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreFile = await client.vectorStores.files.retrieve('file-abc123', { - vector_store_id: 'vs_abc123', - }); - - console.log(vectorStoreFile.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFile, err := client.VectorStores.Files.Get( - context.TODO(), - "vs_abc123", - "file-abc123", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFile.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.files.FileRetrieveParams; - import com.openai.models.vectorstores.files.VectorStoreFile; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileRetrieveParams params = FileRetrieveParams.builder() - .vectorStoreId("vs_abc123") - .fileId("file-abc123") - .build(); - VectorStoreFile vectorStoreFile = client.vectorStores().files().retrieve(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - vector_store_file = openai.vector_stores.files.retrieve("file-abc123", vector_store_id: - "vs_abc123") - - - puts(vector_store_file) - description: Retrieves a vector store file. - delete: - operationId: deleteVectorStoreFile - tags: - - Vector stores - summary: Delete vector store file - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - description: The ID of the vector store that the file belongs to. - - in: path - name: file_id - required: true - schema: - type: string - description: The ID of the file to delete. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/DeleteVectorStoreFileResponse' - x-oaiMeta: - name: Delete vector store file - group: vector_stores - returns: Deletion status - examples: - response: | - { - id: "file-abc123", - object: "vector_store.file.deleted", - deleted: true - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -H "OpenAI-Beta: assistants=v2" \ - -X DELETE - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file_deleted = client.vector_stores.files.delete( - file_id="file_id", - vector_store_id="vector_store_id", - ) - print(vector_store_file_deleted.id) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreFileDeleted = await client.vectorStores.files.delete('file_id', { - vector_store_id: 'vector_store_id', - }); - - console.log(vectorStoreFileDeleted.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFileDeleted, err := client.VectorStores.Files.Delete( - context.TODO(), - "vector_store_id", - "file_id", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFileDeleted.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.files.FileDeleteParams; - import com.openai.models.vectorstores.files.VectorStoreFileDeleted; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileDeleteParams params = FileDeleteParams.builder() - .vectorStoreId("vector_store_id") - .fileId("file_id") - .build(); - VectorStoreFileDeleted vectorStoreFileDeleted = client.vectorStores().files().delete(params); - } - } - ruby: >- - require "openai" - - - openai = OpenAI::Client.new(api_key: "My API Key") - - - vector_store_file_deleted = openai.vector_stores.files.delete("file_id", vector_store_id: - "vector_store_id") - - - puts(vector_store_file_deleted) - description: >- - Delete a vector store file. This will remove the file from the vector store but the file itself will - not be deleted. To delete the file, use the [delete - file](https://platform.openai.com/docs/api-reference/files/delete) endpoint. - post: - operationId: updateVectorStoreFileAttributes - tags: - - Vector stores - summary: Update vector store file attributes - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: The ID of the vector store the file belongs to. - - in: path - name: file_id - required: true - schema: - type: string - example: file-abc123 - description: The ID of the file to update attributes. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/UpdateVectorStoreFileAttributesRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileObject' - x-oaiMeta: - name: Update vector store file attributes - group: vector_stores - returns: >- - The updated [vector store - file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object. - examples: - response: | - { - "id": "file-abc123", - "object": "vector_store.file", - "usage_bytes": 1234, - "created_at": 1699061776, - "vector_store_id": "vs_abcd", - "status": "completed", - "last_error": null, - "chunking_strategy": {...}, - "attributes": {"key1": "value1", "key2": 2} - } - request: - curl: | - curl https://api.openai.com/v1/vector_stores/{vector_store_id}/files/{file_id} \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"attributes": {"key1": "value1", "key2": 2}}' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const vectorStoreFile = await client.vectorStores.files.update('file-abc123', { - vector_store_id: 'vs_abc123', - attributes: { foo: 'string' }, - }); - - console.log(vectorStoreFile.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - vector_store_file = client.vector_stores.files.update( - file_id="file-abc123", - vector_store_id="vs_abc123", - attributes={ - "foo": "string" - }, - ) - print(vector_store_file.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - vectorStoreFile, err := client.VectorStores.Files.Update( - context.TODO(), - "vs_abc123", - "file-abc123", - openai.VectorStoreFileUpdateParams{ - Attributes: map[string]openai.VectorStoreFileUpdateParamsAttributeUnion{ - "foo": openai.VectorStoreFileUpdateParamsAttributeUnion{ - OfString: openai.String("string"), - }, - }, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", vectorStoreFile.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.JsonValue; - import com.openai.models.vectorstores.files.FileUpdateParams; - import com.openai.models.vectorstores.files.VectorStoreFile; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileUpdateParams params = FileUpdateParams.builder() - .vectorStoreId("vs_abc123") - .fileId("file-abc123") - .attributes(FileUpdateParams.Attributes.builder() - .putAdditionalProperty("foo", JsonValue.from("string")) - .build()) - .build(); - VectorStoreFile vectorStoreFile = client.vectorStores().files().update(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - vector_store_file = openai.vector_stores.files.update( - "file-abc123", - vector_store_id: "vs_abc123", - attributes: {foo: "string"} - ) - - puts(vector_store_file) - description: Update attributes on a vector store file. - /vector_stores/{vector_store_id}/files/{file_id}/content: - get: - operationId: retrieveVectorStoreFileContent - tags: - - Vector stores - summary: Retrieve vector store file content - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: The ID of the vector store. - - in: path - name: file_id - required: true - schema: - type: string - example: file-abc123 - description: The ID of the file within the vector store. - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreFileContentResponse' - x-oaiMeta: - name: Retrieve vector store file content - group: vector_stores - returns: The parsed contents of the specified vector store file. - examples: - response: | - { - "file_id": "file-abc123", - "filename": "example.txt", - "attributes": {"key": "value"}, - "content": [ - {"type": "text", "text": "..."}, - ... - ] - } - request: - curl: | - curl \ - https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123/content \ - -H "Authorization: Bearer $OPENAI_API_KEY" - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const fileContentResponse of client.vectorStores.files.content('file-abc123', { - vector_store_id: 'vs_abc123', - })) { - console.log(fileContentResponse.text); - } - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.vector_stores.files.content( - file_id="file-abc123", - vector_store_id="vs_abc123", - ) - page = page.data[0] - print(page.text) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.VectorStores.Files.Content( - context.TODO(), - "vs_abc123", - "file-abc123", - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.files.FileContentPage; - import com.openai.models.vectorstores.files.FileContentParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - FileContentParams params = FileContentParams.builder() - .vectorStoreId("vs_abc123") - .fileId("file-abc123") - .build(); - FileContentPage page = client.vectorStores().files().content(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.vector_stores.files.content("file-abc123", vector_store_id: "vs_abc123") - - puts(page) - description: Retrieve the parsed contents of a vector store file. - /vector_stores/{vector_store_id}/search: - post: - operationId: searchVectorStore - tags: - - Vector stores - summary: Search vector store - parameters: - - in: path - name: vector_store_id - required: true - schema: - type: string - example: vs_abc123 - description: The ID of the vector store to search. - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreSearchRequest' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/VectorStoreSearchResultsPage' - x-oaiMeta: - name: Search vector store - group: vector_stores - returns: A page of search results from the vector store. - examples: - response: | - { - "object": "vector_store.search_results.page", - "search_query": "What is the return policy?", - "data": [ - { - "file_id": "file_123", - "filename": "document.pdf", - "score": 0.95, - "attributes": { - "author": "John Doe", - "date": "2023-01-01" - }, - "content": [ - { - "type": "text", - "text": "Relevant chunk" - } - ] - }, - { - "file_id": "file_456", - "filename": "notes.txt", - "score": 0.89, - "attributes": { - "author": "Jane Smith", - "date": "2023-01-02" - }, - "content": [ - { - "type": "text", - "text": "Sample text content from the vector store." - } - ] - } - ], - "has_more": false, - "next_page": null - } - request: - curl: | - curl -X POST \ - https://api.openai.com/v1/vector_stores/vs_abc123/search \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"query": "What is the return policy?", "filters": {...}}' - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - // Automatically fetches more pages as needed. - - for await (const vectorStoreSearchResponse of client.vectorStores.search('vs_abc123', { query: - 'string' })) { - console.log(vectorStoreSearchResponse.file_id); - } - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.vector_stores.search( - vector_store_id="vs_abc123", - query="string", - ) - page = page.data[0] - print(page.file_id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.VectorStores.Search( - context.TODO(), - "vs_abc123", - openai.VectorStoreSearchParams{ - Query: openai.VectorStoreSearchParamsQueryUnion{ - OfString: openai.String("string"), - }, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.vectorstores.VectorStoreSearchPage; - import com.openai.models.vectorstores.VectorStoreSearchParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VectorStoreSearchParams params = VectorStoreSearchParams.builder() - .vectorStoreId("vs_abc123") - .query("string") - .build(); - VectorStoreSearchPage page = client.vectorStores().search(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.vector_stores.search("vs_abc123", query: "string") - - puts(page) - description: Search a vector store for relevant chunks based on a query and file attributes filter. - /conversations: - post: - tags: - - Conversations - summary: Create a conversation - description: Create a conversation. - operationId: createConversation - parameters: [] - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/CreateConversationBody' - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationResource' - x-oaiMeta: - name: Create a conversation - group: conversations - returns: > - Returns a [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) - object. - path: create - examples: - - title: Create a conversation. - request: - curl: | - curl https://api.openai.com/v1/conversations \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "metadata": {"topic": "demo"}, - "items": [ - { - "type": "message", - "role": "user", - "content": "Hello!" - } - ] - }' - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const conversation = await client.conversations.create({ - metadata: { topic: "demo" }, - items: [ - { type: "message", role: "user", content: "Hello!" } - ], - }); - console.log(conversation); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - conversation = client.conversations.create() - print(conversation.id) - csharp: | - using System; - using System.Collections.Generic; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - Conversation conversation = client.CreateConversation( - new CreateConversationOptions - { - Metadata = new Dictionary - { - { "topic", "demo" } - }, - Items = - { - new ConversationMessageInput - { - Role = "user", - Content = "Hello!", - } - } - } - ); - Console.WriteLine(conversation.Id); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const conversation = await client.conversations.create(); - - console.log(conversation.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/conversations" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversation, err := client.Conversations.New(context.TODO(), conversations.ConversationNewParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", conversation.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.Conversation; - import com.openai.models.conversations.ConversationCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Conversation conversation = client.conversations().create(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - conversation = openai.conversations.create - - puts(conversation) - response: | - { - "id": "conv_123", - "object": "conversation", - "created_at": 1741900000, - "metadata": {"topic": "demo"} - } - /conversations/{conversation_id}: - get: - tags: - - Conversations - summary: Retrieve a conversation - description: Get a conversation - operationId: getConversation - parameters: - - name: conversation_id - in: path - description: The ID of the conversation to retrieve. - required: true - schema: - example: conv_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationResource' - x-oaiMeta: - name: Retrieve a conversation - group: conversations - returns: > - Returns a [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) - object. - path: retrieve - examples: - - title: Retrieve a conversation - request: - curl: | - curl https://api.openai.com/v1/conversations/conv_123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const conversation = await client.conversations.retrieve("conv_123"); - console.log(conversation); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - conversation = client.conversations.retrieve( - "conv_123", - ) - print(conversation.id) - csharp: | - using System; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - Conversation conversation = client.GetConversation("conv_123"); - Console.WriteLine(conversation.Id); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const conversation = await client.conversations.retrieve('conv_123'); - - console.log(conversation.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversation, err := client.Conversations.Get(context.TODO(), "conv_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", conversation.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.Conversation; - import com.openai.models.conversations.ConversationRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Conversation conversation = client.conversations().retrieve("conv_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - conversation = openai.conversations.retrieve("conv_123") - - puts(conversation) - response: | - { - "id": "conv_123", - "object": "conversation", - "created_at": 1741900000, - "metadata": {"topic": "demo"} - } - delete: - tags: - - Conversations - summary: Delete a conversation - description: Delete a conversation. Items in the conversation will not be deleted. - operationId: deleteConversation - parameters: - - name: conversation_id - in: path - description: The ID of the conversation to delete. - required: true - schema: - example: conv_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedConversationResource' - x-oaiMeta: - name: Delete a conversation - group: conversations - returns: | - A success message. - path: delete - examples: - - title: Delete a conversation - request: - curl: | - curl -X DELETE https://api.openai.com/v1/conversations/conv_123 \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const deleted = await client.conversations.delete("conv_123"); - console.log(deleted); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - conversation_deleted_resource = client.conversations.delete( - "conv_123", - ) - print(conversation_deleted_resource.id) - csharp: | - using System; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - DeletedConversation deleted = client.DeleteConversation("conv_123"); - Console.WriteLine(deleted.Id); - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const conversationDeletedResource = await client.conversations.delete('conv_123'); - - console.log(conversationDeletedResource.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversationDeletedResource, err := client.Conversations.Delete(context.TODO(), "conv_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", conversationDeletedResource.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.conversations.ConversationDeleteParams; - import com.openai.models.conversations.ConversationDeletedResource; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ConversationDeletedResource conversationDeletedResource = client.conversations().delete("conv_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - conversation_deleted_resource = openai.conversations.delete("conv_123") - - puts(conversation_deleted_resource) - response: | - { - "id": "conv_123", - "object": "conversation.deleted", - "deleted": true - } - post: - tags: - - Conversations - summary: Update a conversation - description: Update a conversation - operationId: updateConversation - parameters: - - name: conversation_id - in: path - description: The ID of the conversation to update. - required: true - schema: - example: conv_123 - type: string - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/UpdateConversationBody' - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationResource' - x-oaiMeta: - name: Update a conversation - group: conversations - returns: > - Returns the updated - [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object. - path: update - examples: - - title: Update conversation metadata - request: - curl: | - curl https://api.openai.com/v1/conversations/conv_123 \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "metadata": {"topic": "project-x"} - }' - javascript: | - import OpenAI from "openai"; - const client = new OpenAI(); - - const updated = await client.conversations.update( - "conv_123", - { metadata: { topic: "project-x" } } - ); - console.log(updated); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - conversation = client.conversations.update( - conversation_id="conv_123", - metadata={ - "foo": "string" - }, - ) - print(conversation.id) - csharp: | - using System; - using System.Collections.Generic; - using OpenAI.Conversations; - - OpenAIConversationClient client = new( - apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") - ); - - Conversation updated = client.UpdateConversation( - conversationId: "conv_123", - new UpdateConversationOptions - { - Metadata = new Dictionary - { - { "topic", "project-x" } - } - } - ); - Console.WriteLine(updated.Id); - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const conversation = await client.conversations.update('conv_123', { metadata: { foo: 'string' - } }); - - - console.log(conversation.id); - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/conversations" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - conversation, err := client.Conversations.Update( - context.TODO(), - "conv_123", - conversations.ConversationUpdateParams{ - Metadata: shared.Metadata{ - "foo": "string", - }, - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", conversation.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.JsonValue; - import com.openai.models.conversations.Conversation; - import com.openai.models.conversations.ConversationUpdateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ConversationUpdateParams params = ConversationUpdateParams.builder() - .conversationId("conv_123") - .metadata(ConversationUpdateParams.Metadata.builder() - .putAdditionalProperty("foo", JsonValue.from("string")) - .build()) - .build(); - Conversation conversation = client.conversations().update(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - conversation = openai.conversations.update("conv_123", metadata: {foo: "string"}) - - puts(conversation) - response: | - { - "id": "conv_123", - "object": "conversation", - "created_at": 1741900000, - "metadata": {"topic": "project-x"} - } - /videos: - post: - tags: - - Videos - summary: Create video - description: Create a video - operationId: createVideo - parameters: [] - requestBody: - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/CreateVideoBody' - application/json: - schema: - $ref: '#/components/schemas/CreateVideoBody' - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/VideoResource' - x-oaiMeta: - name: Create video - group: videos - path: create - returns: Returns the newly created [video job](https://platform.openai.com/docs/api-reference/videos/object). - examples: - - title: Create a video render - request: - curl: | - curl https://api.openai.com/v1/videos \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -F "model=sora-2" \ - -F "prompt=A calico cat playing a piano on stage" - javascript: | - import OpenAI from 'openai'; - - const openai = new OpenAI(); - - const video = await openai.videos.create({ prompt: 'A calico cat playing a piano on stage' }); - - console.log(video.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - video = client.videos.create( - prompt="x", - ) - print(video.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - video, err := client.Videos.New(context.TODO(), openai.VideoNewParams{ - Prompt: "x", - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", video.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.videos.Video; - import com.openai.models.videos.VideoCreateParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VideoCreateParams params = VideoCreateParams.builder() - .prompt("x") - .build(); - Video video = client.videos().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - video = openai.videos.create(prompt: "x") - - puts(video) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const video = await client.videos.create({ prompt: 'x' }); - - console.log(video.id); - response: | - { - "id": "video_123", - "object": "video", - "model": "sora-2", - "status": "queued", - "progress": 0, - "created_at": 1712697600, - "size": "1024x1808", - "seconds": "8", - "quality": "standard" - } - get: - tags: - - Videos - summary: List videos - description: List videos - operationId: ListVideos - parameters: - - name: limit - in: query - description: Number of items to retrieve - required: false - schema: - type: integer - minimum: 0 - maximum: 100 - - name: order - in: query - description: Sort order of results by timestamp. Use `asc` for ascending order or `desc` for descending order. - required: false - schema: - $ref: '#/components/schemas/OrderEnum' - - name: after - in: query - description: Identifier for the last item from the previous pagination request - required: false - schema: - description: Identifier for the last item from the previous pagination request - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/VideoListResource' - x-oaiMeta: - name: List videos - group: videos - path: list - returns: >- - Returns a paginated list of [video - jobs](https://platform.openai.com/docs/api-reference/videos/object) for the organization. - examples: - - title: List recent videos - request: - curl: | - curl https://api.openai.com/v1/videos \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from 'openai'; - - const openai = new OpenAI(); - - // Automatically fetches more pages as needed. - for await (const video of openai.videos.list()) { - console.log(video.id); - } - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.videos.list() - page = page.data[0] - print(page.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Videos.List(context.TODO(), openai.VideoListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.videos.VideoListPage; - import com.openai.models.videos.VideoListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VideoListPage page = client.videos().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.videos.list - - puts(page) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const video of client.videos.list()) { - console.log(video.id); - } - response: | - { - "data": [ - { - "id": "video_123", - "object": "video", - "model": "sora-2", - "status": "completed" - } - ], - "object": "list" - } - /videos/{video_id}: - get: - tags: - - Videos - summary: Retrieve video - description: Retrieve a video - operationId: GetVideo - parameters: - - name: video_id - in: path - description: The identifier of the video to retrieve. - required: true - schema: - example: video_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/VideoResource' - x-oaiMeta: - name: Retrieve video - group: videos - path: retrieve - returns: >- - Returns the [video job](https://platform.openai.com/docs/api-reference/videos/object) matching the - provided identifier. - examples: - response: '' - request: - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const video = await client.videos.retrieve('video_123'); - - console.log(video.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - video = client.videos.retrieve( - "video_123", - ) - print(video.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - video, err := client.Videos.Get(context.TODO(), "video_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", video.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.videos.Video; - import com.openai.models.videos.VideoRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - Video video = client.videos().retrieve("video_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - video = openai.videos.retrieve("video_123") - - puts(video) - delete: - tags: - - Videos - summary: Delete video - description: Delete a video - operationId: DeleteVideo - parameters: - - name: video_id - in: path - description: The identifier of the video to delete. - required: true - schema: - example: video_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedVideoResource' - x-oaiMeta: - name: Delete video - group: videos - path: delete - returns: Returns the deleted video job metadata. - examples: - response: '' - request: - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const video = await client.videos.delete('video_123'); - - console.log(video.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - video = client.videos.delete( - "video_123", - ) - print(video.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - video, err := client.Videos.Delete(context.TODO(), "video_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", video.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.videos.VideoDeleteParams; - import com.openai.models.videos.VideoDeleteResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VideoDeleteResponse video = client.videos().delete("video_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - video = openai.videos.delete("video_123") - - puts(video) - /videos/{video_id}/content: - get: - tags: - - Videos - summary: Retrieve video content - description: Download video content - operationId: RetrieveVideoContent - parameters: - - name: video_id - in: path - description: The identifier of the video whose media to download. - required: true - schema: - example: video_123 - type: string - - name: variant - in: query - description: Which downloadable asset to return. Defaults to the MP4 video. - required: false - schema: - $ref: '#/components/schemas/VideoContentVariant' - responses: - '200': - description: The video bytes or preview asset that matches the requested variant. - content: - video/mp4: - schema: - type: string - format: binary - image/webp: - schema: - type: string - format: binary - application/json: - schema: - type: string - x-oaiMeta: - name: Retrieve video content - group: videos - path: content - returns: Streams the rendered video content for the specified video job. - examples: - response: '' - request: - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.videos.downloadContent('video_123'); - - console.log(response); - - const content = await response.blob(); - console.log(content); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.videos.download_content( - video_id="video_123", - ) - print(response) - content = response.read() - print(content) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Videos.DownloadContent( - context.TODO(), - "video_123", - openai.VideoDownloadContentParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.core.http.HttpResponse; - import com.openai.models.videos.VideoDownloadContentParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - HttpResponse response = client.videos().downloadContent("video_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.videos.download_content("video_123") - - puts(response) - /videos/{video_id}/remix: - post: - tags: - - Videos - summary: Remix video - description: Create a video remix - operationId: CreateVideoRemix - parameters: - - name: video_id - in: path - description: The identifier of the completed video to remix. - required: true - schema: - example: video_123 - type: string - requestBody: - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/CreateVideoRemixBody' - application/json: - schema: - $ref: '#/components/schemas/CreateVideoRemixBody' - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/VideoResource' - x-oaiMeta: - name: Remix video - group: videos - path: remix - returns: >- - Creates a remix of the specified [video - job](https://platform.openai.com/docs/api-reference/videos/object) using the provided prompt. - examples: - - title: Remix a generated video - request: - curl: | - curl -X POST https://api.openai.com/v1/videos/video_123/remix \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "prompt": "Extend the scene with the cat taking a bow to the cheering audience" - }' - javascript: > - import OpenAI from 'openai'; - - - const client = new OpenAI(); - - - const video = await client.videos.remix('video_123', { prompt: 'Extend the scene with the cat - taking a bow to the cheering audience' }); - - - console.log(video.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - video = client.videos.remix( - video_id="video_123", - prompt="x", - ) - print(video.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - video, err := client.Videos.Remix( - context.TODO(), - "video_123", - openai.VideoRemixParams{ - Prompt: "x", - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", video.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.videos.Video; - import com.openai.models.videos.VideoRemixParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - VideoRemixParams params = VideoRemixParams.builder() - .videoId("video_123") - .prompt("x") - .build(); - Video video = client.videos().remix(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - video = openai.videos.remix("video_123", prompt: "x") - - puts(video) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const video = await client.videos.remix('video_123', { prompt: 'x' }); - - console.log(video.id); - response: | - { - "id": "video_456", - "object": "video", - "model": "sora-2", - "status": "queued", - "progress": 0, - "created_at": 1712698600, - "size": "720x1280", - "seconds": "8", - "remixed_from_video_id": "video_123" - } - /responses/input_tokens: - post: - summary: Get input token counts - description: Get input token counts - operationId: Getinputtokencounts - parameters: [] - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/TokenCountsBody' - application/x-www-form-urlencoded: - schema: - $ref: '#/components/schemas/TokenCountsBody' - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/TokenCountsResource' - x-oaiMeta: - name: Get input token counts - group: responses - returns: | - The input token counts. - ```json - { - object: "response.input_tokens" - input_tokens: 123 - } - ``` - examples: - response: | - { - "object": "response.input_tokens", - "input_tokens": 11 - } - request: - curl: | - curl -X POST https://api.openai.com/v1/responses/input_tokens \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d '{ - "model": "gpt-5", - "input": "Tell me a joke." - }' - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const response = await client.responses.inputTokens.count(); - - console.log(response.input_tokens); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - response = client.responses.input_tokens.count() - print(response.input_tokens) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - response, err := client.Responses.InputTokens.Count(context.TODO(), responses.InputTokenCountParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", response.InputTokens) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.responses.inputtokens.InputTokenCountParams; - import com.openai.models.responses.inputtokens.InputTokenCountResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - InputTokenCountResponse response = client.responses().inputTokens().count(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - response = openai.responses.input_tokens.count - - puts(response) - /chatkit/sessions/{session_id}/cancel: - post: - summary: Cancel chat session - description: Cancel a ChatKit session - operationId: CancelChatSessionMethod - parameters: - - name: session_id - in: path - description: Unique identifier for the ChatKit session to cancel. - required: true - schema: - example: cksess_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ChatSessionResource' - x-oaiMeta: - name: Cancel chat session - group: chatkit - beta: true - path: cancel-session - returns: >- - Returns the chat session after it has been cancelled. Cancelling prevents new requests from using - the issued client secret. - examples: - - title: Cancel a ChatKit session by ID - request: - curl: | - curl -X POST \ - https://api.openai.com/v1/chatkit/sessions/cksess_123/cancel \ - -H "OpenAI-Beta: chatkit_beta=v1" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from 'openai'; - - const client = new OpenAI(); - - const chatSession = await client.beta.chatkit.sessions.cancel('cksess_123'); - - console.log(chatSession.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - chat_session = client.beta.chatkit.sessions.cancel( - "cksess_123", - ) - print(chat_session.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatSession, err := client.Beta.ChatKit.Sessions.Cancel(context.TODO(), "cksess_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatSession.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.chatkit.sessions.SessionCancelParams; - import com.openai.models.beta.chatkit.threads.ChatSession; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatSession chatSession = client.beta().chatkit().sessions().cancel("cksess_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - chat_session = openai.beta.chatkit.sessions.cancel("cksess_123") - - puts(chat_session) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatSession = await client.beta.chatkit.sessions.cancel('cksess_123'); - - console.log(chatSession.id); - response: | - { - "id": "cksess_123", - "object": "chatkit.session", - "workflow": { - "id": "workflow_alpha", - "version": "1" - }, - "scope": { - "customer_id": "cust_456" - }, - "max_requests_per_1_minute": 30, - "ttl_seconds": 900, - "status": "cancelled", - "cancelled_at": 1712345678 - } - /chatkit/sessions: - post: - summary: Create ChatKit session - description: Create a ChatKit session - operationId: CreateChatSessionMethod - parameters: [] - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/CreateChatSessionBody' - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ChatSessionResource' - x-oaiMeta: - name: Create ChatKit session - group: chatkit - beta: true - path: sessions/create - returns: >- - Returns a [ChatKit session](https://platform.openai.com/docs/api-reference/chatkit/sessions/object) - object. - examples: - - title: Create a scoped session - request: - curl: | - curl https://api.openai.com/v1/chatkit/sessions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -H "OpenAI-Beta: chatkit_beta=v1" \ - -d '{ - "workflow": { - "id": "workflow_alpha", - "version": "2024-10-01" - }, - "scope": { - "project": "alpha", - "environment": "staging" - }, - "expires_after": 1800, - "max_requests_per_1_minute": 60, - "max_requests_per_session": 500 - }' - javascript: > - import OpenAI from 'openai'; - - - const client = new OpenAI(); - - - const chatSession = await client.beta.chatkit.sessions.create({ user: 'user', workflow: { id: - 'id' } }); - - - console.log(chatSession.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - chat_session = client.beta.chatkit.sessions.create( - user="x", - workflow={ - "id": "id" - }, - ) - print(chat_session.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatSession, err := client.Beta.ChatKit.Sessions.New(context.TODO(), openai.BetaChatKitSessionNewParams{ - User: "x", - Workflow: openai.ChatSessionWorkflowParam{ - ID: "id", - }, - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatSession.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.chatkit.sessions.SessionCreateParams; - import com.openai.models.beta.chatkit.threads.ChatSession; - import com.openai.models.beta.chatkit.threads.ChatSessionWorkflowParam; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - SessionCreateParams params = SessionCreateParams.builder() - .user("x") - .workflow(ChatSessionWorkflowParam.builder() - .id("id") - .build()) - .build(); - ChatSession chatSession = client.beta().chatkit().sessions().create(params); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - chat_session = openai.beta.chatkit.sessions.create(user: "x", workflow: {id: "id"}) - - puts(chat_session) - node.js: >- - import OpenAI from 'openai'; - - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - - const chatSession = await client.beta.chatkit.sessions.create({ user: 'x', workflow: { id: - 'id' } }); - - - console.log(chatSession.id); - response: | - { - "client_secret": "chatkit_token_123", - "expires_after": 1800, - "workflow": { - "id": "workflow_alpha", - "version": "2024-10-01" - }, - "scope": { - "project": "alpha", - "environment": "staging" - }, - "max_requests_per_1_minute": 60, - "max_requests_per_session": 500, - "status": "active" - } - /chatkit/threads/{thread_id}/items: - get: - summary: List ChatKit thread items - description: List ChatKit thread items - operationId: ListThreadItemsMethod - parameters: - - name: thread_id - in: path - description: Identifier of the ChatKit thread whose items are requested. - required: true - schema: - example: cthr_123 - type: string - - name: limit - in: query - description: Maximum number of thread items to return. Defaults to 20. - required: false - schema: - type: integer - minimum: 0 - maximum: 100 - - name: order - in: query - description: Sort order for results by creation time. Defaults to `desc`. - required: false - schema: - $ref: '#/components/schemas/OrderEnum' - - name: after - in: query - description: List items created after this thread item ID. Defaults to null for the first page. - required: false - schema: - description: List items created after this thread item ID. Defaults to null for the first page. - type: string - - name: before - in: query - description: List items created before this thread item ID. Defaults to null for the newest results. - required: false - schema: - description: List items created before this thread item ID. Defaults to null for the newest results. - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ThreadItemListResource' - x-oaiMeta: - name: List ChatKit thread items - group: chatkit - beta: true - path: threads/list-items - returns: >- - Returns a [list of thread - items](https://platform.openai.com/docs/api-reference/chatkit/threads/item-list) for the specified - thread. - examples: - - title: Retrieve items for a thread - request: - curl: | - curl "https://api.openai.com/v1/chatkit/threads/cthr_abc123/items?limit=3" \ - -H "OpenAI-Beta: chatkit_beta=v1" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from 'openai'; - - const client = new OpenAI(); - - // Automatically fetches more pages as needed. - for await (const thread of client.beta.chatkit.threads.listItems('cthr_123')) { - console.log(thread); - } - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.beta.chatkit.threads.list_items( - thread_id="cthr_123", - ) - page = page.data[0] - print(page) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Beta.ChatKit.Threads.ListItems( - context.TODO(), - "cthr_123", - openai.BetaChatKitThreadListItemsParams{ - - }, - ) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.chatkit.threads.ThreadListItemsPage; - import com.openai.models.beta.chatkit.threads.ThreadListItemsParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadListItemsPage page = client.beta().chatkit().threads().listItems("cthr_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.beta.chatkit.threads.list_items("cthr_123") - - puts(page) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const thread of client.beta.chatkit.threads.listItems('cthr_123')) { - console.log(thread); - } - response: | - { - "data": [ - { - "id": "cthi_user_001", - "object": "chatkit.thread_item", - "type": "user_message", - "content": [ - { - "type": "input_text", - "text": "I need help debugging an onboarding issue." - } - ], - "attachments": [] - }, - { - "id": "cthi_assistant_002", - "object": "chatkit.thread_item", - "type": "assistant_message", - "content": [ - { - "type": "output_text", - "text": "Let's start by confirming the workflow version you deployed." - } - ] - } - ], - "has_more": false, - "object": "list" - } - /chatkit/threads/{thread_id}: - get: - summary: Retrieve ChatKit thread - description: Retrieve a ChatKit thread - operationId: GetThreadMethod - parameters: - - name: thread_id - in: path - description: Identifier of the ChatKit thread to retrieve. - required: true - schema: - example: cthr_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ThreadResource' - x-oaiMeta: - name: Retrieve ChatKit thread - group: chatkit - beta: true - path: threads/retrieve - returns: Returns a [Thread](https://platform.openai.com/docs/api-reference/chatkit/threads/object) object. - examples: - - title: Retrieve a thread by ID - request: - curl: | - curl https://api.openai.com/v1/chatkit/threads/cthr_abc123 \ - -H "OpenAI-Beta: chatkit_beta=v1" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from 'openai'; - - const client = new OpenAI(); - - const chatkitThread = await client.beta.chatkit.threads.retrieve('cthr_123'); - - console.log(chatkitThread.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - chatkit_thread = client.beta.chatkit.threads.retrieve( - "cthr_123", - ) - print(chatkit_thread.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - chatkitThread, err := client.Beta.ChatKit.Threads.Get(context.TODO(), "cthr_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", chatkitThread.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.chatkit.threads.ChatKitThread; - import com.openai.models.beta.chatkit.threads.ThreadRetrieveParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ChatKitThread chatkitThread = client.beta().chatkit().threads().retrieve("cthr_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - chatkit_thread = openai.beta.chatkit.threads.retrieve("cthr_123") - - puts(chatkit_thread) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const chatkitThread = await client.beta.chatkit.threads.retrieve('cthr_123'); - - console.log(chatkitThread.id); - response: | - { - "id": "cthr_abc123", - "object": "chatkit.thread", - "title": "Customer escalation", - "items": { - "data": [ - { - "id": "cthi_user_001", - "object": "chatkit.thread_item", - "type": "user_message", - "content": [ - { - "type": "input_text", - "text": "I need help debugging an onboarding issue." - } - ], - "attachments": [] - }, - { - "id": "cthi_assistant_002", - "object": "chatkit.thread_item", - "type": "assistant_message", - "content": [ - { - "type": "output_text", - "text": "Let's start by confirming the workflow version you deployed." - } - ] - } - ], - "has_more": false - } - } - delete: - summary: Delete ChatKit thread - description: Delete a ChatKit thread - operationId: DeleteThreadMethod - parameters: - - name: thread_id - in: path - description: Identifier of the ChatKit thread to delete. - required: true - schema: - example: cthr_123 - type: string - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/DeletedThreadResource' - x-oaiMeta: - beta: true - examples: - response: '' - request: - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - const thread = await client.beta.chatkit.threads.delete('cthr_123'); - - console.log(thread.id); - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - thread = client.beta.chatkit.threads.delete( - "cthr_123", - ) - print(thread.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - thread, err := client.Beta.ChatKit.Threads.Delete(context.TODO(), "cthr_123") - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", thread.ID) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.chatkit.threads.ThreadDeleteParams; - import com.openai.models.beta.chatkit.threads.ThreadDeleteResponse; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadDeleteResponse thread = client.beta().chatkit().threads().delete("cthr_123"); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - thread = openai.beta.chatkit.threads.delete("cthr_123") - - puts(thread) - name: Delete ChatKit thread - group: chatkit - path: threads/delete - returns: Returns a confirmation object for the deleted thread. - /chatkit/threads: - get: - summary: List ChatKit threads - description: List ChatKit threads - operationId: ListThreadsMethod - parameters: - - name: limit - in: query - description: Maximum number of thread items to return. Defaults to 20. - required: false - schema: - type: integer - minimum: 0 - maximum: 100 - - name: order - in: query - description: Sort order for results by creation time. Defaults to `desc`. - required: false - schema: - $ref: '#/components/schemas/OrderEnum' - - name: after - in: query - description: List items created after this thread item ID. Defaults to null for the first page. - required: false - schema: - description: List items created after this thread item ID. Defaults to null for the first page. - type: string - - name: before - in: query - description: List items created before this thread item ID. Defaults to null for the newest results. - required: false - schema: - description: List items created before this thread item ID. Defaults to null for the newest results. - type: string - - name: user - in: query - description: Filter threads that belong to this user identifier. Defaults to null to return all users. - required: false - schema: - description: Filter threads that belong to this user identifier. Defaults to null to return all users. - type: string - minLength: 1 - maxLength: 512 - responses: - '200': - description: Success - content: - application/json: - schema: - $ref: '#/components/schemas/ThreadListResource' - x-oaiMeta: - name: List ChatKit threads - group: chatkit - beta: true - path: list-threads - returns: Returns a paginated list of ChatKit threads accessible to the request scope. - examples: - - title: List recent threads - request: - curl: | - curl "https://api.openai.com/v1/chatkit/threads?limit=2&order=desc" \ - -H "OpenAI-Beta: chatkit_beta=v1" \ - -H "Authorization: Bearer $OPENAI_API_KEY" - javascript: | - import OpenAI from 'openai'; - - const client = new OpenAI(); - - // Automatically fetches more pages as needed. - for await (const chatkitThread of client.beta.chatkit.threads.list()) { - console.log(chatkitThread.id); - } - python: |- - from openai import OpenAI - - client = OpenAI( - api_key="My API Key", - ) - page = client.beta.chatkit.threads.list() - page = page.data[0] - print(page.id) - go: | - package main - - import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - ) - - func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), - ) - page, err := client.Beta.ChatKit.Threads.List(context.TODO(), openai.BetaChatKitThreadListParams{ - - }) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%+v\n", page) - } - java: |- - package com.openai.example; - - import com.openai.client.OpenAIClient; - import com.openai.client.okhttp.OpenAIOkHttpClient; - import com.openai.models.beta.chatkit.threads.ThreadListPage; - import com.openai.models.beta.chatkit.threads.ThreadListParams; - - public final class Main { - private Main() {} - - public static void main(String[] args) { - OpenAIClient client = OpenAIOkHttpClient.fromEnv(); - - ThreadListPage page = client.beta().chatkit().threads().list(); - } - } - ruby: |- - require "openai" - - openai = OpenAI::Client.new(api_key: "My API Key") - - page = openai.beta.chatkit.threads.list - - puts(page) - node.js: |- - import OpenAI from 'openai'; - - const client = new OpenAI({ - apiKey: 'My API Key', - }); - - // Automatically fetches more pages as needed. - for await (const chatkitThread of client.beta.chatkit.threads.list()) { - console.log(chatkitThread.id); - } - response: | - { - "data": [ - { - "id": "cthr_abc123", - "object": "chatkit.thread", - "title": "Customer escalation" - }, - { - "id": "cthr_def456", - "object": "chatkit.thread", - "title": "Demo feedback" - } - ], - "has_more": false, - "object": "list" - } -webhooks: - batch_cancelled: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookBatchCancelled' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - batch_completed: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookBatchCompleted' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - batch_expired: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookBatchExpired' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - batch_failed: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookBatchFailed' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - eval_run_canceled: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookEvalRunCanceled' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - eval_run_failed: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookEvalRunFailed' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - eval_run_succeeded: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookEvalRunSucceeded' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - fine_tuning_job_cancelled: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookFineTuningJobCancelled' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - fine_tuning_job_failed: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookFineTuningJobFailed' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - fine_tuning_job_succeeded: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookFineTuningJobSucceeded' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - realtime_call_incoming: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookRealtimeCallIncoming' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - response_cancelled: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookResponseCancelled' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - response_completed: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookResponseCompleted' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - response_failed: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookResponseFailed' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. - response_incomplete: - post: - requestBody: - description: The event payload sent by the API. - content: - application/json: - schema: - $ref: '#/components/schemas/WebhookResponseIncomplete' - responses: - '200': - description: | - Return a 200 status code to acknowledge receipt of the event. Non-200 - status codes will be retried. -components: - schemas: - AddUploadPartRequest: - type: object - additionalProperties: false - properties: - data: - description: | - The chunk of bytes for this Part. - type: string - format: binary - required: - - data - AdminApiKey: - type: object - description: Represents an individual Admin API key in an org. - properties: - object: - type: string - example: organization.admin_api_key - description: The object type, which is always `organization.admin_api_key` - x-stainless-const: true - id: - type: string - example: key_abc - description: The identifier, which can be referenced in API endpoints - name: - type: string - example: Administration Key - description: The name of the API key - redacted_value: - type: string - example: sk-admin...def - description: The redacted value of the API key - value: - type: string - example: sk-admin-1234abcd - description: The value of the API key. Only shown on create. - created_at: - type: integer - format: int64 - example: 1711471533 - description: The Unix timestamp (in seconds) of when the API key was created - last_used_at: - anyOf: - - type: integer - format: int64 - example: 1711471534 - description: The Unix timestamp (in seconds) of when the API key was last used - - type: 'null' - owner: - type: object - properties: - type: - type: string - example: user - description: Always `user` - object: - type: string - example: organization.user - description: The object type, which is always organization.user - id: - type: string - example: sa_456 - description: The identifier, which can be referenced in API endpoints - name: - type: string - example: My Service Account - description: The name of the user - created_at: - type: integer - format: int64 - example: 1711471533 - description: The Unix timestamp (in seconds) of when the user was created - role: - type: string - example: owner - description: Always `owner` - required: - - object - - redacted_value - - name - - created_at - - last_used_at - - id - - owner - x-oaiMeta: - name: The admin API key object - example: | - { - "object": "organization.admin_api_key", - "id": "key_abc", - "name": "Main Admin Key", - "redacted_value": "sk-admin...xyz", - "created_at": 1711471533, - "last_used_at": 1711471534, - "owner": { - "type": "user", - "object": "organization.user", - "id": "user_123", - "name": "John Doe", - "created_at": 1711471533, - "role": "owner" - } - } - ApiKeyList: - type: object - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/AdminApiKey' - has_more: - type: boolean - example: false - first_id: - type: string - example: key_abc - last_id: - type: string - example: key_xyz - AssignedRoleDetails: - type: object - description: Detailed information about a role assignment entry returned when listing assignments. - properties: - id: - type: string - description: Identifier for the role. - name: - type: string - description: Name of the role. - permissions: - type: array - description: Permissions associated with the role. - items: - type: string - resource_type: - type: string - description: Resource type the role applies to. - predefined_role: - type: boolean - description: Whether the role is predefined by OpenAI. - description: - description: Description of the role. - anyOf: - - type: string - - type: 'null' - created_at: - description: When the role was created. - anyOf: - - type: integer - format: int64 - - type: 'null' - updated_at: - description: When the role was last updated. - anyOf: - - type: integer - format: int64 - - type: 'null' - created_by: - description: Identifier of the actor who created the role. - anyOf: - - type: string - - type: 'null' - created_by_user_obj: - description: User details for the actor that created the role, when available. - anyOf: - - type: object - additionalProperties: true - - type: 'null' - metadata: - description: Arbitrary metadata stored on the role. - anyOf: - - type: object - additionalProperties: true - - type: 'null' - required: - - id - - name - - permissions - - resource_type - - predefined_role - - description - - created_at - - updated_at - - created_by - - created_by_user_obj - - metadata - AssistantObject: - type: object - title: Assistant - description: Represents an `assistant` that can call the model and use tools. - properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `assistant`. - type: string - enum: - - assistant - x-stainless-const: true - created_at: - description: The Unix timestamp (in seconds) for when the assistant was created. - type: integer - name: - anyOf: - - description: | - The name of the assistant. The maximum length is 256 characters. - type: string - maxLength: 256 - - type: 'null' - description: - anyOf: - - description: | - The description of the assistant. The maximum length is 512 characters. - type: string - maxLength: 512 - - type: 'null' - model: - description: > - ID of the model to use. You can use the [List - models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your - available models, or see our [Model overview](https://platform.openai.com/docs/models) for - descriptions of them. - type: string - instructions: - anyOf: - - description: | - The system instructions that the assistant uses. The maximum length is 256,000 characters. - type: string - maxLength: 256000 - - type: 'null' - tools: - description: > - A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools - can be of types `code_interpreter`, `file_search`, or `function`. - default: [] - type: array - maxItems: 128 - items: - $ref: '#/components/schemas/AssistantTool' - tool_resources: - anyOf: - - type: object - description: > - A set of resources that are used by the assistant's tools. The resources are specific to the - type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the - `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - available to the `code_interpreter`` tool. There can be a maximum of 20 files - associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The ID of the [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached - to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - anyOf: - - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - - type: 'null' - top_p: - anyOf: - - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - - We generally recommend altering this or temperature but not both. - - type: 'null' - response_format: - anyOf: - - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - - type: 'null' - required: - - id - - object - - created_at - - name - - description - - model - - instructions - - tools - - metadata - x-oaiMeta: - name: The assistant object - beta: true - example: | - { - "id": "asst_abc123", - "object": "assistant", - "created_at": 1698984975, - "name": "Math Tutor", - "description": null, - "model": "gpt-4o", - "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", - "tools": [ - { - "type": "code_interpreter" - } - ], - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - } - AssistantStreamEvent: - description: > - Represents an event emitted when streaming a Run. - - - Each event in a server-sent events stream has an `event` and `data` property: - - - ``` - - event: thread.created - - data: {"id": "thread_123", "object": "thread", ...} - - ``` - - - We emit events whenever a new object is created, transitions to a new state, or is being - - streamed in parts (deltas). For example, we emit `thread.run.created` when a new run - - is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses - - to create a message during a run, we emit a `thread.message.created event`, a - - `thread.message.in_progress` event, many `thread.message.delta` events, and finally a - - `thread.message.completed` event. - - - We may add additional events over time, so we recommend handling unknown events gracefully - - in your code. See the [Assistants API - quickstart](https://platform.openai.com/docs/assistants/overview) to learn how to - - integrate the Assistants API with streaming. - x-oaiMeta: - name: Assistant stream events - beta: true - anyOf: - - $ref: '#/components/schemas/ThreadStreamEvent' - - $ref: '#/components/schemas/RunStreamEvent' - - $ref: '#/components/schemas/RunStepStreamEvent' - - $ref: '#/components/schemas/MessageStreamEvent' - - $ref: '#/components/schemas/ErrorEvent' - x-stainless-variantName: error_event - discriminator: - propertyName: event - AssistantSupportedModels: - type: string - enum: - - gpt-5 - - gpt-5-mini - - gpt-5-nano - - gpt-5-2025-08-07 - - gpt-5-mini-2025-08-07 - - gpt-5-nano-2025-08-07 - - gpt-4.1 - - gpt-4.1-mini - - gpt-4.1-nano - - gpt-4.1-2025-04-14 - - gpt-4.1-mini-2025-04-14 - - gpt-4.1-nano-2025-04-14 - - o3-mini - - o3-mini-2025-01-31 - - o1 - - o1-2024-12-17 - - gpt-4o - - gpt-4o-2024-11-20 - - gpt-4o-2024-08-06 - - gpt-4o-2024-05-13 - - gpt-4o-mini - - gpt-4o-mini-2024-07-18 - - gpt-4.5-preview - - gpt-4.5-preview-2025-02-27 - - gpt-4-turbo - - gpt-4-turbo-2024-04-09 - - gpt-4-0125-preview - - gpt-4-turbo-preview - - gpt-4-1106-preview - - gpt-4-vision-preview - - gpt-4 - - gpt-4-0314 - - gpt-4-0613 - - gpt-4-32k - - gpt-4-32k-0314 - - gpt-4-32k-0613 - - gpt-3.5-turbo - - gpt-3.5-turbo-16k - - gpt-3.5-turbo-0613 - - gpt-3.5-turbo-1106 - - gpt-3.5-turbo-0125 - - gpt-3.5-turbo-16k-0613 - AssistantToolsCode: - type: object - title: Code interpreter tool - properties: - type: - type: string - description: 'The type of tool being defined: `code_interpreter`' - enum: - - code_interpreter - x-stainless-const: true - required: - - type - AssistantToolsFileSearch: - type: object - title: FileSearch tool - properties: - type: - type: string - description: 'The type of tool being defined: `file_search`' - enum: - - file_search - x-stainless-const: true - file_search: - type: object - description: Overrides for the file search tool. - properties: - max_num_results: - type: integer - minimum: 1 - maximum: 50 - description: > - The maximum number of results the file search tool should output. The default is 20 for - `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. - - - Note that the file search tool may output fewer than `max_num_results` results. See the [file - search tool - documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - for more information. - ranking_options: - $ref: '#/components/schemas/FileSearchRankingOptions' - required: - - type - AssistantToolsFileSearchTypeOnly: - type: object - title: AssistantToolsFileSearchTypeOnly - properties: - type: - type: string - description: 'The type of tool being defined: `file_search`' - enum: - - file_search - x-stainless-const: true - required: - - type - AssistantToolsFunction: - type: object - title: Function tool - properties: - type: - type: string - description: 'The type of tool being defined: `function`' - enum: - - function - x-stainless-const: true - function: - $ref: '#/components/schemas/FunctionObject' - required: - - type - - function - AssistantsApiResponseFormatOption: - description: > - Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 - Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models - since `gpt-3.5-turbo-1106`. - - - Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures - the model will match your supplied JSON schema. Learn more in the [Structured Outputs - guide](https://platform.openai.com/docs/guides/structured-outputs). - - - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model - generates is valid JSON. - - - **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via - a system or user message. Without this, the model may generate an unending stream of whitespace until - the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. - Also note that the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. - anyOf: - - type: string - description: | - `auto` is the default value - enum: - - auto - x-stainless-const: true - - $ref: '#/components/schemas/ResponseFormatText' - - $ref: '#/components/schemas/ResponseFormatJsonObject' - - $ref: '#/components/schemas/ResponseFormatJsonSchema' - AssistantsApiToolChoiceOption: - description: > - Controls which (if any) tool is called by the model. - - `none` means the model will not call any tools and instead generates a message. - - `auto` is the default value and means the model can pick between generating a message or calling one - or more tools. - - `required` means the model must call one or more tools before responding to the user. - - Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": - {"name": "my_function"}}` forces the model to call that tool. - anyOf: - - type: string - description: > - `none` means the model will not call any tools and instead generates a message. `auto` means the - model can pick between generating a message or calling one or more tools. `required` means the - model must call one or more tools before responding to the user. - enum: - - none - - auto - - required - title: Auto - - $ref: '#/components/schemas/AssistantsNamedToolChoice' - AssistantsNamedToolChoice: - type: object - description: Specifies a tool the model should use. Use to force the model to call a specific tool. - properties: - type: - type: string - enum: - - function - - code_interpreter - - file_search - description: The type of the tool. If type is `function`, the function name must be set - function: - type: object - properties: - name: - type: string - description: The name of the function to call. - required: - - name - required: - - type - AudioResponseFormat: - description: > - The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, `vtt`, or - `diarized_json`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is - `json`. For `gpt-4o-transcribe-diarize`, the supported formats are `json`, `text`, and - `diarized_json`, with `diarized_json` required to receive speaker annotations. - type: string - enum: - - json - - text - - srt - - verbose_json - - vtt - - diarized_json - default: json - AudioTranscription: - type: object - properties: - model: - type: string - description: > - The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, - `gpt-4o-transcribe`, and `gpt-4o-transcribe-diarize`. Use `gpt-4o-transcribe-diarize` when you - need diarization with speaker labels. - enum: - - whisper-1 - - gpt-4o-mini-transcribe - - gpt-4o-transcribe - - gpt-4o-transcribe-diarize - language: - type: string - description: | - 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. - prompt: - type: string - description: > - 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 (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text - string, for example "expect words related to technology". - AuditLog: - type: object - description: A log of a user action or configuration change within this organization. - properties: - id: - type: string - description: The ID of this log. - type: - $ref: '#/components/schemas/AuditLogEventType' - effective_at: - type: integer - description: The Unix timestamp (in seconds) of the event. - project: - type: object - description: >- - The project that the action was scoped to. Absent for actions not scoped to projects. Note that - any admin actions taken via Admin API keys are associated with the default project. - properties: - id: - type: string - description: The project ID. - name: - type: string - description: The project title. - actor: - $ref: '#/components/schemas/AuditLogActor' - api_key.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The tracking ID of the API key. - data: - type: object - description: The payload used to create the API key. - properties: - scopes: - type: array - items: - type: string - description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` - api_key.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The tracking ID of the API key. - changes_requested: - type: object - description: The payload used to update the API key. - properties: - scopes: - type: array - items: - type: string - description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` - api_key.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The tracking ID of the API key. - checkpoint.permission.created: - type: object - description: The project and fine-tuned model checkpoint that the checkpoint permission was created for. - properties: - id: - type: string - description: The ID of the checkpoint permission. - data: - type: object - description: The payload used to create the checkpoint permission. - properties: - project_id: - type: string - description: The ID of the project that the checkpoint permission was created for. - fine_tuned_model_checkpoint: - type: string - description: The ID of the fine-tuned model checkpoint. - checkpoint.permission.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the checkpoint permission. - external_key.registered: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the external key configuration. - data: - type: object - description: The configuration for the external key. - external_key.removed: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the external key configuration. - group.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the group. - data: - type: object - description: Information about the created group. - properties: - group_name: - type: string - description: The group name. - group.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the group. - changes_requested: - type: object - description: The payload used to update the group. - properties: - group_name: - type: string - description: The updated group name. - group.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the group. - scim.enabled: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the SCIM was enabled for. - scim.disabled: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the SCIM was disabled for. - invite.sent: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the invite. - data: - type: object - description: The payload used to create the invite. - properties: - email: - type: string - description: The email invited to the organization. - role: - type: string - description: The role the email was invited to be. Is either `owner` or `member`. - invite.accepted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the invite. - invite.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the invite. - ip_allowlist.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the IP allowlist configuration. - name: - type: string - description: The name of the IP allowlist configuration. - allowed_ips: - type: array - description: The IP addresses or CIDR ranges included in the configuration. - items: - type: string - ip_allowlist.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the IP allowlist configuration. - allowed_ips: - type: array - description: The updated set of IP addresses or CIDR ranges in the configuration. - items: - type: string - ip_allowlist.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The ID of the IP allowlist configuration. - name: - type: string - description: The name of the IP allowlist configuration. - allowed_ips: - type: array - description: The IP addresses or CIDR ranges that were in the configuration. - items: - type: string - ip_allowlist.config.activated: - type: object - description: The details for events with this `type`. - properties: - configs: - type: array - description: The configurations that were activated. - items: - type: object - properties: - id: - type: string - description: The ID of the IP allowlist configuration. - name: - type: string - description: The name of the IP allowlist configuration. - ip_allowlist.config.deactivated: - type: object - description: The details for events with this `type`. - properties: - configs: - type: array - description: The configurations that were deactivated. - items: - type: object - properties: - id: - type: string - description: The ID of the IP allowlist configuration. - name: - type: string - description: The name of the IP allowlist configuration. - login.succeeded: - type: object - description: This event has no additional fields beyond the standard audit log attributes. - login.failed: - type: object - description: The details for events with this `type`. - properties: - error_code: - type: string - description: The error code of the failure. - error_message: - type: string - description: The error message of the failure. - logout.succeeded: - type: object - description: This event has no additional fields beyond the standard audit log attributes. - logout.failed: - type: object - description: The details for events with this `type`. - properties: - error_code: - type: string - description: The error code of the failure. - error_message: - type: string - description: The error message of the failure. - organization.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The organization ID. - changes_requested: - type: object - description: The payload used to update the organization settings. - properties: - title: - type: string - description: The organization title. - description: - type: string - description: The organization description. - name: - type: string - description: The organization name. - threads_ui_visibility: - type: string - description: >- - Visibility of the threads page which shows messages created with the Assistants API and - Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. - usage_dashboard_visibility: - type: string - description: >- - Visibility of the usage dashboard which shows activity and costs for your organization. - One of `ANY_ROLE` or `OWNERS`. - api_call_logging: - type: string - description: >- - How your organization logs data from supported API calls. One of `disabled`, - `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects` - api_call_logging_project_ids: - type: string - description: The list of project ids if api_call_logging is set to `enabled_for_selected_projects` - project.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The project ID. - data: - type: object - description: The payload used to create the project. - properties: - name: - type: string - description: The project name. - title: - type: string - description: The title of the project as seen on the dashboard. - project.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The project ID. - changes_requested: - type: object - description: The payload used to update the project. - properties: - title: - type: string - description: The title of the project as seen on the dashboard. - project.archived: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The project ID. - project.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The project ID. - rate_limit.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The rate limit ID - changes_requested: - type: object - description: The payload used to update the rate limits. - properties: - max_requests_per_1_minute: - type: integer - description: The maximum requests per minute. - max_tokens_per_1_minute: - type: integer - description: The maximum tokens per minute. - max_images_per_1_minute: - type: integer - description: The maximum images per minute. Only relevant for certain models. - max_audio_megabytes_per_1_minute: - type: integer - description: The maximum audio megabytes per minute. Only relevant for certain models. - max_requests_per_1_day: - type: integer - description: The maximum requests per day. Only relevant for certain models. - batch_1_day_max_input_tokens: - type: integer - description: The maximum batch input tokens per day. Only relevant for certain models. - rate_limit.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The rate limit ID - role.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The role ID. - role_name: - type: string - description: The name of the role. - permissions: - type: array - items: - type: string - description: The permissions granted by the role. - resource_type: - type: string - description: The type of resource the role belongs to. - resource_id: - type: string - description: The resource the role is scoped to. - role.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The role ID. - changes_requested: - type: object - description: The payload used to update the role. - properties: - role_name: - type: string - description: The updated role name, when provided. - resource_id: - type: string - description: The resource the role is scoped to. - resource_type: - type: string - description: The type of resource the role belongs to. - permissions_added: - type: array - items: - type: string - description: The permissions added to the role. - permissions_removed: - type: array - items: - type: string - description: The permissions removed from the role. - description: - type: string - description: The updated role description, when provided. - metadata: - type: object - description: Additional metadata stored on the role. - role.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The role ID. - role.assignment.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The identifier of the role assignment. - principal_id: - type: string - description: The principal (user or group) that received the role. - principal_type: - type: string - description: The type of principal (user or group) that received the role. - resource_id: - type: string - description: The resource the role assignment is scoped to. - resource_type: - type: string - description: The type of resource the role assignment is scoped to. - role.assignment.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The identifier of the role assignment. - principal_id: - type: string - description: The principal (user or group) that had the role removed. - principal_type: - type: string - description: The type of principal (user or group) that had the role removed. - resource_id: - type: string - description: The resource the role assignment was scoped to. - resource_type: - type: string - description: The type of resource the role assignment was scoped to. - service_account.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The service account ID. - data: - type: object - description: The payload used to create the service account. - properties: - role: - type: string - description: The role of the service account. Is either `owner` or `member`. - service_account.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The service account ID. - changes_requested: - type: object - description: The payload used to updated the service account. - properties: - role: - type: string - description: The role of the service account. Is either `owner` or `member`. - service_account.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The service account ID. - user.added: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The user ID. - data: - type: object - description: The payload used to add the user to the project. - properties: - role: - type: string - description: The role of the user. Is either `owner` or `member`. - user.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The project ID. - changes_requested: - type: object - description: The payload used to update the user. - properties: - role: - type: string - description: The role of the user. Is either `owner` or `member`. - user.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The user ID. - certificate.created: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The certificate ID. - name: - type: string - description: The name of the certificate. - certificate.updated: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The certificate ID. - name: - type: string - description: The name of the certificate. - certificate.deleted: - type: object - description: The details for events with this `type`. - properties: - id: - type: string - description: The certificate ID. - name: - type: string - description: The name of the certificate. - certificate: - type: string - description: The certificate content in PEM format. - certificates.activated: - type: object - description: The details for events with this `type`. - properties: - certificates: - type: array - items: - type: object - properties: - id: - type: string - description: The certificate ID. - name: - type: string - description: The name of the certificate. - certificates.deactivated: - type: object - description: The details for events with this `type`. - properties: - certificates: - type: array - items: - type: object - properties: - id: - type: string - description: The certificate ID. - name: - type: string - description: The name of the certificate. - required: - - id - - type - - effective_at - - actor - x-oaiMeta: - name: The audit log object - example: | - { - "id": "req_xxx_20240101", - "type": "api_key.created", - "effective_at": 1720804090, - "actor": { - "type": "session", - "session": { - "user": { - "id": "user-xxx", - "email": "user@example.com" - }, - "ip_address": "127.0.0.1", - "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" - } - }, - "api_key.created": { - "id": "key_xxxx", - "data": { - "scopes": ["resource.operation"] - } - } - } - AuditLogActor: - type: object - description: The actor who performed the audit logged action. - properties: - type: - type: string - description: The type of actor. Is either `session` or `api_key`. - enum: - - session - - api_key - session: - $ref: '#/components/schemas/AuditLogActorSession' - api_key: - $ref: '#/components/schemas/AuditLogActorApiKey' - AuditLogActorApiKey: - type: object - description: The API Key used to perform the audit logged action. - properties: - id: - type: string - description: The tracking id of the API key. - type: - type: string - description: The type of API key. Can be either `user` or `service_account`. - enum: - - user - - service_account - user: - $ref: '#/components/schemas/AuditLogActorUser' - service_account: - $ref: '#/components/schemas/AuditLogActorServiceAccount' - AuditLogActorServiceAccount: - type: object - description: The service account that performed the audit logged action. - properties: - id: - type: string - description: The service account id. - AuditLogActorSession: - type: object - description: The session in which the audit logged action was performed. - properties: - user: - $ref: '#/components/schemas/AuditLogActorUser' - ip_address: - type: string - description: The IP address from which the action was performed. - AuditLogActorUser: - type: object - description: The user who performed the audit logged action. - properties: - id: - type: string - description: The user id. - email: - type: string - description: The user email. - AuditLogEventType: - type: string - description: The event type. - enum: - - api_key.created - - api_key.updated - - api_key.deleted - - certificate.created - - certificate.updated - - certificate.deleted - - certificates.activated - - certificates.deactivated - - checkpoint.permission.created - - checkpoint.permission.deleted - - external_key.registered - - external_key.removed - - group.created - - group.updated - - group.deleted - - invite.sent - - invite.accepted - - invite.deleted - - ip_allowlist.created - - ip_allowlist.updated - - ip_allowlist.deleted - - ip_allowlist.config.activated - - ip_allowlist.config.deactivated - - login.succeeded - - login.failed - - logout.succeeded - - logout.failed - - organization.updated - - project.created - - project.updated - - project.archived - - project.deleted - - rate_limit.updated - - rate_limit.deleted - - resource.deleted - - role.created - - role.updated - - role.deleted - - role.assignment.created - - role.assignment.deleted - - scim.enabled - - scim.disabled - - service_account.created - - service_account.updated - - service_account.deleted - - user.added - - user.updated - - user.deleted - AutoChunkingStrategyRequestParam: - type: object - title: Auto Chunking Strategy - description: >- - The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and - `chunk_overlap_tokens` of `400`. - additionalProperties: false - properties: - type: - type: string - description: Always `auto`. - enum: - - auto - x-stainless-const: true - required: - - type - Batch: - type: object - properties: - id: - type: string - object: - type: string - enum: - - batch - description: The object type, which is always `batch`. - x-stainless-const: true - endpoint: - type: string - description: The OpenAI API endpoint used by the batch. - model: - type: string - description: | - Model ID used to process the batch, like `gpt-5-2025-08-07`. OpenAI - offers a wide range of models with different capabilities, performance - characteristics, and price points. Refer to the [model - guide](https://platform.openai.com/docs/models) to browse and compare available models. - errors: - type: object - properties: - object: - type: string - description: The object type, which is always `list`. - data: - type: array - items: - $ref: '#/components/schemas/BatchError' - input_file_id: - type: string - description: The ID of the input file for the batch. - completion_window: - type: string - description: The time frame within which the batch should be processed. - status: - type: string - description: The current status of the batch. - enum: - - validating - - failed - - in_progress - - finalizing - - completed - - expired - - cancelling - - cancelled - output_file_id: - type: string - description: The ID of the file containing the outputs of successfully executed requests. - error_file_id: - type: string - description: The ID of the file containing the outputs of requests with errors. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch was created. - in_progress_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch started processing. - expires_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch will expire. - finalizing_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch started finalizing. - completed_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch was completed. - failed_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch failed. - expired_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch expired. - cancelling_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch started cancelling. - cancelled_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch was cancelled. - request_counts: - $ref: '#/components/schemas/BatchRequestCounts' - usage: - type: object - description: | - Represents token usage details including input tokens, output tokens, a - breakdown of output tokens, and the total tokens used. Only populated on - batches created after September 7, 2025. - properties: - input_tokens: - type: integer - description: The number of input tokens. - input_tokens_details: - type: object - description: A detailed breakdown of the input tokens. - properties: - cached_tokens: - type: integer - description: | - The number of tokens that were retrieved from the cache. [More on - prompt caching](https://platform.openai.com/docs/guides/prompt-caching). - required: - - cached_tokens - output_tokens: - type: integer - description: The number of output tokens. - output_tokens_details: - type: object - description: A detailed breakdown of the output tokens. - properties: - reasoning_tokens: - type: integer - description: The number of reasoning tokens. - required: - - reasoning_tokens - total_tokens: - type: integer - description: The total number of tokens used. - required: - - input_tokens - - input_tokens_details - - output_tokens - - output_tokens_details - - total_tokens - metadata: - $ref: '#/components/schemas/Metadata' - required: - - id - - object - - endpoint - - input_file_id - - completion_window - - status - - created_at - x-oaiMeta: - name: The batch object - example: | - { - "id": "batch_abc123", - "object": "batch", - "endpoint": "/v1/completions", - "model": "gpt-5-2025-08-07", - "errors": null, - "input_file_id": "file-abc123", - "completion_window": "24h", - "status": "completed", - "output_file_id": "file-cvaTdG", - "error_file_id": "file-HOWS94", - "created_at": 1711471533, - "in_progress_at": 1711471538, - "expires_at": 1711557933, - "finalizing_at": 1711493133, - "completed_at": 1711493163, - "failed_at": null, - "expired_at": null, - "cancelling_at": null, - "cancelled_at": null, - "request_counts": { - "total": 100, - "completed": 95, - "failed": 5 - }, - "usage": { - "input_tokens": 1500, - "input_tokens_details": { - "cached_tokens": 1024 - }, - "output_tokens": 500, - "output_tokens_details": { - "reasoning_tokens": 300 - }, - "total_tokens": 2000 - }, - "metadata": { - "customer_id": "user_123456789", - "batch_description": "Nightly eval job", - } - } - BatchFileExpirationAfter: - type: object - title: File expiration policy - description: The expiration policy for the output and/or error file that are generated for a batch. - properties: - anchor: - description: >- - Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note - that the anchor is the file creation time, not the time the batch is created. - type: string - enum: - - created_at - x-stainless-const: true - seconds: - description: >- - The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 - hour) and 2592000 (30 days). - type: integer - minimum: 3600 - maximum: 2592000 - required: - - anchor - - seconds - BatchRequestInput: - type: object - description: The per-line object of the batch input file - properties: - custom_id: - type: string - description: >- - A developer-provided per-request id that will be used to match outputs to inputs. Must be unique - for each request in a batch. - method: - type: string - enum: - - POST - description: The HTTP method to be used for the request. Currently only `POST` is supported. - x-stainless-const: true - url: - type: string - description: >- - The OpenAI API relative URL to be used for the request. Currently `/v1/responses`, - `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, and `/v1/moderations` are supported. - x-oaiMeta: - name: The request input object - example: > - {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": - "gpt-4o-mini", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": - "user", "content": "What is 2+2?"}]}} - BatchRequestOutput: - type: object - description: The per-line object of the batch output and error files - properties: - id: - type: string - custom_id: - type: string - description: A developer-provided per-request id that will be used to match outputs to inputs. - response: - anyOf: - - type: object - properties: - status_code: - type: integer - description: The HTTP status code of the response - request_id: - type: string - description: >- - An unique identifier for the OpenAI API request. Please include this request ID when - contacting support. - body: - type: object - x-oaiTypeLabel: map - description: The JSON body of the response - - type: 'null' - error: - anyOf: - - type: object - description: >- - For requests that failed with a non-HTTP error, this will contain more information on the - cause of the failure. - properties: - code: - type: string - description: | - A machine-readable error code. - - Possible values: - - `batch_expired`: The request could not be executed before the - completion window ended. - - `batch_cancelled`: The batch was cancelled before this request - executed. - - `request_timeout`: The underlying call to the model timed out. - message: - type: string - description: A human-readable error message. - - type: 'null' - x-oaiMeta: - name: The request output object - example: > - {"id": "batch_req_wnaDys", "custom_id": "request-2", "response": {"status_code": 200, "request_id": - "req_c187b3", "body": {"id": "chatcmpl-9758Iw", "object": "chat.completion", "created": 1711475054, - "model": "gpt-4o-mini", "choices": [{"index": 0, "message": {"role": "assistant", "content": "2 + 2 - equals 4."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 24, "completion_tokens": 15, - "total_tokens": 39}, "system_fingerprint": null}}, "error": null} - Certificate: - type: object - description: Represents an individual `certificate` uploaded to the organization. - properties: - object: - type: string - enum: - - certificate - - organization.certificate - - organization.project.certificate - description: > - The object type. - - - - If creating, updating, or getting a specific certificate, the object type is `certificate`. - - - If listing, activating, or deactivating certificates for the organization, the object type is - `organization.certificate`. - - - If listing, activating, or deactivating certificates for a project, the object type is - `organization.project.certificate`. - x-stainless-const: true - id: - type: string - description: The identifier, which can be referenced in API endpoints - name: - type: string - description: The name of the certificate. - created_at: - type: integer - description: The Unix timestamp (in seconds) of when the certificate was uploaded. - certificate_details: - type: object - properties: - valid_at: - type: integer - description: The Unix timestamp (in seconds) of when the certificate becomes valid. - expires_at: - type: integer - description: The Unix timestamp (in seconds) of when the certificate expires. - content: - type: string - description: The content of the certificate in PEM format. - active: - type: boolean - description: >- - Whether the certificate is currently active at the specified scope. Not returned when getting - details for a specific certificate. - required: - - object - - id - - name - - created_at - - certificate_details - x-oaiMeta: - name: The certificate object - example: | - { - "object": "certificate", - "id": "cert_abc", - "name": "My Certificate", - "created_at": 1234567, - "certificate_details": { - "valid_at": 1234567, - "expires_at": 12345678, - "content": "-----BEGIN CERTIFICATE----- MIIGAjCCA...6znFlOW+ -----END CERTIFICATE-----" - } - } - ChatCompletionAllowedTools: - type: object - title: Allowed tools - description: | - Constrains the tools available to the model to a pre-defined set. - properties: - mode: - type: string - enum: - - auto - - required - description: | - Constrains the tools available to the model to a pre-defined set. - - `auto` allows the model to pick from among the allowed tools and generate a - message. - - `required` requires the model to call one or more of the allowed tools. - tools: - type: array - description: | - A list of tool definitions that the model should be allowed to call. - - For the Chat Completions API, the list of tool definitions might look like: - ```json - [ - { "type": "function", "function": { "name": "get_weather" } }, - { "type": "function", "function": { "name": "get_time" } } - ] - ``` - items: - type: object - x-oaiExpandable: false - description: | - A tool definition that the model should be allowed to call. - additionalProperties: true - required: - - mode - - tools - ChatCompletionAllowedToolsChoice: - type: object - title: Allowed tools - description: | - Constrains the tools available to the model to a pre-defined set. - properties: - type: - type: string - enum: - - allowed_tools - description: Allowed tool configuration type. Always `allowed_tools`. - x-stainless-const: true - allowed_tools: - $ref: '#/components/schemas/ChatCompletionAllowedTools' - required: - - type - - allowed_tools - ChatCompletionDeleted: - type: object - properties: - object: - type: string - description: The type of object being deleted. - enum: - - chat.completion.deleted - x-stainless-const: true - id: - type: string - description: The ID of the chat completion that was deleted. - deleted: - type: boolean - description: Whether the chat completion was deleted. - required: - - object - - id - - deleted - ChatCompletionFunctionCallOption: - type: object - description: | - Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. - properties: - name: - type: string - description: The name of the function to call. - required: - - name - x-stainless-variantName: function_call_option - ChatCompletionFunctions: - type: object - deprecated: true - properties: - description: - type: string - description: >- - A description of what the function does, used by the model to choose when and how to call the - function. - name: - type: string - description: >- - The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, - with a maximum length of 64. - parameters: - $ref: '#/components/schemas/FunctionParameters' - required: - - name - ChatCompletionList: - type: object - title: ChatCompletionList - description: | - An object representing a list of Chat Completions. - properties: - object: - type: string - enum: - - list - default: list - description: | - The type of this object. It is always set to "list". - x-stainless-const: true - data: - type: array - description: | - An array of chat completion objects. - items: - $ref: '#/components/schemas/CreateChatCompletionResponse' - first_id: - type: string - description: The identifier of the first chat completion in the data array. - last_id: - type: string - description: The identifier of the last chat completion in the data array. - has_more: - type: boolean - description: Indicates whether there are more Chat Completions available. - required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: The chat completion list object - group: chat - example: | - { - "object": "list", - "data": [ - { - "object": "chat.completion", - "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "model": "gpt-4o-2024-08-06", - "created": 1738960610, - "request_id": "req_ded8ab984ec4bf840f37566c1011c417", - "tool_choice": null, - "usage": { - "total_tokens": 31, - "completion_tokens": 18, - "prompt_tokens": 13 - }, - "seed": 4944116822809979520, - "top_p": 1.0, - "temperature": 1.0, - "presence_penalty": 0.0, - "frequency_penalty": 0.0, - "system_fingerprint": "fp_50cad350e4", - "input_user": null, - "service_tier": "default", - "tools": null, - "metadata": {}, - "choices": [ - { - "index": 0, - "message": { - "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", - "role": "assistant", - "tool_calls": null, - "function_call": null - }, - "finish_reason": "stop", - "logprobs": null - } - ], - "response_format": null - } - ], - "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", - "has_more": false - } - ChatCompletionMessageCustomToolCall: - type: object - title: Custom tool call - description: | - A call to a custom tool created by the model. - properties: - id: - type: string - description: The ID of the tool call. - type: - type: string - enum: - - custom - description: The type of the tool. Always `custom`. - x-stainless-const: true - custom: - type: object - description: The custom tool that the model called. - properties: - name: - type: string - description: The name of the custom tool to call. - input: - type: string - description: The input for the custom tool call generated by the model. - required: - - name - - input - required: - - id - - type - - custom - ChatCompletionMessageList: - type: object - title: ChatCompletionMessageList - description: | - An object representing a list of chat completion messages. - properties: - object: - type: string - enum: - - list - default: list - description: | - The type of this object. It is always set to "list". - x-stainless-const: true - data: - type: array - description: | - An array of chat completion message objects. - items: - allOf: - - $ref: '#/components/schemas/ChatCompletionResponseMessage' - - type: object - required: - - id - properties: - id: - type: string - description: The identifier of the chat message. - content_parts: - anyOf: - - type: array - description: > - If a content parts array was provided, this is an array of `text` and `image_url` - parts. - - Otherwise, null. - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' - - type: 'null' - first_id: - type: string - description: The identifier of the first chat message in the data array. - last_id: - type: string - description: The identifier of the last chat message in the data array. - has_more: - type: boolean - description: Indicates whether there are more chat messages available. - required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: The chat completion message list object - group: chat - example: | - { - "object": "list", - "data": [ - { - "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", - "role": "user", - "content": "write a haiku about ai", - "name": null, - "content_parts": null - } - ], - "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", - "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", - "has_more": false - } - ChatCompletionMessageToolCall: - type: object - title: Function tool call - description: | - A call to a function tool created by the model. - properties: - id: - type: string - description: The ID of the tool call. - type: - type: string - enum: - - function - description: The type of the tool. Currently, only `function` is supported. - x-stainless-const: true - function: - type: object - description: The function that the model called. - properties: - name: - type: string - description: The name of the function to call. - arguments: - type: string - description: >- - The arguments to call the function with, as generated by the model in JSON format. Note that - the model does not always generate valid JSON, and may hallucinate parameters not defined by - your function schema. Validate the arguments in your code before calling your function. - required: - - name - - arguments - required: - - id - - type - - function - ChatCompletionMessageToolCallChunk: - type: object - properties: - index: - type: integer - id: - type: string - description: The ID of the tool call. - type: - type: string - enum: - - function - description: The type of the tool. Currently, only `function` is supported. - x-stainless-const: true - function: - type: object - properties: - name: - type: string - description: The name of the function to call. - arguments: - type: string - description: >- - The arguments to call the function with, as generated by the model in JSON format. Note that - the model does not always generate valid JSON, and may hallucinate parameters not defined by - your function schema. Validate the arguments in your code before calling your function. - required: - - index - ChatCompletionMessageToolCalls: - type: array - description: The tool calls generated by the model, such as function calls. - items: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ChatCompletionMessageToolCall' - - $ref: '#/components/schemas/ChatCompletionMessageCustomToolCall' - x-stainless-naming: - python: - model_name: chat_completion_message_tool_call_union - param_model_name: chat_completion_message_tool_call_union_param - x-stainless-go-variant-constructor: skip - ChatCompletionModalities: - anyOf: - - type: array - description: > - Output types that you would like the model to generate for this request. - - Most models are capable of generating text, which is the default: - - - `["text"]` - - - The `gpt-4o-audio-preview` model can also be used to [generate - audio](https://platform.openai.com/docs/guides/audio). To - - request that this model generate both text and audio responses, you can - - use: - - - `["text", "audio"]` - items: - type: string - enum: - - text - - audio - - type: 'null' - ChatCompletionNamedToolChoice: - type: object - title: Function tool choice - description: Specifies a tool the model should use. Use to force the model to call a specific function. - properties: - type: - type: string - enum: - - function - description: For function calling, the type is always `function`. - x-stainless-const: true - function: - type: object - properties: - name: - type: string - description: The name of the function to call. - required: - - name - required: - - type - - function - ChatCompletionNamedToolChoiceCustom: - type: object - title: Custom tool choice - description: Specifies a tool the model should use. Use to force the model to call a specific custom tool. - properties: - type: - type: string - enum: - - custom - description: For custom tool calling, the type is always `custom`. - x-stainless-const: true - custom: - type: object - properties: - name: - type: string - description: The name of the custom tool to call. - required: - - name - required: - - type - - custom - ChatCompletionRequestAssistantMessage: - type: object - title: Assistant message - description: | - Messages sent by the model in response to user messages. - properties: - content: - anyOf: - - description: > - The contents of the assistant message. Required unless `tool_calls` or `function_call` is - specified. - anyOf: - - type: string - description: The contents of the assistant message. - title: Text content - - type: array - description: >- - An array of content parts with a defined type. Can be one or more of type `text`, or - exactly one of type `refusal`. - title: Array of content parts - items: - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessageContentPart' - minItems: 1 - - type: 'null' - refusal: - anyOf: - - type: string - description: The refusal message by the assistant. - - type: 'null' - role: - type: string - enum: - - assistant - description: The role of the messages author, in this case `assistant`. - x-stainless-const: true - name: - type: string - description: >- - An optional name for the participant. Provides the model information to differentiate between - participants of the same role. - audio: - anyOf: - - type: object - description: | - Data about a previous audio response from the model. - [Learn more](https://platform.openai.com/docs/guides/audio). - required: - - id - properties: - id: - type: string - description: | - Unique identifier for a previous audio response from the model. - - type: 'null' - tool_calls: - $ref: '#/components/schemas/ChatCompletionMessageToolCalls' - function_call: - anyOf: - - type: object - deprecated: true - description: >- - Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be - called, as generated by the model. - properties: - arguments: - type: string - description: >- - The arguments to call the function with, as generated by the model in JSON format. Note - that the model does not always generate valid JSON, and may hallucinate parameters not - defined by your function schema. Validate the arguments in your code before calling your - function. - name: - type: string - description: The name of the function to call. - required: - - arguments - - name - - type: 'null' - required: - - role - x-stainless-soft-required: - - content - ChatCompletionRequestAssistantMessageContentPart: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' - ChatCompletionRequestDeveloperMessage: - type: object - title: Developer message - description: | - Developer-provided instructions that the model should follow, regardless of - messages sent by the user. With o1 models and newer, `developer` messages - replace the previous `system` messages. - properties: - content: - description: The contents of the developer message. - anyOf: - - type: string - description: The contents of the developer message. - title: Text content - - type: array - description: >- - An array of content parts with a defined type. For developer messages, only type `text` is - supported. - title: Array of content parts - items: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - minItems: 1 - role: - type: string - enum: - - developer - description: The role of the messages author, in this case `developer`. - x-stainless-const: true - name: - type: string - description: >- - An optional name for the participant. Provides the model information to differentiate between - participants of the same role. - required: - - content - - role - x-stainless-naming: - go: - variant_constructor: DeveloperMessage - ChatCompletionRequestFunctionMessage: - type: object - title: Function message - deprecated: true - properties: - role: - type: string - enum: - - function - description: The role of the messages author, in this case `function`. - x-stainless-const: true - content: - anyOf: - - type: string - description: The contents of the function message. - - type: 'null' - name: - type: string - description: The name of the function to call. - required: - - role - - content - - name - ChatCompletionRequestMessage: - discriminator: - propertyName: role - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestDeveloperMessage' - - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' - - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' - - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' - ChatCompletionRequestMessageContentPartAudio: - type: object - title: Audio content part - description: | - Learn about [audio inputs](https://platform.openai.com/docs/guides/audio). - properties: - type: - type: string - enum: - - input_audio - description: The type of the content part. Always `input_audio`. - x-stainless-const: true - input_audio: - type: object - properties: - data: - type: string - description: Base64 encoded audio data. - format: - type: string - enum: - - wav - - mp3 - description: | - The format of the encoded audio data. Currently supports "wav" and "mp3". - required: - - data - - format - required: - - type - - input_audio - x-stainless-naming: - go: - variant_constructor: InputAudioContentPart - ChatCompletionRequestMessageContentPartFile: - type: object - title: File content part - description: | - Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text generation. - properties: - type: - type: string - enum: - - file - description: The type of the content part. Always `file`. - x-stainless-const: true - file: - type: object - properties: - filename: - type: string - description: | - The name of the file, used when passing the file to the model as a - string. - file_data: - type: string - description: | - The base64 encoded file data, used when passing the file to the model - as a string. - file_id: - type: string - description: | - The ID of an uploaded file to use as input. - x-stainless-naming: - java: - type_name: FileObject - kotlin: - type_name: FileObject - required: - - type - - file - x-stainless-naming: - go: - variant_constructor: FileContentPart - ChatCompletionRequestMessageContentPartImage: - type: object - title: Image content part - description: | - Learn about [image inputs](https://platform.openai.com/docs/guides/vision). - properties: - type: - type: string - enum: - - image_url - description: The type of the content part. - x-stainless-const: true - image_url: - type: object - properties: - url: - type: string - description: Either a URL of the image or the base64 encoded image data. - format: uri - detail: - type: string - description: >- - Specifies the detail level of the image. Learn more in the [Vision - guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). - enum: - - auto - - low - - high - default: auto - required: - - url - required: - - type - - image_url - x-stainless-naming: - go: - variant_constructor: ImageContentPart - ChatCompletionRequestMessageContentPartRefusal: - type: object - title: Refusal content part - properties: - type: - type: string - enum: - - refusal - description: The type of the content part. - x-stainless-const: true - refusal: - type: string - description: The refusal message generated by the model. - required: - - type - - refusal - ChatCompletionRequestMessageContentPartText: - type: object - title: Text content part - description: | - Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). - properties: - type: - type: string - enum: - - text - description: The type of the content part. - x-stainless-const: true - text: - type: string - description: The text content. - required: - - type - - text - x-stainless-naming: - go: - variant_constructor: TextContentPart - ChatCompletionRequestSystemMessage: - type: object - title: System message - description: | - Developer-provided instructions that the model should follow, regardless of - messages sent by the user. With o1 models and newer, use `developer` messages - for this purpose instead. - properties: - content: - description: The contents of the system message. - anyOf: - - type: string - description: The contents of the system message. - title: Text content - - type: array - description: >- - An array of content parts with a defined type. For system messages, only type `text` is - supported. - title: Array of content parts - items: - $ref: '#/components/schemas/ChatCompletionRequestSystemMessageContentPart' - minItems: 1 - role: - type: string - enum: - - system - description: The role of the messages author, in this case `system`. - x-stainless-const: true - name: - type: string - description: >- - An optional name for the participant. Provides the model information to differentiate between - participants of the same role. - required: - - content - - role - x-stainless-naming: - go: - variant_constructor: SystemMessage - ChatCompletionRequestSystemMessageContentPart: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - ChatCompletionRequestToolMessage: - type: object - title: Tool message - properties: - role: - type: string - enum: - - tool - description: The role of the messages author, in this case `tool`. - x-stainless-const: true - content: - description: The contents of the tool message. - anyOf: - - type: string - description: The contents of the tool message. - title: Text content - - type: array - description: >- - An array of content parts with a defined type. For tool messages, only type `text` is - supported. - title: Array of content parts - items: - $ref: '#/components/schemas/ChatCompletionRequestToolMessageContentPart' - minItems: 1 - tool_call_id: - type: string - description: Tool call that this message is responding to. - required: - - role - - content - - tool_call_id - x-stainless-naming: - go: - variant_constructor: ToolMessage - ChatCompletionRequestToolMessageContentPart: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - ChatCompletionRequestUserMessage: - type: object - title: User message - description: | - Messages sent by an end user, containing prompts or additional context - information. - properties: - content: - description: | - The contents of the user message. - anyOf: - - type: string - description: The text contents of the message. - title: Text content - - type: array - description: >- - An array of content parts with a defined type. Supported options differ based on the - [model](https://platform.openai.com/docs/models) being used to generate the response. Can - contain text, image, or audio inputs. - title: Array of content parts - items: - $ref: '#/components/schemas/ChatCompletionRequestUserMessageContentPart' - minItems: 1 - role: - type: string - enum: - - user - description: The role of the messages author, in this case `user`. - x-stainless-const: true - name: - type: string - description: >- - An optional name for the participant. Provides the model information to differentiate between - participants of the same role. - required: - - content - - role - x-stainless-naming: - go: - variant_constructor: UserMessage - ChatCompletionRequestUserMessageContentPart: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartAudio' - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartFile' - discriminator: - propertyName: type - ChatCompletionResponseMessage: - type: object - description: A chat completion message generated by the model. - properties: - content: - anyOf: - - type: string - description: The contents of the message. - - type: 'null' - refusal: - anyOf: - - type: string - description: The refusal message generated by the model. - - type: 'null' - tool_calls: - $ref: '#/components/schemas/ChatCompletionMessageToolCalls' - annotations: - type: array - description: | - Annotations for the message, when applicable, as when using the - [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). - items: - type: object - description: | - A URL citation when using web search. - required: - - type - - url_citation - properties: - type: - type: string - description: The type of the URL citation. Always `url_citation`. - enum: - - url_citation - x-stainless-const: true - url_citation: - type: object - description: A URL citation when using web search. - required: - - end_index - - start_index - - url - - title - properties: - end_index: - type: integer - description: The index of the last character of the URL citation in the message. - start_index: - type: integer - description: The index of the first character of the URL citation in the message. - url: - type: string - description: The URL of the web resource. - title: - type: string - description: The title of the web resource. - role: - type: string - enum: - - assistant - description: The role of the author of this message. - x-stainless-const: true - function_call: - type: object - deprecated: true - description: >- - Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be - called, as generated by the model. - properties: - arguments: - type: string - description: >- - The arguments to call the function with, as generated by the model in JSON format. Note that - the model does not always generate valid JSON, and may hallucinate parameters not defined by - your function schema. Validate the arguments in your code before calling your function. - name: - type: string - description: The name of the function to call. - required: - - name - - arguments - audio: - anyOf: - - type: object - description: > - If the audio output modality is requested, this object contains data - - about the audio response from the model. [Learn - more](https://platform.openai.com/docs/guides/audio). - required: - - id - - expires_at - - data - - transcript - properties: - id: - type: string - description: Unique identifier for this audio response. - expires_at: - type: integer - description: | - The Unix timestamp (in seconds) for when this audio response will - no longer be accessible on the server for use in multi-turn - conversations. - data: - type: string - description: | - Base64 encoded audio bytes generated by the model, in the format - specified in the request. - transcript: - type: string - description: Transcript of the audio generated by the model. - - type: 'null' - required: - - role - - content - - refusal - ChatCompletionRole: - type: string - description: The role of the author of a message - enum: - - developer - - system - - user - - assistant - - tool - - function - ChatCompletionStreamOptions: - anyOf: - - description: | - Options for streaming response. Only set this when you set `stream: true`. - type: object - properties: - include_usage: - type: boolean - description: | - If set, an additional chunk will be streamed before the `data: [DONE]` - message. The `usage` field on this chunk shows the token usage statistics - for the entire request, and the `choices` field will always be an empty - array. - - All other chunks will also include a `usage` field, but with a null - value. **NOTE:** If the stream is interrupted, you may not receive the - final usage chunk which contains the total token usage for the request. - include_obfuscation: - type: boolean - description: | - When true, stream obfuscation will be enabled. Stream obfuscation adds - random characters to an `obfuscation` field on streaming delta events to - normalize payload sizes as a mitigation to certain side-channel attacks. - These obfuscation fields are included by default, but add a small amount - of overhead to the data stream. You can set `include_obfuscation` to - false to optimize for bandwidth if you trust the network links between - your application and the OpenAI API. - - type: 'null' - ChatCompletionStreamResponseDelta: - type: object - description: A chat completion delta generated by streamed model responses. - properties: - content: - anyOf: - - type: string - description: The contents of the chunk message. - - type: 'null' - function_call: - deprecated: true - type: object - description: >- - Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be - called, as generated by the model. - properties: - arguments: - type: string - description: >- - The arguments to call the function with, as generated by the model in JSON format. Note that - the model does not always generate valid JSON, and may hallucinate parameters not defined by - your function schema. Validate the arguments in your code before calling your function. - name: - type: string - description: The name of the function to call. - tool_calls: - type: array - items: - $ref: '#/components/schemas/ChatCompletionMessageToolCallChunk' - role: - type: string - enum: - - developer - - system - - user - - assistant - - tool - description: The role of the author of this message. - refusal: - anyOf: - - type: string - description: The refusal message generated by the model. - - type: 'null' - ChatCompletionTokenLogprob: - type: object - properties: - token: - description: The token. - type: string - logprob: - description: >- - The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the - value `-9999.0` is used to signify that the token is very unlikely. - type: number - bytes: - anyOf: - - description: >- - A list of integers representing the UTF-8 bytes representation of the token. Useful in - instances where characters are represented by multiple tokens and their byte representations - must be combined to generate the correct text representation. Can be `null` if there is no - bytes representation for the token. - type: array - items: - type: integer - - type: 'null' - top_logprobs: - description: >- - List of the most likely tokens and their log probability, at this token position. In rare cases, - there may be fewer than the number of requested `top_logprobs` returned. - type: array - items: - type: object - properties: - token: - description: The token. - type: string - logprob: - description: >- - The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, - the value `-9999.0` is used to signify that the token is very unlikely. - type: number - bytes: - anyOf: - - description: >- - A list of integers representing the UTF-8 bytes representation of the token. Useful in - instances where characters are represented by multiple tokens and their byte - representations must be combined to generate the correct text representation. Can be - `null` if there is no bytes representation for the token. - type: array - items: - type: integer - - type: 'null' - required: - - token - - logprob - - bytes - required: - - token - - logprob - - bytes - - top_logprobs - ChatCompletionTool: - type: object - title: Function tool - description: | - A function tool that can be used to generate a response. - properties: - type: - type: string - enum: - - function - description: The type of the tool. Currently, only `function` is supported. - x-stainless-const: true - function: - $ref: '#/components/schemas/FunctionObject' - required: - - type - - function - ChatCompletionToolChoiceOption: - description: > - Controls which (if any) tool is called by the model. - - `none` means the model will not call any tool and instead generates a message. - - `auto` means the model can pick between generating a message or calling one or more tools. - - `required` means the model must call one or more tools. - - Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces - the model to call that tool. - - - `none` is the default when no tools are present. `auto` is the default if tools are present. - anyOf: - - type: string - title: Auto - description: > - `none` means the model will not call any tool and instead generates a message. `auto` means the - model can pick between generating a message or calling one or more tools. `required` means the - model must call one or more tools. - enum: - - none - - auto - - required - - $ref: '#/components/schemas/ChatCompletionAllowedToolsChoice' - - $ref: '#/components/schemas/ChatCompletionNamedToolChoice' - - $ref: '#/components/schemas/ChatCompletionNamedToolChoiceCustom' - x-stainless-go-variant-constructor: - naming: tool_choice_option_{variant} - ChunkingStrategyRequestParam: - type: object - description: >- - The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only - applicable if `file_ids` is non-empty. - anyOf: - - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' - - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' - discriminator: - propertyName: type - CodeInterpreterFileOutput: - type: object - title: Code interpreter file output - description: | - The output of a code interpreter tool call that is a file. - properties: - type: - type: string - enum: - - files - description: | - The type of the code interpreter file output. Always `files`. - x-stainless-const: true - files: - type: array - items: - type: object - properties: - mime_type: - type: string - description: | - The MIME type of the file. - file_id: - type: string - description: | - The ID of the file. - required: - - mime_type - - file_id - required: - - type - - files - CodeInterpreterTextOutput: - type: object - title: Code interpreter text output - description: | - The output of a code interpreter tool call that is text. - properties: - type: - type: string - enum: - - logs - description: | - The type of the code interpreter text output. Always `logs`. - x-stainless-const: true - logs: - type: string - description: | - The logs of the code interpreter tool call. - required: - - type - - logs - CodeInterpreterTool: - type: object - title: Code interpreter - description: | - A tool that runs Python code to help generate a response to a prompt. - properties: - type: - type: string - enum: - - code_interpreter - description: | - The type of the code interpreter tool. Always `code_interpreter`. - x-stainless-const: true - container: - description: | - The code interpreter container. Can be a container ID or an object that - specifies uploaded file IDs to make available to your code. - anyOf: - - type: string - description: The container ID. - - $ref: '#/components/schemas/CodeInterpreterContainerAuto' - required: - - type - - container - CodeInterpreterToolCall: - type: object - title: Code interpreter tool call - description: | - A tool call to run code. - properties: - type: - type: string - enum: - - code_interpreter_call - default: code_interpreter_call - x-stainless-const: true - description: | - The type of the code interpreter tool call. Always `code_interpreter_call`. - id: - type: string - description: | - The unique ID of the code interpreter tool call. - status: - type: string - enum: - - in_progress - - completed - - incomplete - - interpreting - - failed - description: > - The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, - `incomplete`, `interpreting`, and `failed`. - container_id: - type: string - description: | - The ID of the container used to run the code. - code: - anyOf: - - type: string - description: | - The code to run, or null if not available. - - type: 'null' - outputs: - anyOf: - - type: array - items: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/CodeInterpreterOutputLogs' - - $ref: '#/components/schemas/CodeInterpreterOutputImage' - discriminator: - propertyName: type - description: | - The outputs generated by the code interpreter, such as logs or images. - Can be null if no outputs are available. - - type: 'null' - required: - - type - - id - - status - - container_id - - code - - outputs - ComparisonFilter: - type: object - additionalProperties: false - title: Comparison Filter - description: > - A filter used to compare a specified attribute key to a given value using a defined comparison - operation. - properties: - type: - type: string - default: eq - enum: - - eq - - ne - - gt - - gte - - lt - - lte - description: | - Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`. - - `eq`: equals - - `ne`: not equal - - `gt`: greater than - - `gte`: greater than or equal - - `lt`: less than - - `lte`: less than or equal - - `in`: in - - `nin`: not in - key: - type: string - description: The key to compare against the value. - value: - description: The value to compare against the attribute key; supports string, number, or boolean types. - anyOf: - - type: string - - type: number - - type: boolean - - type: array - items: - $ref: '#/components/schemas/ComparisonFilterValueItems' - required: - - type - - key - - value - x-oaiMeta: - name: ComparisonFilter - CompleteUploadRequest: - type: object - additionalProperties: false - properties: - part_ids: - type: array - description: | - The ordered list of Part IDs. - items: - type: string - md5: - description: > - The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you - expect. - type: string - required: - - part_ids - CompletionUsage: - type: object - description: Usage statistics for the completion request. - properties: - completion_tokens: - type: integer - default: 0 - description: Number of tokens in the generated completion. - prompt_tokens: - type: integer - default: 0 - description: Number of tokens in the prompt. - total_tokens: - type: integer - default: 0 - description: Total number of tokens used in the request (prompt + completion). - completion_tokens_details: - type: object - description: Breakdown of tokens used in a completion. - properties: - accepted_prediction_tokens: - type: integer - default: 0 - description: | - When using Predicted Outputs, the number of tokens in the - prediction that appeared in the completion. - audio_tokens: - type: integer - default: 0 - description: Audio input tokens generated by the model. - reasoning_tokens: - type: integer - default: 0 - description: Tokens generated by the model for reasoning. - rejected_prediction_tokens: - type: integer - default: 0 - description: | - When using Predicted Outputs, the number of tokens in the - prediction that did not appear in the completion. However, like - reasoning tokens, these tokens are still counted in the total - completion tokens for purposes of billing, output, and context window - limits. - prompt_tokens_details: - type: object - description: Breakdown of tokens used in the prompt. - properties: - audio_tokens: - type: integer - default: 0 - description: Audio input tokens present in the prompt. - cached_tokens: - type: integer - default: 0 - description: Cached tokens present in the prompt. - required: - - prompt_tokens - - completion_tokens - - total_tokens - CompoundFilter: - $recursiveAnchor: true - type: object - additionalProperties: false - title: Compound Filter - description: Combine multiple filters using `and` or `or`. - properties: - type: - type: string - description: 'Type of operation: `and` or `or`.' - enum: - - and - - or - filters: - type: array - description: Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`. - items: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ComparisonFilter' - - $recursiveRef: '#' - required: - - type - - filters - x-oaiMeta: - name: CompoundFilter - ComputerAction: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ClickParam' - - $ref: '#/components/schemas/DoubleClickAction' - - $ref: '#/components/schemas/Drag' - - $ref: '#/components/schemas/KeyPressAction' - - $ref: '#/components/schemas/Move' - - $ref: '#/components/schemas/Screenshot' - - $ref: '#/components/schemas/Scroll' - - $ref: '#/components/schemas/Type' - - $ref: '#/components/schemas/Wait' - ComputerScreenshotImage: - type: object - description: | - A computer screenshot image used with the computer use tool. - properties: - type: - type: string - enum: - - computer_screenshot - default: computer_screenshot - description: | - Specifies the event type. For a computer screenshot, this property is - always set to `computer_screenshot`. - x-stainless-const: true - image_url: - type: string - description: The URL of the screenshot image. - file_id: - type: string - description: The identifier of an uploaded file that contains the screenshot. - required: - - type - ComputerToolCall: - type: object - title: Computer tool call - description: | - A tool call to a computer use tool. See the - [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information. - properties: - type: - type: string - description: The type of the computer call. Always `computer_call`. - enum: - - computer_call - default: computer_call - id: - type: string - description: The unique ID of the computer call. - call_id: - type: string - description: | - An identifier used when responding to the tool call with output. - action: - $ref: '#/components/schemas/ComputerAction' - pending_safety_checks: - type: array - items: - $ref: '#/components/schemas/ComputerCallSafetyCheckParam' - description: | - The pending safety checks for the computer call. - status: - type: string - description: | - The status of the item. One of `in_progress`, `completed`, or - `incomplete`. Populated when items are returned via API. - enum: - - in_progress - - completed - - incomplete - required: - - type - - id - - action - - call_id - - pending_safety_checks - - status - ComputerToolCallOutput: - type: object - title: Computer tool call output - description: | - The output of a computer tool call. - properties: - type: - type: string - description: | - The type of the computer tool call output. Always `computer_call_output`. - enum: - - computer_call_output - default: computer_call_output - x-stainless-const: true - id: - type: string - description: | - The ID of the computer tool call output. - call_id: - type: string - description: | - The ID of the computer tool call that produced the output. - acknowledged_safety_checks: - type: array - description: | - The safety checks reported by the API that have been acknowledged by the - developer. - items: - $ref: '#/components/schemas/ComputerCallSafetyCheckParam' - output: - $ref: '#/components/schemas/ComputerScreenshotImage' - status: - type: string - description: | - The status of the message input. One of `in_progress`, `completed`, or - `incomplete`. Populated when input items are returned via API. - enum: - - in_progress - - completed - - incomplete - required: - - type - - call_id - - output - ComputerToolCallOutputResource: - allOf: - - $ref: '#/components/schemas/ComputerToolCallOutput' - - type: object - properties: - id: - type: string - description: | - The unique ID of the computer call tool output. - required: - - id - ContainerFileListResource: - type: object - properties: - object: - description: The type of object returned, must be 'list'. - const: list - data: - type: array - description: A list of container files. - items: - $ref: '#/components/schemas/ContainerFileResource' - first_id: - type: string - description: The ID of the first file in the list. - last_id: - type: string - description: The ID of the last file in the list. - has_more: - type: boolean - description: Whether there are more files available. - required: - - object - - data - - first_id - - last_id - - has_more - ContainerFileResource: - type: object - title: The container file object - properties: - id: - type: string - description: Unique identifier for the file. - object: - type: string - description: The type of this object (`container.file`). - const: container.file - container_id: - type: string - description: The container this file belongs to. - created_at: - type: integer - description: Unix timestamp (in seconds) when the file was created. - bytes: - type: integer - description: Size of the file in bytes. - path: - type: string - description: Path of the file in the container. - source: - type: string - description: Source of the file (e.g., `user`, `assistant`). - required: - - id - - object - - created_at - - bytes - - container_id - - path - - source - x-oaiMeta: - name: The container file object - example: | - { - "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", - "object": "container.file", - "created_at": 1747848842, - "bytes": 880, - "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", - "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", - "source": "user" - } - ContainerListResource: - type: object - properties: - object: - description: The type of object returned, must be 'list'. - const: list - data: - type: array - description: A list of containers. - items: - $ref: '#/components/schemas/ContainerResource' - first_id: - type: string - description: The ID of the first container in the list. - last_id: - type: string - description: The ID of the last container in the list. - has_more: - type: boolean - description: Whether there are more containers available. - required: - - object - - data - - first_id - - last_id - - has_more - ContainerResource: - type: object - title: The container object - properties: - id: - type: string - description: Unique identifier for the container. - object: - type: string - description: The type of this object. - name: - type: string - description: Name of the container. - created_at: - type: integer - description: Unix timestamp (in seconds) when the container was created. - status: - type: string - description: Status of the container (e.g., active, deleted). - expires_after: - type: object - description: | - The container will expire after this time period. - The anchor is the reference point for the expiration. - The minutes is the number of minutes after the anchor before the container expires. - properties: - anchor: - type: string - description: The reference point for the expiration. - enum: - - last_active_at - minutes: - type: integer - description: The number of minutes after the anchor before the container expires. - required: - - id - - object - - name - - created_at - - status - - id - - name - - created_at - - status - x-oaiMeta: - name: The container object - example: | - { - "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", - "object": "container", - "created_at": 1747844794, - "status": "running", - "expires_after": { - "anchor": "last_active_at", - "minutes": 20 - }, - "last_active_at": 1747844794, - "name": "My Container" - } - Content: - description: | - Multi-modal input and output contents. - anyOf: - - title: Input content types - $ref: '#/components/schemas/InputContent' - - title: Output content types - $ref: '#/components/schemas/OutputContent' - Conversation: - title: The conversation object - allOf: - - $ref: '#/components/schemas/ConversationResource' - x-oaiMeta: - name: The conversation object - group: conversations - ConversationItem: - title: Conversation item - description: >- - A single item within a conversation. The set of possible types are the same as the `output` type of a - [Response - object](https://platform.openai.com/docs/api-reference/responses/object#responses/object-output). - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/Message' - - $ref: '#/components/schemas/FunctionToolCallResource' - - $ref: '#/components/schemas/FunctionToolCallOutputResource' - - $ref: '#/components/schemas/FileSearchToolCall' - - $ref: '#/components/schemas/WebSearchToolCall' - - $ref: '#/components/schemas/ImageGenToolCall' - - $ref: '#/components/schemas/ComputerToolCall' - - $ref: '#/components/schemas/ComputerToolCallOutputResource' - - $ref: '#/components/schemas/ReasoningItem' - - $ref: '#/components/schemas/CodeInterpreterToolCall' - - $ref: '#/components/schemas/LocalShellToolCall' - - $ref: '#/components/schemas/LocalShellToolCallOutput' - - $ref: '#/components/schemas/FunctionShellCall' - - $ref: '#/components/schemas/FunctionShellCallOutput' - - $ref: '#/components/schemas/ApplyPatchToolCall' - - $ref: '#/components/schemas/ApplyPatchToolCallOutput' - - $ref: '#/components/schemas/MCPListTools' - - $ref: '#/components/schemas/MCPApprovalRequest' - - $ref: '#/components/schemas/MCPApprovalResponseResource' - - $ref: '#/components/schemas/MCPToolCall' - - $ref: '#/components/schemas/CustomToolCall' - - $ref: '#/components/schemas/CustomToolCallOutput' - ConversationItemList: - type: object - title: The conversation item list - description: A list of Conversation items. - properties: - object: - description: The type of object returned, must be `list`. - x-stainless-const: true - const: list - data: - type: array - description: A list of conversation items. - items: - $ref: '#/components/schemas/ConversationItem' - has_more: - type: boolean - description: Whether there are more items available. - first_id: - type: string - description: The ID of the first item in the list. - last_id: - type: string - description: The ID of the last item in the list. - required: - - object - - data - - has_more - - first_id - - last_id - x-oaiMeta: - name: The item list - group: conversations - ConversationParam: - description: > - 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. - anyOf: - - type: string - title: Conversation ID - description: | - The unique ID of the conversation. - - $ref: '#/components/schemas/ConversationParam-2' - CostsResult: - type: object - description: The aggregated costs details of the specific time bucket. - properties: - object: - type: string - enum: - - organization.costs.result - x-stainless-const: true - amount: - type: object - description: The monetary value in its associated currency. - properties: - value: - type: number - description: The numeric value of the cost. - currency: - type: string - description: Lowercase ISO-4217 currency e.g. "usd" - line_item: - anyOf: - - type: string - description: When `group_by=line_item`, this field provides the line item of the grouped costs result. - - type: 'null' - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped costs result. - - type: 'null' - required: - - object - x-oaiMeta: - name: Costs object - example: | - { - "object": "organization.costs.result", - "amount": { - "value": 0.06, - "currency": "usd" - }, - "line_item": "Image models", - "project_id": "proj_abc" - } - CreateAssistantRequest: - type: object - additionalProperties: false - properties: - model: - description: > - ID of the model to use. You can use the [List - models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your - available models, or see our [Model overview](https://platform.openai.com/docs/models) for - descriptions of them. - example: gpt-4o - anyOf: - - type: string - - $ref: '#/components/schemas/AssistantSupportedModels' - x-oaiTypeLabel: string - name: - anyOf: - - description: | - The name of the assistant. The maximum length is 256 characters. - type: string - maxLength: 256 - - type: 'null' - description: - anyOf: - - description: | - The description of the assistant. The maximum length is 512 characters. - type: string - maxLength: 512 - - type: 'null' - instructions: - anyOf: - - description: | - The system instructions that the assistant uses. The maximum length is 256,000 characters. - type: string - maxLength: 256000 - - type: 'null' - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - tools: - description: > - A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools - can be of types `code_interpreter`, `file_search`, or `function`. - default: [] - type: array - maxItems: 128 - items: - $ref: '#/components/schemas/AssistantTool' - tool_resources: - anyOf: - - type: object - description: > - A set of resources that are used by the assistant's tools. The resources are specific to the - type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the - `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - available to the `code_interpreter` tool. There can be a maximum of 20 files - associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached - to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - vector_stores: - type: array - description: > - A helper to create a [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) with - file_ids and attach it to this assistant. There can be a maximum of 1 vector store - attached to the assistant. - maxItems: 1 - items: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to - add to the vector store. There can be a maximum of 10000 files in a vector - store. - maxItems: 10000 - items: - type: string - chunking_strategy: - type: object - description: >- - The chunking strategy used to chunk the file(s). If not set, will use the `auto` - strategy. - anyOf: - - type: object - title: Auto Chunking Strategy - description: >- - The default strategy. This strategy currently uses a `max_chunk_size_tokens` - of `800` and `chunk_overlap_tokens` of `400`. - additionalProperties: false - properties: - type: - type: string - description: Always `auto`. - enum: - - auto - x-stainless-const: true - required: - - type - - type: object - title: Static Chunking Strategy - additionalProperties: false - properties: - type: - type: string - description: Always `static`. - enum: - - static - x-stainless-const: true - static: - type: object - additionalProperties: false - properties: - max_chunk_size_tokens: - type: integer - minimum: 100 - maximum: 4096 - description: >- - The maximum number of tokens in each chunk. The default value is - `800`. The minimum value is `100` and the maximum value is `4096`. - chunk_overlap_tokens: - type: integer - description: > - The number of tokens that overlap between chunks. The default value - is `400`. - - - Note that the overlap must not exceed half of - `max_chunk_size_tokens`. - required: - - max_chunk_size_tokens - - chunk_overlap_tokens - required: - - type - - static - discriminator: - propertyName: type - metadata: - $ref: '#/components/schemas/Metadata' - anyOf: - - required: - - vector_store_ids - - required: - - vector_stores - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - anyOf: - - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - - type: 'null' - top_p: - anyOf: - - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - - We generally recommend altering this or temperature but not both. - - type: 'null' - response_format: - anyOf: - - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - - type: 'null' - required: - - model - CreateChatCompletionRequest: - allOf: - - $ref: '#/components/schemas/CreateModelResponseProperties' - - type: object - properties: - messages: - description: > - A list of messages comprising the conversation so far. Depending on the - - [model](https://platform.openai.com/docs/models) you use, different message types (modalities) - are - - supported, like [text](https://platform.openai.com/docs/guides/text-generation), - - [images](https://platform.openai.com/docs/guides/vision), and - [audio](https://platform.openai.com/docs/guides/audio). - type: array - minItems: 1 - items: - $ref: '#/components/schemas/ChatCompletionRequestMessage' - model: - description: > - Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI - - offers a wide range of models with different capabilities, performance - - characteristics, and price points. Refer to the [model - guide](https://platform.openai.com/docs/models) - - to browse and compare available models. - $ref: '#/components/schemas/ModelIdsShared' - modalities: - $ref: '#/components/schemas/ResponseModalities' - verbosity: - $ref: '#/components/schemas/Verbosity' - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - max_completion_tokens: - description: > - An upper bound for the number of tokens that can be generated for a completion, including - visible output tokens and [reasoning - tokens](https://platform.openai.com/docs/guides/reasoning). - type: integer - nullable: true - frequency_penalty: - type: number - default: 0 - minimum: -2 - maximum: 2 - nullable: true - description: | - Number between -2.0 and 2.0. Positive values penalize new tokens based on - their existing frequency in the text so far, decreasing the model's - likelihood to repeat the same line verbatim. - presence_penalty: - type: number - default: 0 - minimum: -2 - maximum: 2 - nullable: true - description: | - Number between -2.0 and 2.0. Positive values penalize new tokens based on - whether they appear in the text so far, increasing the model's likelihood - to talk about new topics. - web_search_options: - type: object - title: Web search - description: > - 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?api-mode=chat). - properties: - user_location: - type: object - nullable: true - required: - - type - - approximate - description: | - Approximate location parameters for the search. - properties: - type: - type: string - description: | - The type of location approximation. Always `approximate`. - enum: - - approximate - x-stainless-const: true - approximate: - $ref: '#/components/schemas/WebSearchLocation' - search_context_size: - $ref: '#/components/schemas/WebSearchContextSize' - top_logprobs: - description: | - An integer between 0 and 20 specifying the number of most likely tokens to - return at each token position, each with an associated log probability. - `logprobs` must be set to `true` if this parameter is used. - type: integer - minimum: 0 - maximum: 20 - nullable: true - response_format: - description: | - An object specifying the format that the model must output. - - Setting to `{ "type": "json_schema", "json_schema": {...} }` enables - Structured Outputs which ensures the model will match your supplied JSON - schema. Learn more in the [Structured Outputs - guide](https://platform.openai.com/docs/guides/structured-outputs). - - Setting to `{ "type": "json_object" }` enables the older JSON mode, which - ensures the message the model generates is valid JSON. Using `json_schema` - is preferred for models that support it. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ResponseFormatText' - - $ref: '#/components/schemas/ResponseFormatJsonSchema' - - $ref: '#/components/schemas/ResponseFormatJsonObject' - audio: - type: object - nullable: true - description: | - Parameters for audio output. Required when audio output is requested with - `modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio). - required: - - voice - - format - properties: - voice: - $ref: '#/components/schemas/VoiceIdsShared' - description: | - The voice the model uses to respond. Supported voices are - `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. - format: - type: string - enum: - - wav - - aac - - mp3 - - flac - - opus - - pcm16 - description: | - Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, - `opus`, or `pcm16`. - store: - type: boolean - default: false - nullable: true - description: | - Whether or not to store the output of this chat completion request for - use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or - [evals](https://platform.openai.com/docs/guides/evals) products. - - Supports text and image inputs. Note: image inputs over 8MB will be dropped. - stream: - description: > - If set to true, the model response data will be streamed to the client - - as it is generated using [server-sent - events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - - See the [Streaming section - below](https://platform.openai.com/docs/api-reference/chat/streaming) - - for more information, along with the [streaming - responses](https://platform.openai.com/docs/guides/streaming-responses) - - guide for more information on how to handle the streaming events. - type: boolean - nullable: true - default: false - stop: - $ref: '#/components/schemas/StopConfiguration' - logit_bias: - type: object - x-oaiTypeLabel: map - default: null - nullable: true - additionalProperties: - type: integer - description: | - Modify the likelihood of specified tokens appearing in the completion. - - Accepts a JSON object that maps tokens (specified by their token ID in the - tokenizer) to an associated bias value from -100 to 100. Mathematically, - the bias is added to the logits generated by the model prior to sampling. - The exact effect will vary per model, but values between -1 and 1 should - decrease or increase likelihood of selection; values like -100 or 100 - should result in a ban or exclusive selection of the relevant token. - logprobs: - description: | - Whether to return log probabilities of the output tokens or not. If true, - returns the log probabilities of each output token returned in the - `content` of `message`. - type: boolean - default: false - nullable: true - max_tokens: - description: | - The maximum number of [tokens](/tokenizer) that can be generated in the - chat completion. This value can be used to control - [costs](https://openai.com/api/pricing/) for text generated via API. - - This value is now deprecated in favor of `max_completion_tokens`, and is - not compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning). - type: integer - nullable: true - deprecated: true - 'n': - type: integer - minimum: 1 - maximum: 128 - default: 1 - example: 1 - nullable: true - description: >- - How many chat completion choices to generate for each input message. Note that you will be - charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to - minimize costs. - prediction: - nullable: true - description: > - Configuration for a [Predicted - Output](https://platform.openai.com/docs/guides/predicted-outputs), - - which can greatly improve response times when large parts of the model - - response are known ahead of time. This is most common when you are - - regenerating a file with only minor changes to most of the content. - anyOf: - - $ref: '#/components/schemas/PredictionContent' - discriminator: - propertyName: type - seed: - type: integer - minimum: -9223372036854776000 - maximum: 9223372036854776000 - nullable: true - deprecated: true - description: > - This feature is in Beta. - - If specified, our system will make a best effort to sample deterministically, such that - repeated requests with the same `seed` and parameters should return the same result. - - Determinism is not guaranteed, and you should refer to the `system_fingerprint` response - parameter to monitor changes in the backend. - x-oaiMeta: - beta: true - stream_options: - $ref: '#/components/schemas/ChatCompletionStreamOptions' - tools: - type: array - description: | - A list of tools the model may call. You can provide either - [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or - [function tools](https://platform.openai.com/docs/guides/function-calling). - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionTool' - - $ref: '#/components/schemas/CustomToolChatCompletions' - x-stainless-naming: - python: - model_name: chat_completion_tool_union - param_model_name: chat_completion_tool_union_param - discriminator: - propertyName: type - x-stainless-go-variant-constructor: - naming: chat_completion_{variant}_tool - tool_choice: - $ref: '#/components/schemas/ChatCompletionToolChoiceOption' - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - function_call: - deprecated: true - description: | - Deprecated in favor of `tool_choice`. - - Controls which (if any) function is called by the model. - - `none` means the model will not call a function and instead generates a - message. - - `auto` means the model can pick between generating a message or calling a - function. - - Specifying a particular function via `{"name": "my_function"}` forces the - model to call that function. - - `none` is the default when no functions are present. `auto` is the default - if functions are present. - anyOf: - - type: string - description: > - `none` means the model will not call a function and instead generates a message. `auto` - means the model can pick between generating a message or calling a function. - enum: - - none - - auto - title: function call mode - - $ref: '#/components/schemas/ChatCompletionFunctionCallOption' - functions: - deprecated: true - description: | - Deprecated in favor of `tools`. - - A list of functions the model may generate JSON inputs for. - type: array - minItems: 1 - maxItems: 128 - items: - $ref: '#/components/schemas/ChatCompletionFunctions' - required: - - model - - messages - CreateChatCompletionResponse: - type: object - description: Represents a chat completion response returned by model, based on the provided input. - properties: - id: - type: string - description: A unique identifier for the chat completion. - choices: - type: array - description: A list of chat completion choices. Can be more than one if `n` is greater than 1. - items: - type: object - required: - - finish_reason - - index - - message - - logprobs - properties: - finish_reason: - type: string - description: > - The reason the model stopped generating tokens. This will be `stop` if the model hit a - natural stop point or a provided stop sequence, - - `length` if the maximum number of tokens specified in the request was reached, - - `content_filter` if content was omitted due to a flag from our content filters, - - `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called - a function. - enum: - - stop - - length - - tool_calls - - content_filter - - function_call - index: - type: integer - description: The index of the choice in the list of choices. - message: - $ref: '#/components/schemas/ChatCompletionResponseMessage' - logprobs: - anyOf: - - description: Log probability information for the choice. - type: object - properties: - content: - anyOf: - - description: A list of message content tokens with log probability information. - type: array - items: - $ref: '#/components/schemas/ChatCompletionTokenLogprob' - - type: 'null' - refusal: - anyOf: - - description: A list of message refusal tokens with log probability information. - type: array - items: - $ref: '#/components/schemas/ChatCompletionTokenLogprob' - - type: 'null' - required: - - content - - refusal - - type: 'null' - created: - type: integer - description: The Unix timestamp (in seconds) of when the chat completion was created. - model: - type: string - description: The model used for the chat completion. - service_tier: - $ref: '#/components/schemas/ServiceTier' - system_fingerprint: - type: string - deprecated: true - description: > - This fingerprint represents the backend configuration that the model runs with. - - - Can be used in conjunction with the `seed` request parameter to understand when backend changes - have been made that might impact determinism. - object: - type: string - description: The object type, which is always `chat.completion`. - enum: - - chat.completion - x-stainless-const: true - usage: - $ref: '#/components/schemas/CompletionUsage' - required: - - choices - - created - - id - - model - - object - x-oaiMeta: - name: The chat completion object - group: chat - example: | - { - "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", - "object": "chat.completion", - "created": 1741570283, - "model": "gpt-4o-2024-08-06", - "choices": [ - { - "index": 0, - "message": { - "role": "assistant", - "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", - "refusal": null, - "annotations": [] - }, - "logprobs": null, - "finish_reason": "stop" - } - ], - "usage": { - "prompt_tokens": 1117, - "completion_tokens": 46, - "total_tokens": 1163, - "prompt_tokens_details": { - "cached_tokens": 0, - "audio_tokens": 0 - }, - "completion_tokens_details": { - "reasoning_tokens": 0, - "audio_tokens": 0, - "accepted_prediction_tokens": 0, - "rejected_prediction_tokens": 0 - } - }, - "service_tier": "default", - "system_fingerprint": "fp_fc9f1d7035" - } - CreateChatCompletionStreamResponse: - type: object - description: | - Represents a streamed chunk of a chat completion response returned - by the model, based on the provided input. - [Learn more](https://platform.openai.com/docs/guides/streaming-responses). - properties: - id: - type: string - description: A unique identifier for the chat completion. Each chunk has the same ID. - choices: - type: array - description: > - A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. - Can also be empty for the - - last chunk if you set `stream_options: {"include_usage": true}`. - items: - type: object - required: - - delta - - finish_reason - - index - properties: - delta: - $ref: '#/components/schemas/ChatCompletionStreamResponseDelta' - logprobs: - description: Log probability information for the choice. - type: object - nullable: true - properties: - content: - description: A list of message content tokens with log probability information. - type: array - items: - $ref: '#/components/schemas/ChatCompletionTokenLogprob' - nullable: true - refusal: - description: A list of message refusal tokens with log probability information. - type: array - items: - $ref: '#/components/schemas/ChatCompletionTokenLogprob' - nullable: true - required: - - content - - refusal - finish_reason: - type: string - description: > - The reason the model stopped generating tokens. This will be `stop` if the model hit a - natural stop point or a provided stop sequence, - - `length` if the maximum number of tokens specified in the request was reached, - - `content_filter` if content was omitted due to a flag from our content filters, - - `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called - a function. - enum: - - stop - - length - - tool_calls - - content_filter - - function_call - nullable: true - index: - type: integer - description: The index of the choice in the list of choices. - created: - type: integer - description: >- - The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same - timestamp. - model: - type: string - description: The model to generate the completion. - service_tier: - $ref: '#/components/schemas/ServiceTier' - system_fingerprint: - type: string - deprecated: true - description: > - This fingerprint represents the backend configuration that the model runs with. - - Can be used in conjunction with the `seed` request parameter to understand when backend changes - have been made that might impact determinism. - object: - type: string - description: The object type, which is always `chat.completion.chunk`. - enum: - - chat.completion.chunk - x-stainless-const: true - usage: - $ref: '#/components/schemas/CompletionUsage' - nullable: true - description: | - An optional field that will only be present when you set - `stream_options: {"include_usage": true}` in your request. When present, it - contains a null value **except for the last chunk** which contains the - token usage statistics for the entire request. - - **NOTE:** If the stream is interrupted or cancelled, you may not - receive the final usage chunk which contains the total token usage for - the request. - required: - - choices - - created - - id - - model - - object - x-oaiMeta: - name: The chat completion chunk object - group: chat - example: > - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", - "system_fingerprint": "fp_44709d6fcb", - "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} - - - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", - "system_fingerprint": "fp_44709d6fcb", - "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} - - - .... - - - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", - "system_fingerprint": "fp_44709d6fcb", - "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - CreateCompletionRequest: - type: object - properties: - model: - description: > - ID of the model to use. You can use the [List - models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your - available models, or see our [Model overview](https://platform.openai.com/docs/models) for - descriptions of them. - anyOf: - - type: string - - type: string - enum: - - gpt-3.5-turbo-instruct - - davinci-002 - - babbage-002 - title: Preset - x-oaiTypeLabel: string - prompt: - description: > - The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, - or array of token arrays. - - - Note that <|endoftext|> is the document separator that the model sees during training, so if a - prompt is not specified the model will generate as if from the beginning of a new document. - nullable: true - anyOf: - - type: string - default: '' - example: This is a test. - - type: array - items: - type: string - default: '' - example: This is a test. - title: Array of strings - - type: array - minItems: 1 - items: - type: integer - title: Array of tokens - - type: array - minItems: 1 - items: - type: array - minItems: 1 - items: - type: integer - title: Array of token arrays - best_of: - type: integer - default: 1 - minimum: 0 - maximum: 20 - nullable: true - description: > - Generates `best_of` completions server-side and returns the "best" (the one with the highest log - probability per token). Results cannot be streamed. - - - When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how - many to return – `best_of` must be greater than `n`. - - - **Note:** Because this parameter generates many completions, it can quickly consume your token - quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. - echo: - type: boolean - default: false - nullable: true - description: | - Echo back the prompt in addition to the completion - frequency_penalty: - type: number - default: 0 - minimum: -2 - maximum: 2 - nullable: true - description: > - Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency - in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - - - [See more information about frequency and presence - penalties.](https://platform.openai.com/docs/guides/text-generation) - logit_bias: - type: object - x-oaiTypeLabel: map - default: null - nullable: true - additionalProperties: - type: integer - description: > - Modify the likelihood of specified tokens appearing in the completion. - - - Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an - associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to - convert text to token IDs. Mathematically, the bias is added to the logits generated by the model - prior to sampling. The exact effect will vary per model, but values between -1 and 1 should - decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or - exclusive selection of the relevant token. - - - As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being - generated. - logprobs: - type: integer - minimum: 0 - maximum: 5 - default: null - nullable: true - description: > - Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen - tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. - The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` - elements in the response. - - - The maximum value for `logprobs` is 5. - max_tokens: - type: integer - minimum: 0 - default: 16 - example: 16 - nullable: true - description: > - The maximum number of [tokens](/tokenizer) that can be generated in the completion. - - - The token count of your prompt plus `max_tokens` cannot exceed the model's context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for - counting tokens. - 'n': - type: integer - minimum: 1 - maximum: 128 - default: 1 - example: 1 - nullable: true - description: > - How many completions to generate for each prompt. - - - **Note:** Because this parameter generates many completions, it can quickly consume your token - quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. - presence_penalty: - type: number - default: 0 - minimum: -2 - maximum: 2 - nullable: true - description: > - Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in - the text so far, increasing the model's likelihood to talk about new topics. - - - [See more information about frequency and presence - penalties.](https://platform.openai.com/docs/guides/text-generation) - seed: - type: integer - format: int64 - nullable: true - description: > - If specified, our system will make a best effort to sample deterministically, such that repeated - requests with the same `seed` and parameters should return the same result. - - - Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter - to monitor changes in the backend. - stop: - $ref: '#/components/schemas/StopConfiguration' - stream: - description: > - Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent - events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python - code](https://cookbook.openai.com/examples/how_to_stream_completions). - type: boolean - nullable: true - default: false - stream_options: - $ref: '#/components/schemas/ChatCompletionStreamOptions' - suffix: - description: | - The suffix that comes after a completion of inserted text. - - This parameter is only supported for `gpt-3.5-turbo-instruct`. - default: null - nullable: true - type: string - example: test. - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - - - We generally recommend altering this or `top_p` but not both. - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model considers - the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the - top 10% probability mass are considered. - - - We generally recommend altering this or `temperature` but not both. - user: - type: string - example: user-1234 - description: > - A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - required: - - model - - prompt - CreateCompletionResponse: - type: object - description: > - Represents a completion response from the API. Note: both the streamed and non-streamed response - objects share the same shape (unlike the chat endpoint). - properties: - id: - type: string - description: A unique identifier for the completion. - choices: - type: array - description: The list of completion choices the model generated for the input prompt. - items: - type: object - required: - - finish_reason - - index - - logprobs - - text - properties: - finish_reason: - type: string - description: > - The reason the model stopped generating tokens. This will be `stop` if the model hit a - natural stop point or a provided stop sequence, - - `length` if the maximum number of tokens specified in the request was reached, - - or `content_filter` if content was omitted due to a flag from our content filters. - enum: - - stop - - length - - content_filter - index: - type: integer - logprobs: - anyOf: - - type: object - properties: - text_offset: - type: array - items: - type: integer - token_logprobs: - type: array - items: - type: number - tokens: - type: array - items: - type: string - top_logprobs: - type: array - items: - type: object - additionalProperties: - type: number - - type: 'null' - text: - type: string - created: - type: integer - description: The Unix timestamp (in seconds) of when the completion was created. - model: - type: string - description: The model used for completion. - system_fingerprint: - type: string - description: > - This fingerprint represents the backend configuration that the model runs with. - - - Can be used in conjunction with the `seed` request parameter to understand when backend changes - have been made that might impact determinism. - object: - type: string - description: The object type, which is always "text_completion" - enum: - - text_completion - x-stainless-const: true - usage: - $ref: '#/components/schemas/CompletionUsage' - required: - - id - - object - - created - - model - - choices - x-oaiMeta: - name: The completion object - legacy: true - example: | - { - "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", - "object": "text_completion", - "created": 1589478378, - "model": "gpt-4-turbo", - "choices": [ - { - "text": "\n\nThis is indeed a test", - "index": 0, - "logprobs": null, - "finish_reason": "length" - } - ], - "usage": { - "prompt_tokens": 5, - "completion_tokens": 7, - "total_tokens": 12 - } - } - CreateContainerBody: - type: object - properties: - name: - type: string - description: Name of the container to create. - file_ids: - type: array - description: IDs of files to copy to the container. - items: - type: string - expires_after: - type: object - description: Container expiration time in seconds relative to the 'anchor' time. - properties: - anchor: - type: string - enum: - - last_active_at - description: Time anchor for the expiration time. Currently only 'last_active_at' is supported. - minutes: - type: integer - required: - - anchor - - minutes - required: - - name - CreateContainerFileBody: - type: object - properties: - file_id: - type: string - description: Name of the file to create. - file: - description: | - The File object (not file name) to be uploaded. - type: string - format: binary - required: [] - CreateEmbeddingRequest: - type: object - additionalProperties: false - properties: - input: - description: > - Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single - request, pass an array of strings or array of token arrays. The input must not exceed the max - input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and - any array must be 2048 dimensions or less. [Example Python - code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 - tokens summed across all inputs in a single request. - example: The quick brown fox jumped over the lazy dog - anyOf: - - type: string - title: string - description: The string that will be turned into an embedding. - default: '' - example: This is a test. - - type: array - title: Array of strings - description: The array of strings that will be turned into an embedding. - minItems: 1 - maxItems: 2048 - items: - type: string - default: '' - example: '[''This is a test.'']' - - type: array - title: Array of tokens - description: The array of integers that will be turned into an embedding. - minItems: 1 - maxItems: 2048 - items: - type: integer - - type: array - title: Array of token arrays - description: The array of arrays containing integers that will be turned into an embedding. - minItems: 1 - maxItems: 2048 - items: - type: array - minItems: 1 - items: - type: integer - model: - description: > - ID of the model to use. You can use the [List - models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your - available models, or see our [Model overview](https://platform.openai.com/docs/models) for - descriptions of them. - example: text-embedding-3-small - anyOf: - - type: string - - type: string - enum: - - text-embedding-ada-002 - - text-embedding-3-small - - text-embedding-3-large - x-stainless-nominal: false - x-oaiTypeLabel: string - encoding_format: - description: >- - The format to return the embeddings in. Can be either `float` or - [`base64`](https://pypi.org/project/pybase64/). - example: float - default: float - type: string - enum: - - float - - base64 - dimensions: - description: > - The number of dimensions the resulting output embeddings should have. Only supported in - `text-embedding-3` and later models. - type: integer - minimum: 1 - user: - type: string - example: user-1234 - description: > - A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - required: - - model - - input - CreateEmbeddingResponse: - type: object - properties: - data: - type: array - description: The list of embeddings generated by the model. - items: - $ref: '#/components/schemas/Embedding' - model: - type: string - description: The name of the model used to generate the embedding. - object: - type: string - description: The object type, which is always "list". - enum: - - list - x-stainless-const: true - usage: - type: object - description: The usage information for the request. - properties: - prompt_tokens: - type: integer - description: The number of tokens used by the prompt. - total_tokens: - type: integer - description: The total number of tokens used by the request. - required: - - prompt_tokens - - total_tokens - required: - - object - - model - - data - - usage - CreateEvalCompletionsRunDataSource: - type: object - title: CompletionsRunDataSource - description: | - A CompletionsRunDataSource object describing a model sampling configuration. - properties: - type: - type: string - enum: - - completions - default: completions - description: The type of run data source. Always `completions`. - input_messages: - description: >- - Used when sampling from a model. Dictates the structure of the messages passed into the model. Can - either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with - variable references to the `item` namespace. - anyOf: - - type: object - title: TemplateInputMessages - properties: - type: - type: string - enum: - - template - description: The type of input messages. Always `template`. - template: - type: array - description: >- - A list of chat messages forming the prompt or context. May include variable references to - the `item` namespace, ie {{item.name}}. - items: - anyOf: - - $ref: '#/components/schemas/EasyInputMessage' - - $ref: '#/components/schemas/EvalItem' - required: - - type - - template - - type: object - title: ItemReferenceInputMessages - properties: - type: - type: string - enum: - - item_reference - description: The type of input messages. Always `item_reference`. - item_reference: - type: string - description: A reference to a variable in the `item` namespace. Ie, "item.input_trajectory" - required: - - type - - item_reference - discriminator: - propertyName: type - sampling_params: - type: object - properties: - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - temperature: - type: number - description: A higher temperature increases randomness in the outputs. - default: 1 - max_completion_tokens: - type: integer - description: The maximum number of tokens in the generated output. - top_p: - type: number - description: An alternative to temperature for nucleus sampling; 1.0 includes all tokens. - default: 1 - seed: - type: integer - description: A seed value to initialize the randomness, during sampling. - default: 42 - response_format: - description: | - An object specifying the format that the model must output. - - Setting to `{ "type": "json_schema", "json_schema": {...} }` enables - Structured Outputs which ensures the model will match your supplied JSON - schema. Learn more in the [Structured Outputs - guide](https://platform.openai.com/docs/guides/structured-outputs). - - Setting to `{ "type": "json_object" }` enables the older JSON mode, which - ensures the message the model generates is valid JSON. Using `json_schema` - is preferred for models that support it. - anyOf: - - $ref: '#/components/schemas/ResponseFormatText' - - $ref: '#/components/schemas/ResponseFormatJsonSchema' - - $ref: '#/components/schemas/ResponseFormatJsonObject' - tools: - type: array - description: > - A list of tools the model may call. Currently, only functions are supported as a tool. Use - this to provide a list of functions the model may generate JSON inputs for. A max of 128 - functions are supported. - items: - $ref: '#/components/schemas/ChatCompletionTool' - model: - type: string - description: The name of the model to use for generating completions (e.g. "o3-mini"). - source: - description: Determines what populates the `item` namespace in this run's data source. - anyOf: - - $ref: '#/components/schemas/EvalJsonlFileContentSource' - - $ref: '#/components/schemas/EvalJsonlFileIdSource' - - $ref: '#/components/schemas/EvalStoredCompletionsSource' - discriminator: - propertyName: type - required: - - type - - source - x-oaiMeta: - name: The completions data source object used to configure an individual run - group: eval runs - example: | - { - "name": "gpt-4o-mini-2024-07-18", - "data_source": { - "type": "completions", - "input_messages": { - "type": "item_reference", - "item_reference": "item.input" - }, - "model": "gpt-4o-mini-2024-07-18", - "source": { - "type": "stored_completions", - "model": "gpt-4o-mini-2024-07-18" - } - } - } - CreateEvalCustomDataSourceConfig: - type: object - title: CustomDataSourceConfig - description: > - A CustomDataSourceConfig object that defines the schema for the data source used for the evaluation - runs. - - This schema is used to define the shape of the data that will be: - - - Used to define your testing criteria and - - - What data is required when creating a run - properties: - type: - type: string - enum: - - custom - default: custom - description: The type of data source. Always `custom`. - x-stainless-const: true - item_schema: - type: object - description: The json schema for each row in the data source. - additionalProperties: true - include_sample_schema: - type: boolean - default: false - description: >- - Whether the eval should expect you to populate the sample namespace (ie, by generating responses - off of your data source) - required: - - item_schema - - type - x-oaiMeta: - name: The eval file data source config object - group: evals - example: | - { - "type": "custom", - "item_schema": { - "type": "object", - "properties": { - "name": {"type": "string"}, - "age": {"type": "integer"} - }, - "required": ["name", "age"] - }, - "include_sample_schema": true - } - CreateEvalItem: - title: CreateEvalItem - description: >- - A chat message that makes up the prompt or context. May include variable references to the `item` - namespace, ie {{item.name}}. - type: object - x-oaiMeta: - name: The chat message object used to configure an individual run - anyOf: - - type: object - title: SimpleInputMessage - properties: - role: - type: string - description: The role of the message (e.g. "system", "assistant", "user"). - content: - type: string - description: The content of the message. - required: - - role - - content - - $ref: '#/components/schemas/EvalItem' - CreateEvalJsonlRunDataSource: - type: object - title: JsonlRunDataSource - description: | - A JsonlRunDataSource object with that specifies a JSONL file that matches the eval - properties: - type: - type: string - enum: - - jsonl - default: jsonl - description: The type of data source. Always `jsonl`. - x-stainless-const: true - source: - description: Determines what populates the `item` namespace in the data source. - anyOf: - - $ref: '#/components/schemas/EvalJsonlFileContentSource' - - $ref: '#/components/schemas/EvalJsonlFileIdSource' - discriminator: - propertyName: type - required: - - type - - source - x-oaiMeta: - name: The file data source object for the eval run configuration - group: evals - example: | - { - "type": "jsonl", - "source": { - "type": "file_id", - "id": "file-9GYS6xbkWgWhmE7VoLUWFg" - } - } - CreateEvalLabelModelGrader: - type: object - title: LabelModelGrader - description: | - A LabelModelGrader object which uses a model to assign labels to each item - in the evaluation. - properties: - type: - description: The object type, which is always `label_model`. - type: string - enum: - - label_model - x-stainless-const: true - name: - type: string - description: The name of the grader. - model: - type: string - description: The model to use for the evaluation. Must support structured outputs. - input: - type: array - description: >- - A list of chat messages forming the prompt or context. May include variable references to the - `item` namespace, ie {{item.name}}. - items: - $ref: '#/components/schemas/CreateEvalItem' - labels: - type: array - items: - type: string - description: The labels to classify to each item in the evaluation. - passing_labels: - type: array - items: - type: string - description: The labels that indicate a passing result. Must be a subset of labels. - required: - - type - - model - - input - - passing_labels - - labels - - name - x-oaiMeta: - name: The eval label model grader object - group: evals - example: | - { - "type": "label_model", - "model": "gpt-4o-2024-08-06", - "input": [ - { - "role": "system", - "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" - }, - { - "role": "user", - "content": "Statement: {{item.response}}" - } - ], - "passing_labels": ["positive"], - "labels": ["positive", "neutral", "negative"], - "name": "Sentiment label grader" - } - CreateEvalLogsDataSourceConfig: - type: object - title: LogsDataSourceConfig - description: | - A data source config which specifies the metadata property of your logs query. - This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. - properties: - type: - type: string - enum: - - logs - default: logs - description: The type of data source. Always `logs`. - x-stainless-const: true - metadata: - type: object - description: Metadata filters for the logs data source. - additionalProperties: true - required: - - type - x-oaiMeta: - name: The logs data source object for evals - group: evals - example: | - { - "type": "logs", - "metadata": { - "use_case": "customer_support_agent" - } - } - CreateEvalRequest: - type: object - title: CreateEvalRequest - properties: - name: - type: string - description: The name of the evaluation. - metadata: - $ref: '#/components/schemas/Metadata' - data_source_config: - type: object - description: >- - The configuration for the data source used for the evaluation runs. Dictates the schema of the - data used in the evaluation. - anyOf: - - $ref: '#/components/schemas/CreateEvalCustomDataSourceConfig' - - $ref: '#/components/schemas/CreateEvalLogsDataSourceConfig' - - $ref: '#/components/schemas/CreateEvalStoredCompletionsDataSourceConfig' - discriminator: - propertyName: type - testing_criteria: - type: array - description: >- - A list of graders for all eval runs in this group. Graders can reference variables in the data - source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's - output, use the `sample` namespace (ie, `{{sample.output_text}}`). - items: - anyOf: - - $ref: '#/components/schemas/CreateEvalLabelModelGrader' - - $ref: '#/components/schemas/EvalGraderStringCheck' - - $ref: '#/components/schemas/EvalGraderTextSimilarity' - - $ref: '#/components/schemas/EvalGraderPython' - - $ref: '#/components/schemas/EvalGraderScoreModel' - discriminator: - propertyName: type - required: - - data_source_config - - testing_criteria - CreateEvalResponsesRunDataSource: - type: object - title: CreateEvalResponsesRunDataSource - description: | - A ResponsesRunDataSource object describing a model sampling configuration. - properties: - type: - type: string - enum: - - responses - default: responses - description: The type of run data source. Always `responses`. - input_messages: - description: >- - Used when sampling from a model. Dictates the structure of the messages passed into the model. Can - either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with - variable references to the `item` namespace. - anyOf: - - type: object - title: InputMessagesTemplate - properties: - type: - type: string - enum: - - template - description: The type of input messages. Always `template`. - template: - type: array - description: >- - A list of chat messages forming the prompt or context. May include variable references to - the `item` namespace, ie {{item.name}}. - items: - anyOf: - - type: object - title: ChatMessage - properties: - role: - type: string - description: The role of the message (e.g. "system", "assistant", "user"). - content: - type: string - description: The content of the message. - required: - - role - - content - - $ref: '#/components/schemas/EvalItem' - required: - - type - - template - - type: object - title: InputMessagesItemReference - properties: - type: - type: string - enum: - - item_reference - description: The type of input messages. Always `item_reference`. - item_reference: - type: string - description: A reference to a variable in the `item` namespace. Ie, "item.name" - required: - - type - - item_reference - discriminator: - propertyName: type - sampling_params: - type: object - properties: - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - temperature: - type: number - description: A higher temperature increases randomness in the outputs. - default: 1 - max_completion_tokens: - type: integer - description: The maximum number of tokens in the generated output. - top_p: - type: number - description: An alternative to temperature for nucleus sampling; 1.0 includes all tokens. - default: 1 - seed: - type: integer - description: A seed value to initialize the randomness, during sampling. - default: 42 - tools: - type: array - description: | - 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: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the - model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) - or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, - enabling the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - items: - $ref: '#/components/schemas/Tool' - text: - type: object - description: | - Configuration options for a text response from the model. Can be plain - text or structured JSON data. Learn more: - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - properties: - format: - $ref: '#/components/schemas/TextResponseFormatConfiguration' - model: - type: string - description: The name of the model to use for generating completions (e.g. "o3-mini"). - source: - description: Determines what populates the `item` namespace in this run's data source. - anyOf: - - $ref: '#/components/schemas/EvalJsonlFileContentSource' - - $ref: '#/components/schemas/EvalJsonlFileIdSource' - - $ref: '#/components/schemas/EvalResponsesSource' - discriminator: - propertyName: type - required: - - type - - source - x-oaiMeta: - name: The completions data source object used to configure an individual run - group: eval runs - example: | - { - "name": "gpt-4o-mini-2024-07-18", - "data_source": { - "type": "responses", - "input_messages": { - "type": "item_reference", - "item_reference": "item.input" - }, - "model": "gpt-4o-mini-2024-07-18", - "source": { - "type": "responses", - "model": "gpt-4o-mini-2024-07-18" - } - } - } - CreateEvalRunRequest: - type: object - title: CreateEvalRunRequest - properties: - name: - type: string - description: The name of the run. - metadata: - $ref: '#/components/schemas/Metadata' - data_source: - type: object - description: Details about the run's data source. - anyOf: - - $ref: '#/components/schemas/CreateEvalJsonlRunDataSource' - - $ref: '#/components/schemas/CreateEvalCompletionsRunDataSource' - - $ref: '#/components/schemas/CreateEvalResponsesRunDataSource' - required: - - data_source - CreateEvalStoredCompletionsDataSourceConfig: - type: object - title: StoredCompletionsDataSourceConfig - description: | - Deprecated in favor of LogsDataSourceConfig. - properties: - type: - type: string - enum: - - stored_completions - default: stored_completions - description: The type of data source. Always `stored_completions`. - x-stainless-const: true - metadata: - type: object - description: Metadata filters for the stored completions data source. - additionalProperties: true - required: - - type - deprecated: true - x-oaiMeta: - name: The stored completions data source object for evals - group: evals - example: | - { - "type": "stored_completions", - "metadata": { - "use_case": "customer_support_agent" - } - } - CreateFileRequest: - type: object - additionalProperties: false - properties: - file: - description: | - The File object (not file name) to be uploaded. - type: string - format: binary - x-oaiMeta: - exampleFilePath: fine-tune.jsonl - purpose: - $ref: '#/components/schemas/FilePurpose' - expires_after: - $ref: '#/components/schemas/FileExpirationAfter' - required: - - file - - purpose - CreateFineTuningCheckpointPermissionRequest: - type: object - additionalProperties: false - properties: - project_ids: - type: array - description: The project identifiers to grant access to. - items: - type: string - required: - - project_ids - CreateFineTuningJobRequest: - type: object - properties: - model: - description: > - The name of the model to fine-tune. You can select one of the - - [supported - models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). - example: gpt-4o-mini - anyOf: - - type: string - - type: string - enum: - - babbage-002 - - davinci-002 - - gpt-3.5-turbo - - gpt-4o-mini - title: Preset - x-oaiTypeLabel: string - training_file: - description: > - The ID of an uploaded file that contains training data. - - - See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a - file. - - - Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the - purpose `fine-tune`. - - - The contents of the file should differ depending on if the model uses the - [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), - [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) - format, or if the fine-tuning method uses the - [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format. - - - See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more - details. - type: string - example: file-abc123 - hyperparameters: - type: object - description: > - The hyperparameters used for the fine-tuning job. - - This value is now deprecated in favor of `method`, and should be passed in under the `method` - parameter. - properties: - batch_size: - description: | - Number of examples in each batch. A larger batch size means that model parameters - are updated less frequently, but with lower variance. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - title: Auto - - type: integer - minimum: 1 - maximum: 256 - learning_rate_multiplier: - description: | - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid - overfitting. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - title: Auto - - type: number - minimum: 0 - exclusiveMinimum: true - n_epochs: - description: | - The number of epochs to train the model for. An epoch refers to one full cycle - through the training dataset. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - title: Auto - - type: integer - minimum: 1 - maximum: 50 - deprecated: true - suffix: - description: > - A string of up to 64 characters that will be added to your fine-tuned model name. - - - For example, a `suffix` of "custom-model-name" would produce a model name like - `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. - type: string - minLength: 1 - maxLength: 64 - default: null - nullable: true - validation_file: - description: > - The ID of an uploaded file that contains validation data. - - - If you provide this file, the data is used to generate validation - - metrics periodically during fine-tuning. These metrics can be viewed in - - the fine-tuning results file. - - The same data should not be present in both train and validation files. - - - Your dataset must be formatted as a JSONL file. You must upload your file with the purpose - `fine-tune`. - - - See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more - details. - type: string - nullable: true - example: file-abc123 - integrations: - type: array - description: A list of integrations to enable for your fine-tuning job. - nullable: true - items: - type: object - required: - - type - - wandb - properties: - type: - description: > - The type of integration to enable. Currently, only "wandb" (Weights and Biases) is - supported. - anyOf: - - type: string - enum: - - wandb - x-stainless-const: true - wandb: - type: object - description: > - The settings for your integration with Weights and Biases. This payload specifies the - project that - - metrics will be sent to. Optionally, you can set an explicit display name for your run, add - tags - - to your run, and set a default entity (team, username, etc) to be associated with your run. - required: - - project - properties: - project: - description: | - The name of the project that the new run will be created under. - type: string - example: my-wandb-project - name: - description: | - A display name to set for the run. If not set, we will use the Job ID as the name. - nullable: true - type: string - entity: - description: > - The entity to use for the run. This allows you to set the team or username of the WandB - user that you would - - like associated with the run. If not set, the default entity for the registered WandB - API key is used. - nullable: true - type: string - tags: - description: > - A list of tags to be attached to the newly created run. These tags are passed through - directly to WandB. Some - - default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", - "openai/{ftjob-abcdef}". - type: array - items: - type: string - example: custom-tag - seed: - description: > - The seed controls the reproducibility of the job. Passing in the same seed and job parameters - should produce the same results, but may differ in rare cases. - - If a seed is not specified, one will be generated for you. - type: integer - nullable: true - minimum: 0 - maximum: 2147483647 - example: 42 - method: - $ref: '#/components/schemas/FineTuneMethod' - metadata: - $ref: '#/components/schemas/Metadata' - required: - - model - - training_file - CreateGroupBody: - type: object - description: Request payload for creating a new group in the organization. - properties: - name: - type: string - description: Human readable name for the group. - minLength: 1 - maxLength: 255 - required: - - name - x-oaiMeta: - example: | - { - "name": "Support Team" - } - CreateGroupUserBody: - type: object - description: Request payload for adding a user to a group. - properties: - user_id: - type: string - description: Identifier of the user to add to the group. - required: - - user_id - x-oaiMeta: - example: | - { - "user_id": "user_abc123" - } - CreateImageEditRequest: - type: object - properties: - image: - anyOf: - - type: string - format: binary - - type: array - maxItems: 16 - items: - type: string - format: binary - description: | - The image(s) to edit. Must be a supported image file or an array of images. - - For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less - than 50MB. You can provide up to 16 images. - - For `dall-e-2`, you can only provide one image, and it should be a square - `png` file less than 4MB. - x-oaiMeta: - exampleFilePath: otter.png - prompt: - description: >- - A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, - and 32000 characters for `gpt-image-1`. - type: string - example: A cute baby sea otter wearing a beret - mask: - description: >- - An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where - `image` should be edited. If there are multiple images provided, the mask will be applied on the - first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. - type: string - format: binary - x-oaiMeta: - exampleFilePath: mask.png - background: - type: string - enum: - - transparent - - opaque - - auto - default: auto - example: transparent - nullable: true - description: | - Allows to set transparency for the background of the generated image(s). - This parameter is only supported for `gpt-image-1`. Must be one of - `transparent`, `opaque` or `auto` (default value). When `auto` is used, the - model will automatically determine the best background for the image. - - If `transparent`, the output format needs to support transparency, so it - should be set to either `png` (default value) or `webp`. - model: - anyOf: - - type: string - - type: string - enum: - - dall-e-2 - - gpt-image-1 - - gpt-image-1-mini - x-stainless-const: true - x-oaiTypeLabel: string - nullable: true - description: >- - The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults - to `dall-e-2` unless a parameter specific to `gpt-image-1` is used. - 'n': - type: integer - minimum: 1 - maximum: 10 - default: 1 - example: 1 - nullable: true - description: The number of images to generate. Must be between 1 and 10. - size: - type: string - enum: - - 256x256 - - 512x512 - - 1024x1024 - - 1536x1024 - - 1024x1536 - - auto - default: 1024x1024 - example: 1024x1024 - nullable: true - description: >- - The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` - (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or - `1024x1024` for `dall-e-2`. - response_format: - type: string - enum: - - url - - b64_json - default: url - example: url - nullable: true - description: >- - The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs - are only valid for 60 minutes after the image has been generated. This parameter is only supported - for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images. - output_format: - type: string - enum: - - png - - jpeg - - webp - default: png - example: png - nullable: true - description: | - The format in which the generated images are returned. This parameter is - only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. - The default value is `png`. - output_compression: - type: integer - default: 100 - example: 100 - nullable: true - description: | - The compression level (0-100%) for the generated images. This parameter - is only supported for `gpt-image-1` with the `webp` or `jpeg` output - formats, and defaults to 100. - user: - type: string - example: user-1234 - description: > - A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - input_fidelity: - anyOf: - - $ref: '#/components/schemas/InputFidelity' - - type: 'null' - stream: - type: boolean - default: false - example: false - nullable: true - description: > - Edit the image in streaming mode. Defaults to `false`. See the - - [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more - information. - partial_images: - $ref: '#/components/schemas/PartialImages' - quality: - type: string - enum: - - standard - - low - - medium - - high - - auto - default: auto - example: high - nullable: true - description: > - The quality of the image that will be generated. `high`, `medium` and `low` are only supported for - `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`. - required: - - prompt - - image - CreateImageRequest: - type: object - properties: - prompt: - description: >- - A text description of the desired image(s). The maximum length is 32000 characters for - `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. - type: string - example: A cute baby sea otter - model: - anyOf: - - type: string - - type: string - enum: - - dall-e-2 - - dall-e-3 - - gpt-image-1 - - gpt-image-1-mini - x-stainless-nominal: false - x-oaiTypeLabel: string - nullable: true - description: >- - The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults - to `dall-e-2` unless a parameter specific to `gpt-image-1` is used. - 'n': - type: integer - minimum: 1 - maximum: 10 - default: 1 - example: 1 - nullable: true - description: >- - The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is - supported. - quality: - type: string - enum: - - standard - - hd - - low - - medium - - high - - auto - default: auto - example: medium - nullable: true - description: | - The quality of the image that will be generated. - - - `auto` (default value) will automatically select the best quality for the given model. - - `high`, `medium` and `low` are supported for `gpt-image-1`. - - `hd` and `standard` are supported for `dall-e-3`. - - `standard` is the only option for `dall-e-2`. - response_format: - type: string - enum: - - url - - b64_json - default: url - example: url - nullable: true - description: >- - The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of - `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This - parameter isn't supported for `gpt-image-1` which will always return base64-encoded images. - output_format: - type: string - enum: - - png - - jpeg - - webp - default: png - example: png - nullable: true - description: >- - The format in which the generated images are returned. This parameter is only supported for - `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. - output_compression: - type: integer - default: 100 - example: 100 - nullable: true - description: >- - The compression level (0-100%) for the generated images. This parameter is only supported for - `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100. - stream: - type: boolean - default: false - example: false - nullable: true - description: > - Generate the image in streaming mode. Defaults to `false`. See the - - [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more - information. - - This parameter is only supported for `gpt-image-1`. - partial_images: - $ref: '#/components/schemas/PartialImages' - size: - type: string - enum: - - auto - - 1024x1024 - - 1536x1024 - - 1024x1536 - - 256x256 - - 512x512 - - 1792x1024 - - 1024x1792 - default: auto - example: 1024x1024 - nullable: true - description: >- - The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` - (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or - `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. - moderation: - type: string - enum: - - low - - auto - default: auto - example: low - nullable: true - description: >- - Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` - for less restrictive filtering or `auto` (default value). - background: - type: string - enum: - - transparent - - opaque - - auto - default: auto - example: transparent - nullable: true - description: | - Allows to set transparency for the background of the generated image(s). - This parameter is only supported for `gpt-image-1`. Must be one of - `transparent`, `opaque` or `auto` (default value). When `auto` is used, the - model will automatically determine the best background for the image. - - If `transparent`, the output format needs to support transparency, so it - should be set to either `png` (default value) or `webp`. - style: - type: string - enum: - - vivid - - natural - default: vivid - example: vivid - nullable: true - description: >- - The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of - `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic - images. Natural causes the model to produce more natural, less hyper-real looking images. - user: - type: string - example: user-1234 - description: > - A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - required: - - prompt - CreateImageVariationRequest: - type: object - properties: - image: - description: >- - The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and - square. - type: string - format: binary - x-oaiMeta: - exampleFilePath: otter.png - model: - anyOf: - - type: string - - type: string - enum: - - dall-e-2 - x-stainless-const: true - x-oaiTypeLabel: string - nullable: true - description: The model to use for image generation. Only `dall-e-2` is supported at this time. - 'n': - type: integer - minimum: 1 - maximum: 10 - default: 1 - example: 1 - nullable: true - description: The number of images to generate. Must be between 1 and 10. - response_format: - type: string - enum: - - url - - b64_json - default: url - example: url - nullable: true - description: >- - The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs - are only valid for 60 minutes after the image has been generated. - size: - type: string - enum: - - 256x256 - - 512x512 - - 1024x1024 - default: 1024x1024 - example: 1024x1024 - nullable: true - description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. - user: - type: string - example: user-1234 - description: > - A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - required: - - image - CreateMessageRequest: - type: object - additionalProperties: false - required: - - role - - content - properties: - role: - type: string - enum: - - user - - assistant - description: > - The role of the entity that is creating the message. Allowed values include: - - - `user`: Indicates the message is sent by an actual user and should be used in most cases to - represent user-generated messages. - - - `assistant`: Indicates the message is generated by the assistant. Use this value to insert - messages from the assistant into the conversation. - content: - anyOf: - - type: string - description: The text contents of the message. - title: Text content - - type: array - description: >- - An array of content parts with a defined type, each can be of type `text` or images can be - passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible - models](https://platform.openai.com/docs/models). - title: Array of content parts - items: - anyOf: - - $ref: '#/components/schemas/MessageContentImageFileObject' - - $ref: '#/components/schemas/MessageContentImageUrlObject' - - $ref: '#/components/schemas/MessageRequestContentTextObject' - discriminator: - propertyName: type - minItems: 1 - attachments: - anyOf: - - type: array - items: - type: object - properties: - file_id: - type: string - description: The ID of the file to attach to the message. - tools: - description: The tools to add this file to. - type: array - items: - anyOf: - - $ref: '#/components/schemas/AssistantToolsCode' - - $ref: '#/components/schemas/AssistantToolsFileSearchTypeOnly' - discriminator: - propertyName: type - description: A list of files attached to the message, and the tools they should be added to. - required: - - file_id - - tools - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - CreateModelResponseProperties: - allOf: - - $ref: '#/components/schemas/ModelResponseProperties' - - type: object - properties: - top_logprobs: - description: | - An integer between 0 and 20 specifying the number of most likely tokens to - return at each token position, each with an associated log probability. - type: integer - minimum: 0 - maximum: 20 - CreateModerationRequest: - type: object - properties: - input: - description: | - Input (or inputs) to classify. Can be a single string, an array of strings, or - an array of multi-modal input objects similar to other models. - anyOf: - - type: string - description: A string of text to classify for moderation. - default: '' - example: I want to kill them. - - type: array - description: An array of strings to classify for moderation. - items: - type: string - default: '' - example: I want to kill them. - - type: array - description: An array of multi-modal inputs to the moderation model. - items: - anyOf: - - $ref: '#/components/schemas/ModerationImageURLInput' - - $ref: '#/components/schemas/ModerationTextInput' - discriminator: - propertyName: type - title: Moderation Multi Modal Array - model: - description: | - The content moderation model you would like to use. Learn more in - [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about - available models [here](https://platform.openai.com/docs/models#moderation). - nullable: false - anyOf: - - type: string - - type: string - enum: - - omni-moderation-latest - - omni-moderation-2024-09-26 - - text-moderation-latest - - text-moderation-stable - x-stainless-nominal: false - x-oaiTypeLabel: string - required: - - input - CreateModerationResponse: - type: object - description: Represents if a given text input is potentially harmful. - properties: - id: - type: string - description: The unique identifier for the moderation request. - model: - type: string - description: The model used to generate the moderation results. - results: - type: array - description: A list of moderation objects. - items: - type: object - properties: - flagged: - type: boolean - description: Whether any of the below categories are flagged. - categories: - type: object - description: A list of the categories, and whether they are flagged or not. - properties: - hate: - type: boolean - description: >- - Content that expresses, incites, or promotes hate based on race, gender, ethnicity, - religion, nationality, sexual orientation, disability status, or caste. Hateful content - aimed at non-protected groups (e.g., chess players) is harassment. - hate/threatening: - type: boolean - description: >- - Hateful content that also includes violence or serious harm towards the targeted group - based on race, gender, ethnicity, religion, nationality, sexual orientation, disability - status, or caste. - harassment: - type: boolean - description: Content that expresses, incites, or promotes harassing language towards any target. - harassment/threatening: - type: boolean - description: Harassment content that also includes violence or serious harm towards any target. - illicit: - anyOf: - - type: boolean - description: >- - Content that includes instructions or advice that facilitate the planning or - execution of wrongdoing, or that gives advice or instruction on how to commit - illicit acts. For example, "how to shoplift" would fit this category. - - type: 'null' - illicit/violent: - anyOf: - - type: boolean - description: >- - Content that includes instructions or advice that facilitate the planning or - execution of wrongdoing that also includes violence, or that gives advice or - instruction on the procurement of any weapon. - - type: 'null' - self-harm: - type: boolean - description: >- - Content that promotes, encourages, or depicts acts of self-harm, such as suicide, - cutting, and eating disorders. - self-harm/intent: - type: boolean - description: >- - Content where the speaker expresses that they are engaging or intend to engage in acts - of self-harm, such as suicide, cutting, and eating disorders. - self-harm/instructions: - type: boolean - description: >- - Content that encourages performing acts of self-harm, such as suicide, cutting, and - eating disorders, or that gives instructions or advice on how to commit such acts. - sexual: - type: boolean - description: >- - Content meant to arouse sexual excitement, such as the description of sexual activity, - or that promotes sexual services (excluding sex education and wellness). - sexual/minors: - type: boolean - description: Sexual content that includes an individual who is under 18 years old. - violence: - type: boolean - description: Content that depicts death, violence, or physical injury. - violence/graphic: - type: boolean - description: Content that depicts death, violence, or physical injury in graphic detail. - required: - - hate - - hate/threatening - - harassment - - harassment/threatening - - illicit - - illicit/violent - - self-harm - - self-harm/intent - - self-harm/instructions - - sexual - - sexual/minors - - violence - - violence/graphic - category_scores: - type: object - description: A list of the categories along with their scores as predicted by model. - properties: - hate: - type: number - description: The score for the category 'hate'. - hate/threatening: - type: number - description: The score for the category 'hate/threatening'. - harassment: - type: number - description: The score for the category 'harassment'. - harassment/threatening: - type: number - description: The score for the category 'harassment/threatening'. - illicit: - type: number - description: The score for the category 'illicit'. - illicit/violent: - type: number - description: The score for the category 'illicit/violent'. - self-harm: - type: number - description: The score for the category 'self-harm'. - self-harm/intent: - type: number - description: The score for the category 'self-harm/intent'. - self-harm/instructions: - type: number - description: The score for the category 'self-harm/instructions'. - sexual: - type: number - description: The score for the category 'sexual'. - sexual/minors: - type: number - description: The score for the category 'sexual/minors'. - violence: - type: number - description: The score for the category 'violence'. - violence/graphic: - type: number - description: The score for the category 'violence/graphic'. - required: - - hate - - hate/threatening - - harassment - - harassment/threatening - - illicit - - illicit/violent - - self-harm - - self-harm/intent - - self-harm/instructions - - sexual - - sexual/minors - - violence - - violence/graphic - category_applied_input_types: - type: object - description: A list of the categories along with the input type(s) that the score applies to. - properties: - hate: - type: array - description: The applied input type(s) for the category 'hate'. - items: - type: string - enum: - - text - x-stainless-const: true - hate/threatening: - type: array - description: The applied input type(s) for the category 'hate/threatening'. - items: - type: string - enum: - - text - x-stainless-const: true - harassment: - type: array - description: The applied input type(s) for the category 'harassment'. - items: - type: string - enum: - - text - x-stainless-const: true - harassment/threatening: - type: array - description: The applied input type(s) for the category 'harassment/threatening'. - items: - type: string - enum: - - text - x-stainless-const: true - illicit: - type: array - description: The applied input type(s) for the category 'illicit'. - items: - type: string - enum: - - text - x-stainless-const: true - illicit/violent: - type: array - description: The applied input type(s) for the category 'illicit/violent'. - items: - type: string - enum: - - text - x-stainless-const: true - self-harm: - type: array - description: The applied input type(s) for the category 'self-harm'. - items: - type: string - enum: - - text - - image - self-harm/intent: - type: array - description: The applied input type(s) for the category 'self-harm/intent'. - items: - type: string - enum: - - text - - image - self-harm/instructions: - type: array - description: The applied input type(s) for the category 'self-harm/instructions'. - items: - type: string - enum: - - text - - image - sexual: - type: array - description: The applied input type(s) for the category 'sexual'. - items: - type: string - enum: - - text - - image - sexual/minors: - type: array - description: The applied input type(s) for the category 'sexual/minors'. - items: - type: string - enum: - - text - x-stainless-const: true - violence: - type: array - description: The applied input type(s) for the category 'violence'. - items: - type: string - enum: - - text - - image - violence/graphic: - type: array - description: The applied input type(s) for the category 'violence/graphic'. - items: - type: string - enum: - - text - - image - required: - - hate - - hate/threatening - - harassment - - harassment/threatening - - illicit - - illicit/violent - - self-harm - - self-harm/intent - - self-harm/instructions - - sexual - - sexual/minors - - violence - - violence/graphic - required: - - flagged - - categories - - category_scores - - category_applied_input_types - required: - - id - - model - - results - x-oaiMeta: - name: The moderation object - example: | - { - "id": "modr-0d9740456c391e43c445bf0f010940c7", - "model": "omni-moderation-latest", - "results": [ - { - "flagged": true, - "categories": { - "harassment": true, - "harassment/threatening": true, - "sexual": false, - "hate": false, - "hate/threatening": false, - "illicit": false, - "illicit/violent": false, - "self-harm/intent": false, - "self-harm/instructions": false, - "self-harm": false, - "sexual/minors": false, - "violence": true, - "violence/graphic": true - }, - "category_scores": { - "harassment": 0.8189693396524255, - "harassment/threatening": 0.804985420696006, - "sexual": 1.573112165348997e-6, - "hate": 0.007562942636942845, - "hate/threatening": 0.004208854591835476, - "illicit": 0.030535955153511665, - "illicit/violent": 0.008925306722380033, - "self-harm/intent": 0.00023023930975076432, - "self-harm/instructions": 0.0002293869201073356, - "self-harm": 0.012598046106750154, - "sexual/minors": 2.212566909570261e-8, - "violence": 0.9999992735124786, - "violence/graphic": 0.843064871157054 - }, - "category_applied_input_types": { - "harassment": [ - "text" - ], - "harassment/threatening": [ - "text" - ], - "sexual": [ - "text", - "image" - ], - "hate": [ - "text" - ], - "hate/threatening": [ - "text" - ], - "illicit": [ - "text" - ], - "illicit/violent": [ - "text" - ], - "self-harm/intent": [ - "text", - "image" - ], - "self-harm/instructions": [ - "text", - "image" - ], - "self-harm": [ - "text", - "image" - ], - "sexual/minors": [ - "text" - ], - "violence": [ - "text", - "image" - ], - "violence/graphic": [ - "text", - "image" - ] - } - } - ] - } - CreateResponse: - allOf: - - $ref: '#/components/schemas/CreateModelResponseProperties' - - $ref: '#/components/schemas/ResponseProperties' - - type: object - properties: - input: - $ref: '#/components/schemas/InputParam' - include: - anyOf: - - type: array - description: >- - 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 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). - items: - $ref: '#/components/schemas/IncludeEnum' - - type: 'null' - parallel_tool_calls: - anyOf: - - type: boolean - description: | - Whether to allow the model to run tool calls in parallel. - default: true - - type: 'null' - store: - anyOf: - - type: boolean - description: | - Whether to store the generated model response for later retrieval via - API. - default: true - - type: 'null' - instructions: - anyOf: - - type: string - description: | - A system (or developer) message inserted into the model's context. - - When using along with `previous_response_id`, the instructions from a previous - response will not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - type: 'null' - stream: - anyOf: - - description: > - If set to true, the model response data will be streamed to the client - - as it is generated using [server-sent - events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - - See the [Streaming section - below](https://platform.openai.com/docs/api-reference/responses-streaming) - - for more information. - type: boolean - default: false - - type: 'null' - stream_options: - $ref: '#/components/schemas/ResponseStreamOptions' - conversation: - anyOf: - - $ref: '#/components/schemas/ConversationParam' - - type: 'null' - CreateRunRequest: - type: object - additionalProperties: false - properties: - assistant_id: - description: >- - The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - execute this run. - type: string - model: - description: >- - The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute - this run. If a value is provided here, it will override the model associated with the assistant. - If not, the model associated with the assistant will be used. - anyOf: - - type: string - - $ref: '#/components/schemas/AssistantSupportedModels' - x-oaiTypeLabel: string - nullable: true - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - instructions: - description: >- - Overrides the - [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the - assistant. This is useful for modifying the behavior on a per-run basis. - type: string - nullable: true - additional_instructions: - description: >- - Appends additional instructions at the end of the instructions for the run. This is useful for - modifying the behavior on a per-run basis without overriding other instructions. - type: string - nullable: true - additional_messages: - description: Adds additional messages to the thread before creating the run. - type: array - items: - $ref: '#/components/schemas/CreateMessageRequest' - nullable: true - tools: - description: >- - Override the tools the assistant can use for this run. This is useful for modifying the behavior - on a per-run basis. - nullable: true - type: array - maxItems: 20 - items: - $ref: '#/components/schemas/AssistantTool' - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model considers - the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the - top 10% probability mass are considered. - - - We generally recommend altering this or temperature but not both. - stream: - type: boolean - nullable: true - description: > - If `true`, returns a stream of events that happen during the Run as server-sent events, - terminating when the Run enters a terminal state with a `data: [DONE]` message. - max_prompt_tokens: - type: integer - nullable: true - description: > - The maximum number of prompt tokens that may be used over the course of the run. The run will make - a best effort to use only the number of prompt tokens specified, across multiple turns of the run. - If the run exceeds the number of prompt tokens specified, the run will end with status - `incomplete`. See `incomplete_details` for more info. - minimum: 256 - max_completion_tokens: - type: integer - nullable: true - description: > - The maximum number of completion tokens that may be used over the course of the run. The run will - make a best effort to use only the number of completion tokens specified, across multiple turns of - the run. If the run exceeds the number of completion tokens specified, the run will end with - status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - truncation_strategy: - allOf: - - $ref: '#/components/schemas/TruncationObject' - - nullable: true - tool_choice: - allOf: - - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - - nullable: true - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - response_format: - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - nullable: true - required: &ref_0 - - assistant_id - CreateSpeechRequest: - type: object - additionalProperties: false - properties: - model: - description: > - One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, - `tts-1-hd` or `gpt-4o-mini-tts`. - anyOf: - - type: string - - type: string - enum: - - tts-1 - - tts-1-hd - - gpt-4o-mini-tts - x-stainless-nominal: false - x-oaiTypeLabel: string - input: - type: string - description: The text to generate audio for. The maximum length is 4096 characters. - maxLength: 4096 - instructions: - type: string - description: >- - Control the voice of your generated audio with additional instructions. Does not work with `tts-1` - or `tts-1-hd`. - maxLength: 4096 - voice: - description: >- - The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, - `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices - are available in the [Text to speech - guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). - $ref: '#/components/schemas/VoiceIdsShared' - response_format: - description: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. - default: mp3 - type: string - enum: - - mp3 - - opus - - aac - - flac - - wav - - pcm - speed: - description: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. - type: number - default: 1 - minimum: 0.25 - maximum: 4 - stream_format: - description: >- - The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported - for `tts-1` or `tts-1-hd`. - type: string - default: audio - enum: - - sse - - audio - required: - - model - - input - - voice - CreateSpeechResponseStreamEvent: - anyOf: - - $ref: '#/components/schemas/SpeechAudioDeltaEvent' - - $ref: '#/components/schemas/SpeechAudioDoneEvent' - discriminator: - propertyName: type - CreateThreadAndRunRequest: - type: object - additionalProperties: false - properties: - assistant_id: - description: >- - The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - execute this run. - type: string - thread: - $ref: '#/components/schemas/CreateThreadRequest' - model: - description: >- - The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute - this run. If a value is provided here, it will override the model associated with the assistant. - If not, the model associated with the assistant will be used. - anyOf: - - type: string - - type: string - enum: - - gpt-5 - - gpt-5-mini - - gpt-5-nano - - gpt-5-2025-08-07 - - gpt-5-mini-2025-08-07 - - gpt-5-nano-2025-08-07 - - gpt-4.1 - - gpt-4.1-mini - - gpt-4.1-nano - - gpt-4.1-2025-04-14 - - gpt-4.1-mini-2025-04-14 - - gpt-4.1-nano-2025-04-14 - - gpt-4o - - gpt-4o-2024-11-20 - - gpt-4o-2024-08-06 - - gpt-4o-2024-05-13 - - gpt-4o-mini - - gpt-4o-mini-2024-07-18 - - gpt-4.5-preview - - gpt-4.5-preview-2025-02-27 - - gpt-4-turbo - - gpt-4-turbo-2024-04-09 - - gpt-4-0125-preview - - gpt-4-turbo-preview - - gpt-4-1106-preview - - gpt-4-vision-preview - - gpt-4 - - gpt-4-0314 - - gpt-4-0613 - - gpt-4-32k - - gpt-4-32k-0314 - - gpt-4-32k-0613 - - gpt-3.5-turbo - - gpt-3.5-turbo-16k - - gpt-3.5-turbo-0613 - - gpt-3.5-turbo-1106 - - gpt-3.5-turbo-0125 - - gpt-3.5-turbo-16k-0613 - x-oaiTypeLabel: string - nullable: true - instructions: - description: >- - Override the default system message of the assistant. This is useful for modifying the behavior on - a per-run basis. - type: string - nullable: true - tools: - description: >- - Override the tools the assistant can use for this run. This is useful for modifying the behavior - on a per-run basis. - nullable: true - type: array - maxItems: 20 - items: - $ref: '#/components/schemas/AssistantTool' - tool_resources: - type: object - description: > - A set of resources that are used by the assistant's tools. The resources are specific to the type - of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the - `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available - to the `code_interpreter` tool. There can be a maximum of 20 files associated with the - tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The ID of the [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to - this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - nullable: true - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model considers - the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the - top 10% probability mass are considered. - - - We generally recommend altering this or temperature but not both. - stream: - type: boolean - nullable: true - description: > - If `true`, returns a stream of events that happen during the Run as server-sent events, - terminating when the Run enters a terminal state with a `data: [DONE]` message. - max_prompt_tokens: - type: integer - nullable: true - description: > - The maximum number of prompt tokens that may be used over the course of the run. The run will make - a best effort to use only the number of prompt tokens specified, across multiple turns of the run. - If the run exceeds the number of prompt tokens specified, the run will end with status - `incomplete`. See `incomplete_details` for more info. - minimum: 256 - max_completion_tokens: - type: integer - nullable: true - description: > - The maximum number of completion tokens that may be used over the course of the run. The run will - make a best effort to use only the number of completion tokens specified, across multiple turns of - the run. If the run exceeds the number of completion tokens specified, the run will end with - status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - truncation_strategy: - allOf: - - $ref: '#/components/schemas/TruncationObject' - - nullable: true - tool_choice: - allOf: - - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - - nullable: true - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - response_format: - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - nullable: true - required: *ref_0 - CreateThreadRequest: - type: object - description: | - Options to create a new thread. If no thread is provided when running a - request, an empty thread will be created. - additionalProperties: false - properties: - messages: - description: >- - A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread - with. - type: array - items: - $ref: '#/components/schemas/CreateMessageRequest' - tool_resources: - anyOf: - - type: object - description: > - A set of resources that are made available to the assistant's tools in this thread. The - resources are specific to the type of tool. For example, the `code_interpreter` tool requires - a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - available to the `code_interpreter` tool. There can be a maximum of 20 files - associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached - to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: string - vector_stores: - type: array - description: > - A helper to create a [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) with - file_ids and attach it to this thread. There can be a maximum of 1 vector store - attached to the thread. - maxItems: 1 - items: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to - add to the vector store. There can be a maximum of 10000 files in a vector - store. - maxItems: 10000 - items: - type: string - chunking_strategy: - type: object - description: >- - The chunking strategy used to chunk the file(s). If not set, will use the `auto` - strategy. - anyOf: - - type: object - title: Auto Chunking Strategy - description: >- - The default strategy. This strategy currently uses a `max_chunk_size_tokens` - of `800` and `chunk_overlap_tokens` of `400`. - additionalProperties: false - properties: - type: - type: string - description: Always `auto`. - enum: - - auto - x-stainless-const: true - required: - - type - - type: object - title: Static Chunking Strategy - additionalProperties: false - properties: - type: - type: string - description: Always `static`. - enum: - - static - x-stainless-const: true - static: - type: object - additionalProperties: false - properties: - max_chunk_size_tokens: - type: integer - minimum: 100 - maximum: 4096 - description: >- - The maximum number of tokens in each chunk. The default value is - `800`. The minimum value is `100` and the maximum value is `4096`. - chunk_overlap_tokens: - type: integer - description: > - The number of tokens that overlap between chunks. The default value - is `400`. - - - Note that the overlap must not exceed half of - `max_chunk_size_tokens`. - required: - - max_chunk_size_tokens - - chunk_overlap_tokens - required: - - type - - static - discriminator: - propertyName: type - metadata: - $ref: '#/components/schemas/Metadata' - anyOf: - - required: - - vector_store_ids - - required: - - vector_stores - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - CreateTranscriptionRequest: - type: object - additionalProperties: false - properties: - file: - description: > - The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, - mpeg, mpga, m4a, ogg, wav, or webm. - type: string - x-oaiTypeLabel: file - format: binary - x-oaiMeta: - exampleFilePath: speech.mp3 - model: - description: > - ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `whisper-1` - (which is powered by our open source Whisper V2 model), and `gpt-4o-transcribe-diarize`. - example: gpt-4o-transcribe - anyOf: - - type: string - - type: string - enum: - - whisper-1 - - gpt-4o-transcribe - - gpt-4o-mini-transcribe - - gpt-4o-transcribe-diarize - x-stainless-const: true - x-stainless-nominal: false - x-oaiTypeLabel: string - language: - description: > - 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. - type: string - prompt: - description: > - 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. This field is not supported when using `gpt-4o-transcribe-diarize`. - type: string - response_format: - $ref: '#/components/schemas/AudioResponseFormat' - temperature: - description: > - The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more - random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the - model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically - increase the temperature until certain thresholds are hit. - type: number - default: 0 - include: - description: > - Additional information to include in the transcription response. - - `logprobs` will return the log probabilities of the tokens in the - - response to understand the model's confidence in the transcription. - - `logprobs` only works with response_format set to `json` and only with - - the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`. This field is not supported when - using `gpt-4o-transcribe-diarize`. - type: array - items: - $ref: '#/components/schemas/TranscriptionInclude' - timestamp_granularities: - description: > - The timestamp granularities to populate for this transcription. `response_format` must be set - `verbose_json` to use timestamp granularities. Either or both of these options are supported: - `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating - word timestamps incurs additional latency. - - This option is not available for `gpt-4o-transcribe-diarize`. - type: array - items: - type: string - enum: - - word - - segment - default: - - segment - stream: - anyOf: - - description: > - If set to true, the model response data will be streamed to the client - - as it is generated using [server-sent - events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - - See the [Streaming section of the Speech-to-Text - guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) - - for more information. - - - Note: Streaming is not supported for the `whisper-1` model and will be ignored. - type: boolean - default: false - - type: 'null' - chunking_strategy: - $ref: '#/components/schemas/TranscriptionChunkingStrategy' - known_speaker_names: - description: > - Optional list of speaker names that correspond to the audio samples provided in - `known_speaker_references[]`. Each entry should be a short identifier (for example `customer` or - `agent`). Up to 4 speakers are supported. - type: array - maxItems: 4 - items: - type: string - known_speaker_references: - description: > - Optional list of audio samples (as [data - URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)) that contain - known speaker references matching `known_speaker_names[]`. Each sample must be between 2 and 10 - seconds, and can use any of the same input audio formats supported by `file`. - type: array - maxItems: 4 - items: - type: string - required: - - file - - model - CreateTranscriptionResponseDiarizedJson: - type: object - description: > - Represents a diarized transcription response returned by the model, including the combined transcript - and speaker-segment annotations. - properties: - task: - type: string - description: The type of task that was run. Always `transcribe`. - enum: - - transcribe - x-stainless-const: true - duration: - type: number - description: Duration of the input audio in seconds. - text: - type: string - description: The concatenated transcript text for the entire audio input. - segments: - type: array - description: Segments of the transcript annotated with timestamps and speaker labels. - items: - $ref: '#/components/schemas/TranscriptionDiarizedSegment' - usage: - type: object - description: Token or duration usage statistics for the request. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/TranscriptTextUsageTokens' - title: Token Usage - - $ref: '#/components/schemas/TranscriptTextUsageDuration' - title: Duration Usage - required: - - task - - duration - - text - - segments - x-oaiMeta: - name: The transcription object (Diarized JSON) - group: audio - example: | - { - "task": "transcribe", - "duration": 42.7, - "text": "Agent: Thanks for calling OpenAI support.\nCustomer: Hi, I need help with diarization.", - "segments": [ - { - "type": "transcript.text.segment", - "id": "seg_001", - "start": 0.0, - "end": 5.2, - "text": "Thanks for calling OpenAI support.", - "speaker": "agent" - }, - { - "type": "transcript.text.segment", - "id": "seg_002", - "start": 5.2, - "end": 12.8, - "text": "Hi, I need help with diarization.", - "speaker": "A" - } - ], - "usage": { - "type": "duration", - "seconds": 43 - } - } - CreateTranscriptionResponseJson: - type: object - description: Represents a transcription response returned by model, based on the provided input. - properties: - text: - type: string - description: The transcribed text. - logprobs: - type: array - optional: true - description: > - The log probabilities of the tokens in the transcription. Only returned with the models - `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array. - items: - type: object - properties: - token: - type: string - description: The token in the transcription. - logprob: - type: number - description: The log probability of the token. - bytes: - type: array - items: - type: number - description: The bytes of the token. - usage: - type: object - description: Token usage statistics for the request. - anyOf: - - $ref: '#/components/schemas/TranscriptTextUsageTokens' - title: Token Usage - - $ref: '#/components/schemas/TranscriptTextUsageDuration' - title: Duration Usage - discriminator: - propertyName: type - required: - - text - x-oaiMeta: - name: The transcription object (JSON) - group: audio - example: | - { - "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.", - "usage": { - "type": "tokens", - "input_tokens": 14, - "input_token_details": { - "text_tokens": 10, - "audio_tokens": 4 - }, - "output_tokens": 101, - "total_tokens": 115 - } - } - CreateTranscriptionResponseStreamEvent: - anyOf: - - $ref: '#/components/schemas/TranscriptTextSegmentEvent' - - $ref: '#/components/schemas/TranscriptTextDeltaEvent' - - $ref: '#/components/schemas/TranscriptTextDoneEvent' - discriminator: - propertyName: type - CreateTranscriptionResponseVerboseJson: - type: object - description: Represents a verbose json transcription response returned by model, based on the provided input. - properties: - language: - type: string - description: The language of the input audio. - duration: - type: number - description: The duration of the input audio. - text: - type: string - description: The transcribed text. - words: - type: array - description: Extracted words and their corresponding timestamps. - items: - $ref: '#/components/schemas/TranscriptionWord' - segments: - type: array - description: Segments of the transcribed text and their corresponding details. - items: - $ref: '#/components/schemas/TranscriptionSegment' - usage: - $ref: '#/components/schemas/TranscriptTextUsageDuration' - required: - - language - - duration - - text - x-oaiMeta: - name: The transcription object (Verbose JSON) - group: audio - example: | - { - "task": "transcribe", - "language": "english", - "duration": 8.470000267028809, - "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", - "segments": [ - { - "id": 0, - "seek": 0, - "start": 0.0, - "end": 3.319999933242798, - "text": " The beach was a popular spot on a hot summer day.", - "tokens": [ - 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530 - ], - "temperature": 0.0, - "avg_logprob": -0.2860786020755768, - "compression_ratio": 1.2363636493682861, - "no_speech_prob": 0.00985979475080967 - }, - ... - ], - "usage": { - "type": "duration", - "seconds": 9 - } - } - CreateTranslationRequest: - type: object - additionalProperties: false - properties: - file: - description: > - The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, - mpga, m4a, ogg, wav, or webm. - type: string - x-oaiTypeLabel: file - format: binary - x-oaiMeta: - exampleFilePath: speech.mp3 - model: - description: > - ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is - currently available. - example: whisper-1 - anyOf: - - type: string - - type: string - enum: - - whisper-1 - x-stainless-const: true - x-oaiTypeLabel: string - prompt: - description: > - 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 be in English. - type: string - response_format: - description: > - The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or - `vtt`. - type: string - enum: - - json - - text - - srt - - verbose_json - - vtt - default: json - temperature: - description: > - The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more - random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the - model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically - increase the temperature until certain thresholds are hit. - type: number - default: 0 - required: - - file - - model - CreateTranslationResponseJson: - type: object - properties: - text: - type: string - required: - - text - CreateTranslationResponseVerboseJson: - type: object - properties: - language: - type: string - description: The language of the output translation (always `english`). - duration: - type: number - description: The duration of the input audio. - text: - type: string - description: The translated text. - segments: - type: array - description: Segments of the translated text and their corresponding details. - items: - $ref: '#/components/schemas/TranscriptionSegment' - required: - - language - - duration - - text - CreateUploadRequest: - type: object - additionalProperties: false - properties: - filename: - description: | - The name of the file to upload. - type: string - purpose: - description: > - The intended purpose of the uploaded file. - - - See the [documentation on File - purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). - type: string - enum: - - assistants - - batch - - fine-tune - - vision - bytes: - description: | - The number of bytes in the file you are uploading. - type: integer - mime_type: - description: > - The MIME type of the file. - - - This must fall within the supported MIME types for your file purpose. See the supported MIME types - for assistants and vision. - type: string - expires_after: - $ref: '#/components/schemas/FileExpirationAfter' - required: - - filename - - purpose - - bytes - - mime_type - CreateVectorStoreFileBatchRequest: - type: object - additionalProperties: false - properties: - file_ids: - description: >- - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store - should use. Useful for tools like `file_search` that can access files. If `attributes` or - `chunking_strategy` are provided, they will be applied to all files in the batch. Mutually - exclusive with `files`. - type: array - minItems: 1 - maxItems: 500 - items: - type: string - files: - description: >- - A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. - Use this when you need to override metadata for specific files. The global `attributes` or - `chunking_strategy` will be ignored and must be specified for each file. Mutually exclusive with - `file_ids`. - type: array - minItems: 1 - maxItems: 500 - items: - $ref: '#/components/schemas/CreateVectorStoreFileRequest' - chunking_strategy: - $ref: '#/components/schemas/ChunkingStrategyRequestParam' - attributes: - $ref: '#/components/schemas/VectorStoreFileAttributes' - CreateVectorStoreFileRequest: - type: object - additionalProperties: false - properties: - file_id: - description: >- - A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should - use. Useful for tools like `file_search` that can access files. - type: string - chunking_strategy: - $ref: '#/components/schemas/ChunkingStrategyRequestParam' - attributes: - $ref: '#/components/schemas/VectorStoreFileAttributes' - required: - - file_id - CreateVectorStoreRequest: - type: object - additionalProperties: false - properties: - file_ids: - description: >- - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store - should use. Useful for tools like `file_search` that can access files. - type: array - maxItems: 500 - items: - type: string - name: - description: The name of the vector store. - type: string - description: - description: A description for the vector store. Can be used to describe the vector store's purpose. - type: string - expires_after: - $ref: '#/components/schemas/VectorStoreExpirationAfter' - chunking_strategy: - $ref: '#/components/schemas/ChunkingStrategyRequestParam' - metadata: - $ref: '#/components/schemas/Metadata' - CustomToolCall: - type: object - title: Custom tool call - description: | - A call to a custom tool created by the model. - properties: - type: - type: string - enum: - - custom_tool_call - x-stainless-const: true - description: | - The type of the custom tool call. Always `custom_tool_call`. - id: - type: string - description: | - The unique ID of the custom tool call in the OpenAI platform. - call_id: - type: string - description: | - An identifier used to map this custom tool call to a tool call output. - name: - type: string - description: | - The name of the custom tool being called. - input: - type: string - description: | - The input for the custom tool call generated by the model. - required: - - type - - call_id - - name - - input - CustomToolCallOutput: - type: object - title: Custom tool call output - description: | - The output of a custom tool call from your code, being sent back to the model. - properties: - type: - type: string - enum: - - custom_tool_call_output - x-stainless-const: true - description: | - The type of the custom tool call output. Always `custom_tool_call_output`. - id: - type: string - description: | - The unique ID of the custom tool call output in the OpenAI platform. - call_id: - type: string - description: | - The call ID, used to map this custom tool call output to a custom tool call. - output: - description: | - The output from the custom tool call generated by your code. - Can be a string or an list of output content. - anyOf: - - type: string - description: | - A string of the output of the custom tool call. - title: string output - - type: array - items: - $ref: '#/components/schemas/FunctionAndCustomToolCallOutput' - title: output content list - description: | - Text, image, or file output of the custom tool call. - required: - - type - - call_id - - output - CustomToolChatCompletions: - type: object - title: Custom tool - description: | - A custom tool that processes input using a specified format. - properties: - type: - type: string - enum: - - custom - description: The type of the custom tool. Always `custom`. - x-stainless-const: true - custom: - type: object - title: Custom tool properties - description: | - Properties of the custom tool. - properties: - name: - type: string - description: The name of the custom tool, used to identify it in tool calls. - description: - type: string - description: | - Optional description of the custom tool, used to provide more context. - format: - description: | - The input format for the custom tool. Default is unconstrained text. - anyOf: - - type: object - title: Text format - description: Unconstrained free-form text. - properties: - type: - type: string - enum: - - text - description: Unconstrained text format. Always `text`. - x-stainless-const: true - required: - - type - additionalProperties: false - - type: object - title: Grammar format - description: A grammar defined by the user. - properties: - type: - type: string - enum: - - grammar - description: Grammar format. Always `grammar`. - x-stainless-const: true - grammar: - type: object - title: Grammar format - description: Your chosen grammar. - properties: - definition: - type: string - description: The grammar definition. - syntax: - type: string - description: The syntax of the grammar definition. One of `lark` or `regex`. - enum: - - lark - - regex - required: - - definition - - syntax - required: - - type - - grammar - additionalProperties: false - discriminator: - propertyName: type - required: - - name - required: - - type - - custom - DeleteAssistantResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: - type: string - enum: - - assistant.deleted - x-stainless-const: true - required: - - id - - object - - deleted - DeleteCertificateResponse: - type: object - properties: - object: - description: The object type, must be `certificate.deleted`. - x-stainless-const: true - const: certificate.deleted - id: - type: string - description: The ID of the certificate that was deleted. - required: - - object - - id - DeleteFileResponse: - type: object - properties: - id: - type: string - object: - type: string - enum: - - file - x-stainless-const: true - deleted: - type: boolean - required: - - id - - object - - deleted - DeleteFineTuningCheckpointPermissionResponse: - type: object - properties: - id: - type: string - description: The ID of the fine-tuned model checkpoint permission that was deleted. - object: - type: string - description: The object type, which is always "checkpoint.permission". - enum: - - checkpoint.permission - x-stainless-const: true - deleted: - type: boolean - description: Whether the fine-tuned model checkpoint permission was successfully deleted. - required: - - id - - object - - deleted - DeleteMessageResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: - type: string - enum: - - thread.message.deleted - x-stainless-const: true - required: - - id - - object - - deleted - DeleteModelResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: - type: string - required: - - id - - object - - deleted - DeleteThreadResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: - type: string - enum: - - thread.deleted - x-stainless-const: true - required: - - id - - object - - deleted - DeleteVectorStoreFileResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: - type: string - enum: - - vector_store.file.deleted - x-stainless-const: true - required: - - id - - object - - deleted - DeleteVectorStoreResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: - type: string - enum: - - vector_store.deleted - x-stainless-const: true - required: - - id - - object - - deleted - DeletedConversation: - title: The deleted conversation object - allOf: - - $ref: '#/components/schemas/DeletedConversationResource' - x-oaiMeta: - name: The deleted conversation object - group: conversations - DeletedRoleAssignmentResource: - type: object - description: Confirmation payload returned after unassigning a role. - properties: - object: - type: string - description: Identifier for the deleted assignment, such as `group.role.deleted` or `user.role.deleted`. - deleted: - type: boolean - description: Whether the assignment was removed. - required: - - object - - deleted - x-oaiMeta: - name: Role assignment deletion confirmation - example: | - { - "object": "group.role.deleted", - "deleted": true - } - DoneEvent: - type: object - properties: - event: - type: string - enum: - - done - x-stainless-const: true - data: - type: string - enum: - - '[DONE]' - x-stainless-const: true - required: - - event - - data - description: Occurs when a stream ends. - x-oaiMeta: - dataDescription: '`data` is `[DONE]`' - Drag: - type: object - title: Drag - description: | - A drag action. - properties: - type: - type: string - enum: - - drag - default: drag - description: | - Specifies the event type. For a drag action, this property is - always set to `drag`. - x-stainless-const: true - path: - type: array - description: > - An array of coordinates representing the path of the drag action. Coordinates will appear as an - array - - of objects, eg - - ``` - - [ - { x: 100, y: 200 }, - { x: 200, y: 300 } - ] - - ``` - items: - $ref: '#/components/schemas/DragPoint' - required: - - type - - path - EasyInputMessage: - type: object - title: Input message - description: | - A message input to the model with a role indicating instruction following - hierarchy. Instructions given with the `developer` or `system` role take - precedence over instructions given with the `user` role. Messages with the - `assistant` role are presumed to have been generated by the model in previous - interactions. - properties: - role: - type: string - description: | - The role of the message input. One of `user`, `assistant`, `system`, or - `developer`. - enum: - - user - - assistant - - system - - developer - content: - description: | - Text, image, or audio input to the model, used to generate a response. - Can also contain previous assistant responses. - anyOf: - - type: string - title: Text input - description: | - A text input to the model. - - $ref: '#/components/schemas/InputMessageContentList' - type: - type: string - description: | - The type of the message input. Always `message`. - enum: - - message - x-stainless-const: true - required: - - role - - content - Embedding: - type: object - description: | - Represents an embedding vector returned by embedding endpoint. - properties: - index: - type: integer - description: The index of the embedding in the list of embeddings. - embedding: - type: array - description: > - The embedding vector, which is a list of floats. The length of vector depends on the model as - listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings). - items: - type: number - format: float - object: - type: string - description: The object type, which is always "embedding". - enum: - - embedding - x-stainless-const: true - required: - - index - - object - - embedding - x-oaiMeta: - name: The embedding object - example: | - { - "object": "embedding", - "embedding": [ - 0.0023064255, - -0.009327292, - .... (1536 floats total for ada-002) - -0.0028842222, - ], - "index": 0 - } - Error: - type: object - properties: - code: - anyOf: - - type: string - - type: 'null' - message: - type: string - param: - anyOf: - - type: string - - type: 'null' - type: - type: string - required: - - type - - message - - param - - code - ErrorEvent: - type: object - properties: - event: - type: string - enum: - - error - x-stainless-const: true - data: - $ref: '#/components/schemas/Error' - required: - - event - - data - description: >- - Occurs when an [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs. This - can happen due to an internal server error or a timeout. - x-oaiMeta: - dataDescription: '`data` is an [error](/docs/guides/error-codes#api-errors)' - ErrorResponse: - type: object - properties: - error: - $ref: '#/components/schemas/Error' - required: - - error - Eval: - type: object - title: Eval - description: | - An Eval object with a data source config and testing criteria. - An Eval represents a task to be done for your LLM integration. - Like: - - Improve the quality of my chatbot - - See how well my chatbot handles customer support - - Check if o4-mini is better at my usecase than gpt-4o - properties: - object: - type: string - enum: - - eval - default: eval - description: The object type. - x-stainless-const: true - id: - type: string - description: Unique identifier for the evaluation. - name: - type: string - description: The name of the evaluation. - example: Chatbot effectiveness Evaluation - data_source_config: - type: object - description: Configuration of data sources used in runs of the evaluation. - anyOf: - - $ref: '#/components/schemas/EvalCustomDataSourceConfig' - - $ref: '#/components/schemas/EvalLogsDataSourceConfig' - - $ref: '#/components/schemas/EvalStoredCompletionsDataSourceConfig' - discriminator: - propertyName: type - testing_criteria: - description: A list of testing criteria. - type: array - items: - anyOf: - - $ref: '#/components/schemas/EvalGraderLabelModel' - - $ref: '#/components/schemas/EvalGraderStringCheck' - - $ref: '#/components/schemas/EvalGraderTextSimilarity' - - $ref: '#/components/schemas/EvalGraderPython' - - $ref: '#/components/schemas/EvalGraderScoreModel' - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the eval was created. - metadata: - $ref: '#/components/schemas/Metadata' - required: - - id - - data_source_config - - object - - testing_criteria - - name - - created_at - - metadata - x-oaiMeta: - name: The eval object - group: evals - example: | - { - "object": "eval", - "id": "eval_67abd54d9b0081909a86353f6fb9317a", - "data_source_config": { - "type": "custom", - "item_schema": { - "type": "object", - "properties": { - "label": {"type": "string"}, - }, - "required": ["label"] - }, - "include_sample_schema": true - }, - "testing_criteria": [ - { - "name": "My string check grader", - "type": "string_check", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq", - } - ], - "name": "External Data Eval", - "created_at": 1739314509, - "metadata": { - "test": "synthetics", - } - } - EvalApiError: - type: object - title: EvalApiError - description: | - An object representing an error response from the Eval API. - properties: - code: - type: string - description: The error code. - message: - type: string - description: The error message. - required: - - code - - message - x-oaiMeta: - name: The API error object - group: evals - example: | - { - "code": "internal_error", - "message": "The eval run failed due to an internal error." - } - EvalCustomDataSourceConfig: - type: object - title: CustomDataSourceConfig - description: | - A CustomDataSourceConfig which specifies the schema of your `item` and optionally `sample` namespaces. - The response schema defines the shape of the data that will be: - - Used to define your testing criteria and - - What data is required when creating a run - properties: - type: - type: string - enum: - - custom - default: custom - description: The type of data source. Always `custom`. - x-stainless-const: true - schema: - type: object - description: | - The json schema for the run data source items. - Learn how to build JSON schemas [here](https://json-schema.org/). - additionalProperties: true - required: - - type - - schema - x-oaiMeta: - name: The eval custom data source config object - group: evals - example: | - { - "type": "custom", - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object", - "properties": { - "label": {"type": "string"}, - }, - "required": ["label"] - } - }, - "required": ["item"] - } - } - EvalGraderLabelModel: - type: object - title: LabelModelGrader - allOf: - - $ref: '#/components/schemas/GraderLabelModel' - EvalGraderPython: - type: object - title: EvalGraderPython - allOf: - - $ref: '#/components/schemas/GraderPython' - - type: object - properties: - pass_threshold: - type: number - description: The threshold for the score. - x-oaiMeta: - name: Eval Python Grader - group: graders - example: | - { - "type": "python", - "name": "Example python grader", - "image_tag": "2025-05-08", - "source": """ - def grade(sample: dict, item: dict) -> float: - \""" - Returns 1.0 if `output_text` equals `label`, otherwise 0.0. - \""" - output = sample.get("output_text") - label = item.get("label") - return 1.0 if output == label else 0.0 - """, - "pass_threshold": 0.8 - } - EvalGraderScoreModel: - type: object - title: EvalGraderScoreModel - allOf: - - $ref: '#/components/schemas/GraderScoreModel' - - type: object - properties: - pass_threshold: - type: number - description: The threshold for the score. - EvalGraderStringCheck: - type: object - title: StringCheckGrader - allOf: - - $ref: '#/components/schemas/GraderStringCheck' - EvalGraderTextSimilarity: - type: object - title: EvalGraderTextSimilarity - allOf: - - $ref: '#/components/schemas/GraderTextSimilarity' - - type: object - properties: - pass_threshold: - type: number - description: The threshold for the score. - required: - - pass_threshold - x-oaiMeta: - name: Text Similarity Grader - group: graders - example: | - { - "type": "text_similarity", - "name": "Example text similarity grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "pass_threshold": 0.8, - "evaluation_metric": "fuzzy_match" - } - EvalItem: - type: object - title: EvalItem - description: | - A message input to the model with a role indicating instruction following - hierarchy. Instructions given with the `developer` or `system` role take - precedence over instructions given with the `user` role. Messages with the - `assistant` role are presumed to have been generated by the model in previous - interactions. - properties: - role: - type: string - description: | - The role of the message input. One of `user`, `assistant`, `system`, or - `developer`. - enum: - - user - - assistant - - system - - developer - content: - description: | - Inputs to the model - can contain template strings. - anyOf: - - type: string - title: Text input - description: | - A text input to the model. - - $ref: '#/components/schemas/InputTextContent' - - type: object - title: Output text - description: | - A text output from the model. - properties: - type: - type: string - description: | - The type of the output text. Always `output_text`. - enum: - - output_text - x-stainless-const: true - text: - type: string - description: | - The text output from the model. - required: - - type - - text - - type: object - title: Input image - description: | - An image input to the model. - properties: - type: - type: string - description: | - The type of the image input. Always `input_image`. - enum: - - input_image - x-stainless-const: true - image_url: - type: string - description: | - The URL of the image input. - detail: - type: string - description: > - The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. - Defaults to `auto`. - required: - - type - - image_url - - $ref: '#/components/schemas/InputAudio' - - type: array - title: An array of Input text, Input image, and Input audio - description: > - A list of inputs, each of which may be either an input text, input image, or input audio - object. - type: - type: string - description: | - The type of the message input. Always `message`. - enum: - - message - x-stainless-const: true - required: - - role - - content - EvalJsonlFileContentSource: - type: object - title: EvalJsonlFileContentSource - properties: - type: - type: string - enum: - - file_content - default: file_content - description: The type of jsonl source. Always `file_content`. - x-stainless-const: true - content: - type: array - items: - type: object - properties: - item: - type: object - additionalProperties: true - sample: - type: object - additionalProperties: true - required: - - item - description: The content of the jsonl file. - required: - - type - - content - EvalJsonlFileIdSource: - type: object - title: EvalJsonlFileIdSource - properties: - type: - type: string - enum: - - file_id - default: file_id - description: The type of jsonl source. Always `file_id`. - x-stainless-const: true - id: - type: string - description: The identifier of the file. - required: - - type - - id - EvalList: - type: object - title: EvalList - description: | - An object representing a list of evals. - properties: - object: - type: string - enum: - - list - default: list - description: | - The type of this object. It is always set to "list". - x-stainless-const: true - data: - type: array - description: | - An array of eval objects. - items: - $ref: '#/components/schemas/Eval' - first_id: - type: string - description: The identifier of the first eval in the data array. - last_id: - type: string - description: The identifier of the last eval in the data array. - has_more: - type: boolean - description: Indicates whether there are more evals available. - required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: The eval list object - group: evals - example: | - { - "object": "list", - "data": [ - { - "object": "eval", - "id": "eval_67abd54d9b0081909a86353f6fb9317a", - "data_source_config": { - "type": "custom", - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object", - "properties": { - "input": { - "type": "string" - }, - "ground_truth": { - "type": "string" - } - }, - "required": [ - "input", - "ground_truth" - ] - } - }, - "required": [ - "item" - ] - } - }, - "testing_criteria": [ - { - "name": "String check", - "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", - "type": "string_check", - "input": "{{item.input}}", - "reference": "{{item.ground_truth}}", - "operation": "eq" - } - ], - "name": "External Data Eval", - "created_at": 1739314509, - "metadata": {}, - } - ], - "first_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "last_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "has_more": true - } - EvalLogsDataSourceConfig: - type: object - title: LogsDataSourceConfig - description: > - A LogsDataSourceConfig which specifies the metadata property of your logs query. - - This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. - - The schema returned by this data source config is used to defined what variables are available in your - evals. - - `item` and `sample` are both defined when using this data source config. - properties: - type: - type: string - enum: - - logs - default: logs - description: The type of data source. Always `logs`. - x-stainless-const: true - metadata: - $ref: '#/components/schemas/Metadata' - schema: - type: object - description: | - The json schema for the run data source items. - Learn how to build JSON schemas [here](https://json-schema.org/). - additionalProperties: true - required: - - type - - schema - x-oaiMeta: - name: The logs data source object for evals - group: evals - example: | - { - "type": "logs", - "metadata": { - "language": "english" - }, - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object" - }, - "sample": { - "type": "object" - } - }, - "required": [ - "item", - "sample" - } - } - EvalResponsesSource: - type: object - title: EvalResponsesSource - description: | - A EvalResponsesSource object describing a run data source configuration. - properties: - type: - type: string - enum: - - responses - description: The type of run data source. Always `responses`. - metadata: - anyOf: - - type: object - description: Metadata filter for the responses. This is a query parameter used to select responses. - - type: 'null' - model: - anyOf: - - type: string - description: >- - The name of the model to find responses for. This is a query parameter used to select - responses. - - type: 'null' - instructions_search: - anyOf: - - type: string - description: >- - Optional string to search the 'instructions' field. This is a query parameter used to select - responses. - - type: 'null' - created_after: - anyOf: - - type: integer - minimum: 0 - description: >- - Only include items created after this timestamp (inclusive). This is a query parameter used to - select responses. - - type: 'null' - created_before: - anyOf: - - type: integer - minimum: 0 - description: >- - Only include items created before this timestamp (inclusive). This is a query parameter used - to select responses. - - type: 'null' - reasoning_effort: - anyOf: - - $ref: '#/components/schemas/ReasoningEffort' - description: Optional reasoning effort parameter. This is a query parameter used to select responses. - - type: 'null' - temperature: - anyOf: - - type: number - description: Sampling temperature. This is a query parameter used to select responses. - - type: 'null' - top_p: - anyOf: - - type: number - description: Nucleus sampling parameter. This is a query parameter used to select responses. - - type: 'null' - users: - anyOf: - - type: array - items: - type: string - description: List of user identifiers. This is a query parameter used to select responses. - - type: 'null' - tools: - anyOf: - - type: array - items: - type: string - description: List of tool names. This is a query parameter used to select responses. - - type: 'null' - required: - - type - x-oaiMeta: - name: The run data source object used to configure an individual run - group: eval runs - example: | - { - "type": "responses", - "model": "gpt-4o-mini-2024-07-18", - "temperature": 0.7, - "top_p": 1.0, - "users": ["user1", "user2"], - "tools": ["tool1", "tool2"], - "instructions_search": "You are a coding assistant" - } - EvalRun: - type: object - title: EvalRun - description: | - A schema representing an evaluation run. - properties: - object: - type: string - enum: - - eval.run - default: eval.run - description: The type of the object. Always "eval.run". - x-stainless-const: true - id: - type: string - description: Unique identifier for the evaluation run. - eval_id: - type: string - description: The identifier of the associated evaluation. - status: - type: string - description: The status of the evaluation run. - model: - type: string - description: The model that is evaluated, if applicable. - name: - type: string - description: The name of the evaluation run. - created_at: - type: integer - description: Unix timestamp (in seconds) when the evaluation run was created. - report_url: - type: string - description: The URL to the rendered evaluation run report on the UI dashboard. - result_counts: - type: object - description: Counters summarizing the outcomes of the evaluation run. - properties: - total: - type: integer - description: Total number of executed output items. - errored: - type: integer - description: Number of output items that resulted in an error. - failed: - type: integer - description: Number of output items that failed to pass the evaluation. - passed: - type: integer - description: Number of output items that passed the evaluation. - required: - - total - - errored - - failed - - passed - per_model_usage: - type: array - description: Usage statistics for each model during the evaluation run. - items: - type: object - properties: - model_name: - type: string - description: The name of the model. - x-stainless-naming: - python: - property_name: run_model_name - invocation_count: - type: integer - description: The number of invocations. - prompt_tokens: - type: integer - description: The number of prompt tokens used. - completion_tokens: - type: integer - description: The number of completion tokens generated. - total_tokens: - type: integer - description: The total number of tokens used. - cached_tokens: - type: integer - description: The number of tokens retrieved from cache. - required: - - model_name - - invocation_count - - prompt_tokens - - completion_tokens - - total_tokens - - cached_tokens - per_testing_criteria_results: - type: array - description: Results per testing criteria applied during the evaluation run. - items: - type: object - properties: - testing_criteria: - type: string - description: A description of the testing criteria. - passed: - type: integer - description: Number of tests passed for this criteria. - failed: - type: integer - description: Number of tests failed for this criteria. - required: - - testing_criteria - - passed - - failed - data_source: - type: object - description: Information about the run's data source. - anyOf: - - $ref: '#/components/schemas/CreateEvalJsonlRunDataSource' - - $ref: '#/components/schemas/CreateEvalCompletionsRunDataSource' - - $ref: '#/components/schemas/CreateEvalResponsesRunDataSource' - discriminator: - propertyName: type - metadata: - $ref: '#/components/schemas/Metadata' - error: - $ref: '#/components/schemas/EvalApiError' - required: - - object - - id - - eval_id - - status - - model - - name - - created_at - - report_url - - result_counts - - per_model_usage - - per_testing_criteria_results - - data_source - - metadata - - error - x-oaiMeta: - name: The eval run object - group: evals - example: | - { - "object": "eval.run", - "id": "evalrun_67e57965b480819094274e3a32235e4c", - "eval_id": "eval_67e579652b548190aaa83ada4b125f47", - "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47?run_id=evalrun_67e57965b480819094274e3a32235e4c", - "status": "queued", - "model": "gpt-4o-mini", - "name": "gpt-4o-mini", - "created_at": 1743092069, - "result_counts": { - "total": 0, - "errored": 0, - "failed": 0, - "passed": 0 - }, - "per_model_usage": null, - "per_testing_criteria_results": null, - "data_source": { - "type": "completions", - "source": { - "type": "file_content", - "content": [ - { - "item": { - "input": "Tech Company Launches Advanced Artificial Intelligence Platform", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "International Summit Addresses Climate Change Strategies", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Major Retailer Reports Record-Breaking Holiday Sales", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "National Team Qualifies for World Championship Finals", - "ground_truth": "Sports" - } - }, - { - "item": { - "input": "Stock Markets Rally After Positive Economic Data Released", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "Global Manufacturer Announces Merger with Competitor", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "Breakthrough in Renewable Energy Technology Unveiled", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "World Leaders Sign Historic Climate Agreement", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Professional Athlete Sets New Record in Championship Event", - "ground_truth": "Sports" - } - }, - { - "item": { - "input": "Financial Institutions Adapt to New Regulatory Requirements", - "ground_truth": "Business" - } - }, - { - "item": { - "input": "Tech Conference Showcases Advances in Artificial Intelligence", - "ground_truth": "Technology" - } - }, - { - "item": { - "input": "Global Markets Respond to Oil Price Fluctuations", - "ground_truth": "Markets" - } - }, - { - "item": { - "input": "International Cooperation Strengthened Through New Treaty", - "ground_truth": "World" - } - }, - { - "item": { - "input": "Sports League Announces Revised Schedule for Upcoming Season", - "ground_truth": "Sports" - } - } - ] - }, - "input_messages": { - "type": "template", - "template": [ - { - "type": "message", - "role": "developer", - "content": { - "type": "input_text", - "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "{{item.input}}" - } - } - ] - }, - "model": "gpt-4o-mini", - "sampling_params": { - "seed": 42, - "temperature": 1.0, - "top_p": 1.0, - "max_completions_tokens": 2048 - } - }, - "error": null, - "metadata": {} - } - EvalRunList: - type: object - title: EvalRunList - description: | - An object representing a list of runs for an evaluation. - properties: - object: - type: string - enum: - - list - default: list - description: | - The type of this object. It is always set to "list". - x-stainless-const: true - data: - type: array - description: | - An array of eval run objects. - items: - $ref: '#/components/schemas/EvalRun' - first_id: - type: string - description: The identifier of the first eval run in the data array. - last_id: - type: string - description: The identifier of the last eval run in the data array. - has_more: - type: boolean - description: Indicates whether there are more evals available. - required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: The eval run list object - group: evals - example: | - { - "object": "list", - "data": [ - { - "object": "eval.run", - "id": "evalrun_67b7fbdad46c819092f6fe7a14189620", - "eval_id": "eval_67b7fa9a81a88190ab4aa417e397ea21", - "report_url": "https://platform.openai.com/evaluations/eval_67b7fa9a81a88190ab4aa417e397ea21?run_id=evalrun_67b7fbdad46c819092f6fe7a14189620", - "status": "completed", - "model": "o3-mini", - "name": "Academic Assistant", - "created_at": 1740110812, - "result_counts": { - "total": 171, - "errored": 0, - "failed": 80, - "passed": 91 - }, - "per_model_usage": null, - "per_testing_criteria_results": [ - { - "testing_criteria": "String check grader", - "passed": 91, - "failed": 80 - } - ], - "run_data_source": { - "type": "completions", - "template_messages": [ - { - "type": "message", - "role": "system", - "content": { - "type": "input_text", - "text": "You are a helpful assistant." - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "Hello, can you help me with my homework?" - } - } - ], - "datasource_reference": null, - "model": "o3-mini", - "max_completion_tokens": null, - "seed": null, - "temperature": null, - "top_p": null - }, - "error": null, - "metadata": {"test": "synthetics"} - } - ], - "first_id": "evalrun_67abd54d60ec8190832b46859da808f7", - "last_id": "evalrun_67abd54d60ec8190832b46859da808f7", - "has_more": false - } - EvalRunOutputItem: - type: object - title: EvalRunOutputItem - description: | - A schema representing an evaluation run output item. - properties: - object: - type: string - enum: - - eval.run.output_item - default: eval.run.output_item - description: The type of the object. Always "eval.run.output_item". - x-stainless-const: true - id: - type: string - description: Unique identifier for the evaluation run output item. - run_id: - type: string - description: The identifier of the evaluation run associated with this output item. - eval_id: - type: string - description: The identifier of the evaluation group. - created_at: - type: integer - description: Unix timestamp (in seconds) when the evaluation run was created. - status: - type: string - description: The status of the evaluation run. - datasource_item_id: - type: integer - description: The identifier for the data source item. - datasource_item: - type: object - description: Details of the input data source item. - additionalProperties: true - results: - type: array - description: A list of grader results for this output item. - items: - $ref: '#/components/schemas/EvalRunOutputItemResult' - sample: - type: object - description: A sample containing the input and output of the evaluation run. - properties: - input: - type: array - description: An array of input messages. - items: - type: object - description: An input message. - properties: - role: - type: string - description: The role of the message sender (e.g., system, user, developer). - content: - type: string - description: The content of the message. - required: - - role - - content - output: - type: array - description: An array of output messages. - items: - type: object - properties: - role: - type: string - description: The role of the message (e.g. "system", "assistant", "user"). - content: - type: string - description: The content of the message. - finish_reason: - type: string - description: The reason why the sample generation was finished. - model: - type: string - description: The model used for generating the sample. - usage: - type: object - description: Token usage details for the sample. - properties: - total_tokens: - type: integer - description: The total number of tokens used. - completion_tokens: - type: integer - description: The number of completion tokens generated. - prompt_tokens: - type: integer - description: The number of prompt tokens used. - cached_tokens: - type: integer - description: The number of tokens retrieved from cache. - required: - - total_tokens - - completion_tokens - - prompt_tokens - - cached_tokens - error: - $ref: '#/components/schemas/EvalApiError' - temperature: - type: number - description: The sampling temperature used. - max_completion_tokens: - type: integer - description: The maximum number of tokens allowed for completion. - top_p: - type: number - description: The top_p value used for sampling. - seed: - type: integer - description: The seed used for generating the sample. - required: - - input - - output - - finish_reason - - model - - usage - - error - - temperature - - max_completion_tokens - - top_p - - seed - required: - - object - - id - - run_id - - eval_id - - created_at - - status - - datasource_item_id - - datasource_item - - results - - sample - x-oaiMeta: - name: The eval run output item object - group: evals - example: | - { - "object": "eval.run.output_item", - "id": "outputitem_67abd55eb6548190bb580745d5644a33", - "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", - "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "created_at": 1739314509, - "status": "pass", - "datasource_item_id": 137, - "datasource_item": { - "teacher": "To grade essays, I only check for style, content, and grammar.", - "student": "I am a student who is trying to write the best essay." - }, - "results": [ - { - "name": "String Check Grader", - "type": "string-check-grader", - "score": 1.0, - "passed": true, - } - ], - "sample": { - "input": [ - { - "role": "system", - "content": "You are an evaluator bot..." - }, - { - "role": "user", - "content": "You are assessing..." - } - ], - "output": [ - { - "role": "assistant", - "content": "The rubric is not clear nor concise." - } - ], - "finish_reason": "stop", - "model": "gpt-4o-2024-08-06", - "usage": { - "total_tokens": 521, - "completion_tokens": 2, - "prompt_tokens": 519, - "cached_tokens": 0 - }, - "error": null, - "temperature": 1.0, - "max_completion_tokens": 2048, - "top_p": 1.0, - "seed": 42 - } - } - EvalRunOutputItemList: - type: object - title: EvalRunOutputItemList - description: | - An object representing a list of output items for an evaluation run. - properties: - object: - type: string - enum: - - list - default: list - description: | - The type of this object. It is always set to "list". - x-stainless-const: true - data: - type: array - description: | - An array of eval run output item objects. - items: - $ref: '#/components/schemas/EvalRunOutputItem' - first_id: - type: string - description: The identifier of the first eval run output item in the data array. - last_id: - type: string - description: The identifier of the last eval run output item in the data array. - has_more: - type: boolean - description: Indicates whether there are more eval run output items available. - required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: The eval run output item list object - group: evals - example: | - { - "object": "list", - "data": [ - { - "object": "eval.run.output_item", - "id": "outputitem_67abd55eb6548190bb580745d5644a33", - "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", - "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", - "created_at": 1739314509, - "status": "pass", - "datasource_item_id": 137, - "datasource_item": { - "teacher": "To grade essays, I only check for style, content, and grammar.", - "student": "I am a student who is trying to write the best essay." - }, - "results": [ - { - "name": "String Check Grader", - "type": "string-check-grader", - "score": 1.0, - "passed": true, - } - ], - "sample": { - "input": [ - { - "role": "system", - "content": "You are an evaluator bot..." - }, - { - "role": "user", - "content": "You are assessing..." - } - ], - "output": [ - { - "role": "assistant", - "content": "The rubric is not clear nor concise." - } - ], - "finish_reason": "stop", - "model": "gpt-4o-2024-08-06", - "usage": { - "total_tokens": 521, - "completion_tokens": 2, - "prompt_tokens": 519, - "cached_tokens": 0 - }, - "error": null, - "temperature": 1.0, - "max_completion_tokens": 2048, - "top_p": 1.0, - "seed": 42 - } - }, - ], - "first_id": "outputitem_67abd55eb6548190bb580745d5644a33", - "last_id": "outputitem_67abd55eb6548190bb580745d5644a33", - "has_more": false - } - EvalRunOutputItemResult: - type: object - title: EvalRunOutputItemResult - description: | - A single grader result for an evaluation run output item. - properties: - name: - type: string - description: The name of the grader. - type: - type: string - description: The grader type (for example, "string-check-grader"). - score: - type: number - description: The numeric score produced by the grader. - passed: - type: boolean - description: Whether the grader considered the output a pass. - sample: - anyOf: - - type: object - additionalProperties: true - - type: 'null' - description: Optional sample or intermediate data produced by the grader. - additionalProperties: true - required: - - name - - score - - passed - EvalStoredCompletionsDataSourceConfig: - type: object - title: StoredCompletionsDataSourceConfig - description: | - Deprecated in favor of LogsDataSourceConfig. - properties: - type: - type: string - enum: - - stored_completions - default: stored_completions - description: The type of data source. Always `stored_completions`. - x-stainless-const: true - metadata: - $ref: '#/components/schemas/Metadata' - schema: - type: object - description: | - The json schema for the run data source items. - Learn how to build JSON schemas [here](https://json-schema.org/). - additionalProperties: true - required: - - type - - schema - deprecated: true - x-oaiMeta: - name: The stored completions data source object for evals - group: evals - example: | - { - "type": "stored_completions", - "metadata": { - "language": "english" - }, - "schema": { - "type": "object", - "properties": { - "item": { - "type": "object" - }, - "sample": { - "type": "object" - } - }, - "required": [ - "item", - "sample" - } - } - EvalStoredCompletionsSource: - type: object - title: StoredCompletionsRunDataSource - description: | - A StoredCompletionsRunDataSource configuration describing a set of filters - properties: - type: - type: string - enum: - - stored_completions - default: stored_completions - description: The type of source. Always `stored_completions`. - x-stainless-const: true - metadata: - $ref: '#/components/schemas/Metadata' - model: - anyOf: - - type: string - description: An optional model to filter by (e.g., 'gpt-4o'). - - type: 'null' - created_after: - anyOf: - - type: integer - description: An optional Unix timestamp to filter items created after this time. - - type: 'null' - created_before: - anyOf: - - type: integer - description: An optional Unix timestamp to filter items created before this time. - - type: 'null' - limit: - anyOf: - - type: integer - description: An optional maximum number of items to return. - - type: 'null' - required: - - type - x-oaiMeta: - name: The stored completions data source object used to configure an individual run - group: eval runs - example: | - { - "type": "stored_completions", - "model": "gpt-4o", - "created_after": 1668124800, - "created_before": 1668124900, - "limit": 100, - "metadata": {} - } - FileExpirationAfter: - type: object - title: File expiration policy - description: >- - The expiration policy for a file. By default, files with `purpose=batch` expire after 30 days and all - other files are persisted until they are manually deleted. - properties: - anchor: - description: 'Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.' - type: string - enum: - - created_at - x-stainless-const: true - seconds: - description: >- - The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 - hour) and 2592000 (30 days). - type: integer - minimum: 3600 - maximum: 2592000 - required: - - anchor - - seconds - FilePath: - type: object - title: File path - description: | - A path to a file. - properties: - type: - type: string - description: | - The type of the file path. Always `file_path`. - enum: - - file_path - x-stainless-const: true - file_id: - type: string - description: | - The ID of the file. - index: - type: integer - description: | - The index of the file in the list of files. - required: - - type - - file_id - - index - FileSearchRanker: - type: string - description: The ranker to use for the file search. If not specified will use the `auto` ranker. - enum: - - auto - - default_2024_08_21 - FileSearchRankingOptions: - title: File search tool call ranking options - type: object - description: > - The ranking options for the file search. If not specified, the file search tool will use the `auto` - ranker and a score_threshold of 0. - - - See the [file search tool - documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - for more information. - properties: - ranker: - $ref: '#/components/schemas/FileSearchRanker' - score_threshold: - type: number - description: >- - The score threshold for the file search. All values must be a floating point number between 0 and - 1. - minimum: 0 - maximum: 1 - required: - - score_threshold - FileSearchToolCall: - type: object - title: File search tool call - description: | - The results of a file search tool call. See the - [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information. - properties: - id: - type: string - description: | - The unique ID of the file search tool call. - type: - type: string - enum: - - file_search_call - description: | - The type of the file search tool call. Always `file_search_call`. - x-stainless-const: true - status: - type: string - description: | - The status of the file search tool call. One of `in_progress`, - `searching`, `incomplete` or `failed`, - enum: - - in_progress - - searching - - completed - - incomplete - - failed - queries: - type: array - items: - type: string - description: | - The queries used to search for files. - results: - anyOf: - - type: array - description: | - The results of the file search tool call. - items: - type: object - properties: - file_id: - type: string - description: | - The unique ID of the file. - text: - type: string - description: | - The text that was retrieved from the file. - filename: - type: string - description: | - The name of the file. - attributes: - $ref: '#/components/schemas/VectorStoreFileAttributes' - score: - type: number - format: float - description: | - The relevance score of the file - a value between 0 and 1. - - type: 'null' - required: - - id - - type - - status - - queries - FineTuneChatCompletionRequestAssistantMessage: - allOf: - - type: object - title: Assistant message - deprecated: false - properties: - weight: - type: integer - enum: - - 0 - - 1 - description: Controls whether the assistant message is trained against (0 or 1) - - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' - required: - - role - FineTuneChatRequestInput: - type: object - description: | - The per-line training example of a fine-tuning input file for chat models using the supervised method. - Input messages may contain text or image content only. Audio and file input messages - are not currently supported for fine-tuning. - properties: - messages: - type: array - minItems: 1 - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' - - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - - $ref: '#/components/schemas/FineTuneChatCompletionRequestAssistantMessage' - - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' - tools: - type: array - description: A list of tools the model may generate JSON inputs for. - items: - $ref: '#/components/schemas/ChatCompletionTool' - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - functions: - deprecated: true - description: A list of functions the model may generate JSON inputs for. - type: array - minItems: 1 - maxItems: 128 - items: - $ref: '#/components/schemas/ChatCompletionFunctions' - x-oaiMeta: - name: Training format for chat models using the supervised method - example: | - { - "messages": [ - { "role": "user", "content": "What is the weather in San Francisco?" }, - { - "role": "assistant", - "tool_calls": [ - { - "id": "call_id", - "type": "function", - "function": { - "name": "get_current_weather", - "arguments": "{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}" - } - } - ] - } - ], - "parallel_tool_calls": false, - "tools": [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and country, eg. San Francisco, USA" - }, - "format": { "type": "string", "enum": ["celsius", "fahrenheit"] } - }, - "required": ["location", "format"] - } - } - } - ] - } - FineTuneDPOHyperparameters: - type: object - description: The hyperparameters used for the DPO fine-tuning job. - properties: - beta: - description: > - The beta value for the DPO method. A higher beta value will increase the weight of the penalty - between the policy and reference model. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: number - minimum: 0 - maximum: 2 - exclusiveMinimum: true - batch_size: - description: > - Number of examples in each batch. A larger batch size means that model parameters are updated less - frequently, but with lower variance. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 256 - learning_rate_multiplier: - description: | - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: number - minimum: 0 - exclusiveMinimum: true - n_epochs: - description: > - The number of epochs to train the model for. An epoch refers to one full cycle through the - training dataset. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 50 - FineTuneDPOMethod: - type: object - description: Configuration for the DPO fine-tuning method. - properties: - hyperparameters: - $ref: '#/components/schemas/FineTuneDPOHyperparameters' - FineTuneMethod: - type: object - description: The method used for fine-tuning. - properties: - type: - type: string - description: The type of method. Is either `supervised`, `dpo`, or `reinforcement`. - enum: - - supervised - - dpo - - reinforcement - supervised: - $ref: '#/components/schemas/FineTuneSupervisedMethod' - dpo: - $ref: '#/components/schemas/FineTuneDPOMethod' - reinforcement: - $ref: '#/components/schemas/FineTuneReinforcementMethod' - required: - - type - FineTunePreferenceRequestInput: - type: object - description: | - The per-line training example of a fine-tuning input file for chat models using the dpo method. - Input messages may contain text or image content only. Audio and file input messages - are not currently supported for fine-tuning. - properties: - input: - type: object - properties: - messages: - type: array - minItems: 1 - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' - - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - - $ref: '#/components/schemas/FineTuneChatCompletionRequestAssistantMessage' - - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' - tools: - type: array - description: A list of tools the model may generate JSON inputs for. - items: - $ref: '#/components/schemas/ChatCompletionTool' - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - preferred_output: - type: array - description: The preferred completion message for the output. - maxItems: 1 - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' - non_preferred_output: - type: array - description: The non-preferred completion message for the output. - maxItems: 1 - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' - x-oaiMeta: - name: Training format for chat models using the preference method - example: | - { - "input": { - "messages": [ - { "role": "user", "content": "What is the weather in San Francisco?" } - ] - }, - "preferred_output": [ - { - "role": "assistant", - "content": "The weather in San Francisco is 70 degrees Fahrenheit." - } - ], - "non_preferred_output": [ - { - "role": "assistant", - "content": "The weather in San Francisco is 21 degrees Celsius." - } - ] - } - FineTuneReinforcementHyperparameters: - type: object - description: The hyperparameters used for the reinforcement fine-tuning job. - properties: - batch_size: - description: > - Number of examples in each batch. A larger batch size means that model parameters are updated less - frequently, but with lower variance. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 256 - learning_rate_multiplier: - description: | - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: number - minimum: 0 - exclusiveMinimum: true - n_epochs: - description: > - The number of epochs to train the model for. An epoch refers to one full cycle through the - training dataset. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 50 - reasoning_effort: - description: | - Level of reasoning effort. - type: string - enum: - - default - - low - - medium - - high - default: default - compute_multiplier: - description: | - Multiplier on amount of compute used for exploring search space during training. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: number - minimum: 0.00001 - maximum: 10 - exclusiveMinimum: true - eval_interval: - description: | - The number of training steps between evaluation runs. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - eval_samples: - description: | - Number of evaluation samples to generate per training step. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - FineTuneReinforcementMethod: - type: object - description: Configuration for the reinforcement fine-tuning method. - properties: - grader: - type: object - description: The grader used for the fine-tuning job. - anyOf: - - $ref: '#/components/schemas/GraderStringCheck' - - $ref: '#/components/schemas/GraderTextSimilarity' - - $ref: '#/components/schemas/GraderPython' - - $ref: '#/components/schemas/GraderScoreModel' - - $ref: '#/components/schemas/GraderMulti' - hyperparameters: - $ref: '#/components/schemas/FineTuneReinforcementHyperparameters' - required: - - grader - FineTuneReinforcementRequestInput: - type: object - unevaluatedProperties: true - description: > - Per-line training example for reinforcement fine-tuning. Note that `messages` and `tools` are the only - reserved keywords. - - Any other arbitrary key-value data can be included on training datapoints and will be available to - reference during grading under the `{{ item.XXX }}` template variable. - - Input messages may contain text or image content only. Audio and file input messages - - are not currently supported for fine-tuning. - required: - - messages - properties: - messages: - type: array - minItems: 1 - items: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestDeveloperMessage' - - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' - - $ref: '#/components/schemas/FineTuneChatCompletionRequestAssistantMessage' - - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' - tools: - type: array - description: A list of tools the model may generate JSON inputs for. - items: - $ref: '#/components/schemas/ChatCompletionTool' - x-oaiMeta: - name: Training format for reasoning models using the reinforcement method - example: | - { - "messages": [ - { - "role": "user", - "content": "Your task is to take a chemical in SMILES format and predict the number of hydrobond bond donors and acceptors according to Lipinkski's rule. CCN(CC)CCC(=O)c1sc(N)nc1C" - }, - ], - # Any other JSON data can be inserted into an example and referenced during RFT grading - "reference_answer": { - "donor_bond_counts": 5, - "acceptor_bond_counts": 7 - } - } - FineTuneSupervisedHyperparameters: - type: object - description: The hyperparameters used for the fine-tuning job. - properties: - batch_size: - description: > - Number of examples in each batch. A larger batch size means that model parameters are updated less - frequently, but with lower variance. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 256 - learning_rate_multiplier: - description: | - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: number - minimum: 0 - exclusiveMinimum: true - n_epochs: - description: > - The number of epochs to train the model for. An epoch refers to one full cycle through the - training dataset. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 50 - FineTuneSupervisedMethod: - type: object - description: Configuration for the supervised fine-tuning method. - properties: - hyperparameters: - $ref: '#/components/schemas/FineTuneSupervisedHyperparameters' - FineTuningCheckpointPermission: - type: object - title: FineTuningCheckpointPermission - description: | - The `checkpoint.permission` object represents a permission for a fine-tuned model checkpoint. - properties: - id: - type: string - description: The permission identifier, which can be referenced in the API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the permission was created. - project_id: - type: string - description: The project identifier that the permission is for. - object: - type: string - description: The object type, which is always "checkpoint.permission". - enum: - - checkpoint.permission - x-stainless-const: true - required: - - created_at - - id - - object - - project_id - x-oaiMeta: - name: The fine-tuned model checkpoint permission object - example: | - { - "object": "checkpoint.permission", - "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", - "created_at": 1712211699, - "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" - } - FineTuningIntegration: - type: object - title: Fine-Tuning Job Integration - required: - - type - - wandb - properties: - type: - type: string - description: The type of the integration being enabled for the fine-tuning job - enum: - - wandb - x-stainless-const: true - wandb: - type: object - description: | - The settings for your integration with Weights and Biases. This payload specifies the project that - metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags - to your run, and set a default entity (team, username, etc) to be associated with your run. - required: - - project - properties: - project: - description: | - The name of the project that the new run will be created under. - type: string - example: my-wandb-project - name: - anyOf: - - description: | - A display name to set for the run. If not set, we will use the Job ID as the name. - type: string - - type: 'null' - entity: - anyOf: - - description: > - The entity to use for the run. This allows you to set the team or username of the WandB - user that you would - - like associated with the run. If not set, the default entity for the registered WandB API - key is used. - type: string - - type: 'null' - tags: - description: > - A list of tags to be attached to the newly created run. These tags are passed through directly - to WandB. Some - - default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", - "openai/{ftjob-abcdef}". - type: array - items: - type: string - example: custom-tag - FineTuningJob: - type: object - title: FineTuningJob - description: | - The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. - properties: - id: - type: string - description: The object identifier, which can be referenced in the API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the fine-tuning job was created. - error: - anyOf: - - type: object - description: >- - For fine-tuning jobs that have `failed`, this will contain more information on the cause of - the failure. - properties: - code: - type: string - description: A machine-readable error code. - message: - type: string - description: A human-readable error message. - param: - anyOf: - - type: string - description: >- - The parameter that was invalid, usually `training_file` or `validation_file`. This - field will be null if the failure was not parameter-specific. - - type: 'null' - required: - - code - - message - - param - - type: 'null' - fine_tuned_model: - anyOf: - - type: string - description: >- - The name of the fine-tuned model that is being created. The value will be null if the - fine-tuning job is still running. - - type: 'null' - finished_at: - anyOf: - - type: integer - description: >- - The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be - null if the fine-tuning job is still running. - - type: 'null' - hyperparameters: - type: object - description: >- - The hyperparameters used for the fine-tuning job. This value will only be returned when running - `supervised` jobs. - properties: - batch_size: - anyOf: - - description: | - Number of examples in each batch. A larger batch size means that model parameters - are updated less frequently, but with lower variance. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - - type: integer - minimum: 1 - maximum: 256 - title: Auto - - type: 'null' - title: Manual - learning_rate_multiplier: - description: | - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid - overfitting. - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - title: Auto - - type: number - minimum: 0 - exclusiveMinimum: true - n_epochs: - description: | - The number of epochs to train the model for. An epoch refers to one full cycle - through the training dataset. - default: auto - anyOf: - - type: string - enum: - - auto - x-stainless-const: true - title: Auto - - type: integer - minimum: 1 - maximum: 50 - model: - type: string - description: The base model that is being fine-tuned. - object: - type: string - description: The object type, which is always "fine_tuning.job". - enum: - - fine_tuning.job - x-stainless-const: true - organization_id: - type: string - description: The organization that owns the fine-tuning job. - result_files: - type: array - description: >- - The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the - [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). - items: - type: string - example: file-abc123 - status: - type: string - description: >- - The current status of the fine-tuning job, which can be either `validating_files`, `queued`, - `running`, `succeeded`, `failed`, or `cancelled`. - enum: - - validating_files - - queued - - running - - succeeded - - failed - - cancelled - trained_tokens: - anyOf: - - type: integer - description: >- - The total number of billable tokens processed by this fine-tuning job. The value will be null - if the fine-tuning job is still running. - - type: 'null' - training_file: - type: string - description: >- - The file ID used for training. You can retrieve the training data with the [Files - API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). - validation_file: - anyOf: - - type: string - description: >- - The file ID used for validation. You can retrieve the validation results with the [Files - API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). - - type: 'null' - integrations: - anyOf: - - type: array - description: A list of integrations to enable for this fine-tuning job. - maxItems: 5 - items: - anyOf: - - $ref: '#/components/schemas/FineTuningIntegration' - discriminator: - propertyName: type - - type: 'null' - seed: - type: integer - description: The seed used for the fine-tuning job. - estimated_finish: - anyOf: - - type: integer - description: >- - The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value - will be null if the fine-tuning job is not running. - - type: 'null' - method: - $ref: '#/components/schemas/FineTuneMethod' - metadata: - $ref: '#/components/schemas/Metadata' - required: - - created_at - - error - - finished_at - - fine_tuned_model - - hyperparameters - - id - - model - - object - - organization_id - - result_files - - status - - trained_tokens - - training_file - - validation_file - - seed - x-oaiMeta: - name: The fine-tuning job object - example: | - { - "object": "fine_tuning.job", - "id": "ftjob-abc123", - "model": "davinci-002", - "created_at": 1692661014, - "finished_at": 1692661190, - "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", - "organization_id": "org-123", - "result_files": [ - "file-abc123" - ], - "status": "succeeded", - "validation_file": null, - "training_file": "file-abc123", - "hyperparameters": { - "n_epochs": 4, - "batch_size": 1, - "learning_rate_multiplier": 1.0 - }, - "trained_tokens": 5768, - "integrations": [], - "seed": 0, - "estimated_finish": 0, - "method": { - "type": "supervised", - "supervised": { - "hyperparameters": { - "n_epochs": 4, - "batch_size": 1, - "learning_rate_multiplier": 1.0 - } - } - }, - "metadata": { - "key": "value" - } - } - FineTuningJobCheckpoint: - type: object - title: FineTuningJobCheckpoint - description: > - The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is - ready to use. - properties: - id: - type: string - description: The checkpoint identifier, which can be referenced in the API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the checkpoint was created. - fine_tuned_model_checkpoint: - type: string - description: The name of the fine-tuned checkpoint model that is created. - step_number: - type: integer - description: The step number that the checkpoint was created at. - metrics: - type: object - description: Metrics at the step number during the fine-tuning job. - properties: - step: - type: number - train_loss: - type: number - train_mean_token_accuracy: - type: number - valid_loss: - type: number - valid_mean_token_accuracy: - type: number - full_valid_loss: - type: number - full_valid_mean_token_accuracy: - type: number - fine_tuning_job_id: - type: string - description: The name of the fine-tuning job that this checkpoint was created from. - object: - type: string - description: The object type, which is always "fine_tuning.job.checkpoint". - enum: - - fine_tuning.job.checkpoint - x-stainless-const: true - required: - - created_at - - fine_tuning_job_id - - fine_tuned_model_checkpoint - - id - - metrics - - object - - step_number - x-oaiMeta: - name: The fine-tuning job checkpoint object - example: | - { - "object": "fine_tuning.job.checkpoint", - "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", - "created_at": 1712211699, - "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom_suffix:9ABel2dg:ckpt-step-88", - "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", - "metrics": { - "step": 88, - "train_loss": 0.478, - "train_mean_token_accuracy": 0.924, - "valid_loss": 10.112, - "valid_mean_token_accuracy": 0.145, - "full_valid_loss": 0.567, - "full_valid_mean_token_accuracy": 0.944 - }, - "step_number": 88 - } - FineTuningJobEvent: - type: object - description: Fine-tuning job event object - properties: - object: - type: string - description: The object type, which is always "fine_tuning.job.event". - enum: - - fine_tuning.job.event - x-stainless-const: true - id: - type: string - description: The object identifier. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the fine-tuning job was created. - level: - type: string - description: The log level of the event. - enum: - - info - - warn - - error - message: - type: string - description: The message of the event. - type: - type: string - description: The type of event. - enum: - - message - - metrics - data: - type: object - description: The data associated with the event. - required: - - id - - object - - created_at - - level - - message - x-oaiMeta: - name: The fine-tuning job event object - example: | - { - "object": "fine_tuning.job.event", - "id": "ftevent-abc123" - "created_at": 1677610602, - "level": "info", - "message": "Created fine-tuning job", - "data": {}, - "type": "message" - } - FunctionAndCustomToolCallOutput: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/InputTextContent' - - $ref: '#/components/schemas/InputImageContent' - - $ref: '#/components/schemas/InputFileContent' - FunctionObject: - type: object - properties: - description: - type: string - description: >- - A description of what the function does, used by the model to choose when and how to call the - function. - name: - type: string - description: >- - The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, - with a maximum length of 64. - parameters: - $ref: '#/components/schemas/FunctionParameters' - strict: - anyOf: - - type: boolean - default: false - description: >- - Whether to enable strict schema adherence when generating the function call. If set to true, - the model will follow the exact schema defined in the `parameters` field. Only a subset of - JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the - [function calling guide](https://platform.openai.com/docs/guides/function-calling). - - type: 'null' - required: - - name - FunctionParameters: - type: object - description: >- - 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. - additionalProperties: true - FunctionToolCall: - type: object - title: Function tool call - description: > - A tool call to run a function. See the - - [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more - information. - properties: - id: - type: string - description: | - The unique ID of the function tool call. - type: - type: string - enum: - - function_call - description: | - The type of the function tool call. Always `function_call`. - x-stainless-const: true - call_id: - type: string - description: | - The unique ID of the function tool call generated by the model. - name: - type: string - description: | - The name of the function to run. - arguments: - type: string - description: | - A JSON string of the arguments to pass to the function. - status: - type: string - description: | - The status of the item. One of `in_progress`, `completed`, or - `incomplete`. Populated when items are returned via API. - enum: - - in_progress - - completed - - incomplete - required: - - type - - call_id - - name - - arguments - FunctionToolCallOutput: - type: object - title: Function tool call output - description: | - The output of a function tool call. - properties: - id: - type: string - description: | - The unique ID of the function tool call output. Populated when this item - is returned via API. - type: - type: string - enum: - - function_call_output - description: | - The type of the function tool call output. Always `function_call_output`. - x-stainless-const: true - call_id: - type: string - description: | - The unique ID of the function tool call generated by the model. - output: - description: | - The output from the function call generated by your code. - Can be a string or an list of output content. - anyOf: - - type: string - description: | - A string of the output of the function call. - title: string output - - type: array - items: - $ref: '#/components/schemas/FunctionAndCustomToolCallOutput' - title: output content list - description: | - Text, image, or file output of the function call. - status: - type: string - description: | - The status of the item. One of `in_progress`, `completed`, or - `incomplete`. Populated when items are returned via API. - enum: - - in_progress - - completed - - incomplete - required: - - type - - call_id - - output - FunctionToolCallOutputResource: - allOf: - - $ref: '#/components/schemas/FunctionToolCallOutput' - - type: object - properties: - id: - type: string - description: | - The unique ID of the function call tool output. - required: - - id - FunctionToolCallResource: - allOf: - - $ref: '#/components/schemas/FunctionToolCall' - - type: object - properties: - id: - type: string - description: | - The unique ID of the function tool call. - required: - - id - GraderLabelModel: - type: object - title: LabelModelGrader - description: | - A LabelModelGrader object which uses a model to assign labels to each item - in the evaluation. - properties: - type: - description: The object type, which is always `label_model`. - type: string - enum: - - label_model - x-stainless-const: true - name: - type: string - description: The name of the grader. - model: - type: string - description: The model to use for the evaluation. Must support structured outputs. - input: - type: array - items: - $ref: '#/components/schemas/EvalItem' - labels: - type: array - items: - type: string - description: The labels to assign to each item in the evaluation. - passing_labels: - type: array - items: - type: string - description: The labels that indicate a passing result. Must be a subset of labels. - required: - - type - - model - - input - - passing_labels - - labels - - name - x-oaiMeta: - name: Label Model Grader - group: graders - example: | - { - "name": "First label grader", - "type": "label_model", - "model": "gpt-4o-2024-08-06", - "input": [ - { - "type": "message", - "role": "system", - "content": { - "type": "input_text", - "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative" - } - }, - { - "type": "message", - "role": "user", - "content": { - "type": "input_text", - "text": "Statement: {{item.response}}" - } - } - ], - "passing_labels": [ - "positive" - ], - "labels": [ - "positive", - "neutral", - "negative" - ] - } - GraderMulti: - type: object - title: MultiGrader - description: A MultiGrader object combines the output of multiple graders to produce a single score. - properties: - type: - type: string - enum: - - multi - default: multi - description: The object type, which is always `multi`. - x-stainless-const: true - name: - type: string - description: The name of the grader. - graders: - anyOf: - - $ref: '#/components/schemas/GraderStringCheck' - - $ref: '#/components/schemas/GraderTextSimilarity' - - $ref: '#/components/schemas/GraderPython' - - $ref: '#/components/schemas/GraderScoreModel' - - $ref: '#/components/schemas/GraderLabelModel' - calculate_output: - type: string - description: A formula to calculate the output based on grader results. - required: - - name - - type - - graders - - calculate_output - x-oaiMeta: - name: Multi Grader - group: graders - example: | - { - "type": "multi", - "name": "example multi grader", - "graders": [ - { - "type": "text_similarity", - "name": "example text similarity grader", - "input": "The graded text", - "reference": "The reference text", - "evaluation_metric": "fuzzy_match" - }, - { - "type": "string_check", - "name": "Example string check grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq" - } - ], - "calculate_output": "0.5 * text_similarity_score + 0.5 * string_check_score)" - } - GraderPython: - type: object - title: PythonGrader - description: | - A PythonGrader object that runs a python script on the input. - properties: - type: - type: string - enum: - - python - description: The object type, which is always `python`. - x-stainless-const: true - name: - type: string - description: The name of the grader. - source: - type: string - description: The source code of the python script. - image_tag: - type: string - description: The image tag to use for the python script. - required: - - type - - name - - source - x-oaiMeta: - name: Python Grader - group: graders - example: | - { - "type": "python", - "name": "Example python grader", - "image_tag": "2025-05-08", - "source": """ - def grade(sample: dict, item: dict) -> float: - \""" - Returns 1.0 if `output_text` equals `label`, otherwise 0.0. - \""" - output = sample.get("output_text") - label = item.get("label") - return 1.0 if output == label else 0.0 - """, - } - GraderScoreModel: - type: object - title: ScoreModelGrader - description: | - A ScoreModelGrader object that uses a model to assign a score to the input. - properties: - type: - type: string - enum: - - score_model - description: The object type, which is always `score_model`. - x-stainless-const: true - name: - type: string - description: The name of the grader. - model: - type: string - description: The model to use for the evaluation. - sampling_params: - type: object - description: The sampling parameters for the model. - properties: - seed: - anyOf: - - type: integer - description: | - A seed value to initialize the randomness, during sampling. - - type: 'null' - top_p: - anyOf: - - type: number - default: 1 - example: 1 - description: | - An alternative to temperature for nucleus sampling; 1.0 includes all tokens. - - type: 'null' - temperature: - anyOf: - - type: number - description: | - A higher temperature increases randomness in the outputs. - - type: 'null' - max_completions_tokens: - anyOf: - - type: integer - minimum: 1 - description: | - The maximum number of tokens the grader model may generate in its response. - - type: 'null' - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - input: - type: array - items: - $ref: '#/components/schemas/EvalItem' - description: The input text. This may include template strings. - range: - type: array - items: - type: number - min_items: 2 - max_items: 2 - description: The range of the score. Defaults to `[0, 1]`. - required: - - type - - name - - input - - model - x-oaiMeta: - name: Score Model Grader - group: graders - example: | - { - "type": "score_model", - "name": "Example score model grader", - "input": [ - { - "role": "user", - "content": ( - "Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different." - " Return just a floating point score\n\n" - " Reference answer: {{item.label}}\n\n" - " Model answer: {{sample.output_text}}" - ), - } - ], - "model": "o4-mini-2025-04-16", - "sampling_params": { - "temperature": 1, - "top_p": 1, - "seed": 42, - "max_completions_tokens": 32768, - "reasoning_effort": "medium" - }, - } - GraderStringCheck: - type: object - title: StringCheckGrader - description: > - A StringCheckGrader object that performs a string comparison between input and reference using a - specified operation. - properties: - type: - type: string - enum: - - string_check - description: The object type, which is always `string_check`. - x-stainless-const: true - name: - type: string - description: The name of the grader. - input: - type: string - description: The input text. This may include template strings. - reference: - type: string - description: The reference text. This may include template strings. - operation: - type: string - enum: - - eq - - ne - - like - - ilike - description: The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. - required: - - type - - name - - input - - reference - - operation - x-oaiMeta: - name: String Check Grader - group: graders - example: | - { - "type": "string_check", - "name": "Example string check grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "operation": "eq" - } - GraderTextSimilarity: - type: object - title: TextSimilarityGrader - description: | - A TextSimilarityGrader object which grades text based on similarity metrics. - properties: - type: - type: string - enum: - - text_similarity - default: text_similarity - description: The type of grader. - x-stainless-const: true - name: - type: string - description: The name of the grader. - input: - type: string - description: The text being graded. - reference: - type: string - description: The text being graded against. - evaluation_metric: - type: string - enum: - - cosine - - fuzzy_match - - bleu - - gleu - - meteor - - rouge_1 - - rouge_2 - - rouge_3 - - rouge_4 - - rouge_5 - - rouge_l - description: | - The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, - `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, - or `rouge_l`. - required: - - type - - name - - input - - reference - - evaluation_metric - x-oaiMeta: - name: Text Similarity Grader - group: graders - example: | - { - "type": "text_similarity", - "name": "Example text similarity grader", - "input": "{{sample.output_text}}", - "reference": "{{item.label}}", - "evaluation_metric": "fuzzy_match" - } - Group: - type: object - description: Summary information about a group returned in role assignment responses. - properties: - object: - type: string - enum: - - group - description: Always `group`. - x-stainless-const: true - id: - type: string - description: Identifier for the group. - name: - type: string - description: Display name of the group. - created_at: - type: integer - format: int64 - description: Unix timestamp (in seconds) when the group was created. - scim_managed: - type: boolean - description: Whether the group is managed through SCIM. - required: - - object - - id - - name - - created_at - - scim_managed - x-oaiMeta: - name: The group object - example: | - { - "object": "group", - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "scim_managed": false - } - GroupDeletedResource: - type: object - description: Confirmation payload returned after deleting a group. - properties: - object: - type: string - enum: - - group.deleted - description: Always `group.deleted`. - x-stainless-const: true - id: - type: string - description: Identifier of the deleted group. - deleted: - type: boolean - description: Whether the group was deleted. - required: - - object - - id - - deleted - x-oaiMeta: - example: | - { - "object": "group.deleted", - "id": "group_01J1F8ABCDXYZ", - "deleted": true - } - GroupListResource: - type: object - description: Paginated list of organization groups. - properties: - object: - type: string - enum: - - list - description: Always `list`. - x-stainless-const: true - data: - type: array - description: Groups returned in the current page. - items: - $ref: '#/components/schemas/GroupResponse' - has_more: - type: boolean - description: Whether additional groups are available when paginating. - next: - description: Cursor to fetch the next page of results, or `null` if there are no more results. - anyOf: - - type: string - - type: 'null' - required: - - object - - data - - has_more - - next - x-oaiMeta: - name: Group list - example: | - { - "object": "list", - "data": [ - { - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "is_scim_managed": false - }, - { - "id": "group_01J1F8PQRMNO", - "name": "Sales", - "created_at": 1711472599, - "is_scim_managed": true - } - ], - "has_more": false, - "next": null - } - GroupResourceWithSuccess: - type: object - description: Response returned after updating a group. - properties: - id: - type: string - description: Identifier for the group. - name: - type: string - description: Updated display name for the group. - created_at: - type: integer - format: int64 - description: Unix timestamp (in seconds) when the group was created. - is_scim_managed: - type: boolean - description: Whether the group is managed through SCIM and controlled by your identity provider. - required: - - id - - name - - created_at - - is_scim_managed - x-oaiMeta: - example: | - { - "id": "group_01J1F8ABCDXYZ", - "name": "Escalations", - "created_at": 1711471533, - "is_scim_managed": false - } - GroupResponse: - type: object - description: Details about an organization group. - properties: - id: - type: string - description: Identifier for the group. - name: - type: string - description: Display name of the group. - created_at: - type: integer - format: int64 - description: Unix timestamp (in seconds) when the group was created. - is_scim_managed: - type: boolean - description: Whether the group is managed through SCIM and controlled by your identity provider. - required: - - id - - name - - created_at - - is_scim_managed - x-oaiMeta: - name: Group - example: | - { - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "is_scim_managed": false - } - GroupRoleAssignment: - type: object - description: Role assignment linking a group to a role. - properties: - object: - type: string - enum: - - group.role - description: Always `group.role`. - x-stainless-const: true - group: - $ref: '#/components/schemas/Group' - role: - $ref: '#/components/schemas/Role' - required: - - object - - group - - role - x-oaiMeta: - name: The group role object - example: | - { - "object": "group.role", - "group": { - "object": "group", - "id": "group_01J1F8ABCDXYZ", - "name": "Support Team", - "created_at": 1711471533, - "scim_managed": false - }, - "role": { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - } - GroupUserAssignment: - type: object - description: Confirmation payload returned after adding a user to a group. - properties: - object: - type: string - enum: - - group.user - description: Always `group.user`. - x-stainless-const: true - user_id: - type: string - description: Identifier of the user that was added. - group_id: - type: string - description: Identifier of the group the user was added to. - required: - - object - - user_id - - group_id - x-oaiMeta: - name: The group user object - example: | - { - "object": "group.user", - "user_id": "user_abc123", - "group_id": "group_01J1F8ABCDXYZ" - } - GroupUserDeletedResource: - type: object - description: Confirmation payload returned after removing a user from a group. - properties: - object: - type: string - enum: - - group.user.deleted - description: Always `group.user.deleted`. - x-stainless-const: true - deleted: - type: boolean - description: Whether the group membership was removed. - required: - - object - - deleted - x-oaiMeta: - name: Group user deletion confirmation - example: | - { - "object": "group.user.deleted", - "deleted": true - } - Image: - type: object - description: Represents the content or the URL of an image generated by the OpenAI API. - properties: - b64_json: - type: string - description: >- - The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present - if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`. - url: - type: string - description: >- - When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to - `url` (default value). Unsupported for `gpt-image-1`. - revised_prompt: - type: string - description: For `dall-e-3` only, the revised prompt that was used to generate the image. - ImageEditCompletedEvent: - type: object - description: | - Emitted when image editing has completed and the final image is available. - properties: - type: - type: string - description: | - The type of the event. Always `image_edit.completed`. - enum: - - image_edit.completed - x-stainless-const: true - b64_json: - type: string - description: | - Base64-encoded final edited image data, suitable for rendering as an image. - created_at: - type: integer - description: | - The Unix timestamp when the event was created. - size: - type: string - description: | - The size of the edited image. - enum: - - 1024x1024 - - 1024x1536 - - 1536x1024 - - auto - quality: - type: string - description: | - The quality setting for the edited image. - enum: - - low - - medium - - high - - auto - background: - type: string - description: | - The background setting for the edited image. - enum: - - transparent - - opaque - - auto - output_format: - type: string - description: | - The output format for the edited image. - enum: - - png - - webp - - jpeg - usage: - $ref: '#/components/schemas/ImagesUsage' - required: - - type - - b64_json - - created_at - - size - - quality - - background - - output_format - - usage - x-oaiMeta: - name: image_edit.completed - group: images - example: | - { - "type": "image_edit.completed", - "b64_json": "...", - "created_at": 1620000000, - "size": "1024x1024", - "quality": "high", - "background": "transparent", - "output_format": "png", - "usage": { - "total_tokens": 100, - "input_tokens": 50, - "output_tokens": 50, - "input_tokens_details": { - "text_tokens": 10, - "image_tokens": 40 - } - } - } - ImageEditPartialImageEvent: - type: object - description: | - Emitted when a partial image is available during image editing streaming. - properties: - type: - type: string - description: | - The type of the event. Always `image_edit.partial_image`. - enum: - - image_edit.partial_image - x-stainless-const: true - b64_json: - type: string - description: | - Base64-encoded partial image data, suitable for rendering as an image. - created_at: - type: integer - description: | - The Unix timestamp when the event was created. - size: - type: string - description: | - The size of the requested edited image. - enum: - - 1024x1024 - - 1024x1536 - - 1536x1024 - - auto - quality: - type: string - description: | - The quality setting for the requested edited image. - enum: - - low - - medium - - high - - auto - background: - type: string - description: | - The background setting for the requested edited image. - enum: - - transparent - - opaque - - auto - output_format: - type: string - description: | - The output format for the requested edited image. - enum: - - png - - webp - - jpeg - partial_image_index: - type: integer - description: | - 0-based index for the partial image (streaming). - required: - - type - - b64_json - - created_at - - size - - quality - - background - - output_format - - partial_image_index - x-oaiMeta: - name: image_edit.partial_image - group: images - example: | - { - "type": "image_edit.partial_image", - "b64_json": "...", - "created_at": 1620000000, - "size": "1024x1024", - "quality": "high", - "background": "transparent", - "output_format": "png", - "partial_image_index": 0 - } - ImageEditStreamEvent: - anyOf: - - $ref: '#/components/schemas/ImageEditPartialImageEvent' - - $ref: '#/components/schemas/ImageEditCompletedEvent' - discriminator: - propertyName: type - ImageGenCompletedEvent: - type: object - description: | - Emitted when image generation has completed and the final image is available. - properties: - type: - type: string - description: | - The type of the event. Always `image_generation.completed`. - enum: - - image_generation.completed - x-stainless-const: true - b64_json: - type: string - description: | - Base64-encoded image data, suitable for rendering as an image. - created_at: - type: integer - description: | - The Unix timestamp when the event was created. - size: - type: string - description: | - The size of the generated image. - enum: - - 1024x1024 - - 1024x1536 - - 1536x1024 - - auto - quality: - type: string - description: | - The quality setting for the generated image. - enum: - - low - - medium - - high - - auto - background: - type: string - description: | - The background setting for the generated image. - enum: - - transparent - - opaque - - auto - output_format: - type: string - description: | - The output format for the generated image. - enum: - - png - - webp - - jpeg - usage: - $ref: '#/components/schemas/ImagesUsage' - required: - - type - - b64_json - - created_at - - size - - quality - - background - - output_format - - usage - x-oaiMeta: - name: image_generation.completed - group: images - example: | - { - "type": "image_generation.completed", - "b64_json": "...", - "created_at": 1620000000, - "size": "1024x1024", - "quality": "high", - "background": "transparent", - "output_format": "png", - "usage": { - "total_tokens": 100, - "input_tokens": 50, - "output_tokens": 50, - "input_tokens_details": { - "text_tokens": 10, - "image_tokens": 40 - } - } - } - ImageGenPartialImageEvent: - type: object - description: | - Emitted when a partial image is available during image generation streaming. - properties: - type: - type: string - description: | - The type of the event. Always `image_generation.partial_image`. - enum: - - image_generation.partial_image - x-stainless-const: true - b64_json: - type: string - description: | - Base64-encoded partial image data, suitable for rendering as an image. - created_at: - type: integer - description: | - The Unix timestamp when the event was created. - size: - type: string - description: | - The size of the requested image. - enum: - - 1024x1024 - - 1024x1536 - - 1536x1024 - - auto - quality: - type: string - description: | - The quality setting for the requested image. - enum: - - low - - medium - - high - - auto - background: - type: string - description: | - The background setting for the requested image. - enum: - - transparent - - opaque - - auto - output_format: - type: string - description: | - The output format for the requested image. - enum: - - png - - webp - - jpeg - partial_image_index: - type: integer - description: | - 0-based index for the partial image (streaming). - required: - - type - - b64_json - - created_at - - size - - quality - - background - - output_format - - partial_image_index - x-oaiMeta: - name: image_generation.partial_image - group: images - example: | - { - "type": "image_generation.partial_image", - "b64_json": "...", - "created_at": 1620000000, - "size": "1024x1024", - "quality": "high", - "background": "transparent", - "output_format": "png", - "partial_image_index": 0 - } - ImageGenStreamEvent: - anyOf: - - $ref: '#/components/schemas/ImageGenPartialImageEvent' - - $ref: '#/components/schemas/ImageGenCompletedEvent' - discriminator: - propertyName: type - ImageGenTool: - type: object - title: Image generation tool - description: | - A tool that generates images using a model like `gpt-image-1`. - properties: - type: - type: string - enum: - - image_generation - description: | - The type of the image generation tool. Always `image_generation`. - x-stainless-const: true - model: - type: string - enum: - - gpt-image-1 - - gpt-image-1-mini - description: | - The image generation model to use. Default: `gpt-image-1`. - default: gpt-image-1 - quality: - type: string - enum: - - low - - medium - - high - - auto - description: | - The quality of the generated image. One of `low`, `medium`, `high`, - or `auto`. Default: `auto`. - default: auto - size: - type: string - enum: - - 1024x1024 - - 1024x1536 - - 1536x1024 - - auto - description: | - The size of the generated image. One of `1024x1024`, `1024x1536`, - `1536x1024`, or `auto`. Default: `auto`. - default: auto - output_format: - type: string - enum: - - png - - webp - - jpeg - description: | - The output format of the generated image. One of `png`, `webp`, or - `jpeg`. Default: `png`. - default: png - output_compression: - type: integer - minimum: 0 - maximum: 100 - description: | - Compression level for the output image. Default: 100. - default: 100 - moderation: - type: string - enum: - - auto - - low - description: | - Moderation level for the generated image. Default: `auto`. - default: auto - background: - type: string - enum: - - transparent - - opaque - - auto - description: | - Background type for the generated image. One of `transparent`, - `opaque`, or `auto`. Default: `auto`. - default: auto - input_fidelity: - anyOf: - - $ref: '#/components/schemas/InputFidelity' - - type: 'null' - input_image_mask: - type: object - description: | - Optional mask for inpainting. Contains `image_url` - (string, optional) and `file_id` (string, optional). - properties: - image_url: - type: string - description: | - Base64-encoded mask image. - file_id: - type: string - description: | - File ID for the mask image. - required: [] - additionalProperties: false - partial_images: - type: integer - minimum: 0 - maximum: 3 - description: | - Number of partial images to generate in streaming mode, from 0 (default value) to 3. - default: 0 - required: - - type - ImageGenToolCall: - type: object - title: Image generation call - description: | - An image generation request made by the model. - properties: - type: - type: string - enum: - - image_generation_call - description: | - The type of the image generation call. Always `image_generation_call`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the image generation call. - status: - type: string - enum: - - in_progress - - completed - - generating - - failed - description: | - The status of the image generation call. - result: - anyOf: - - type: string - description: | - The generated image encoded in base64. - - type: 'null' - required: - - type - - id - - status - - result - ImagesResponse: - type: object - title: Image generation response - description: The response from the image generation endpoint. - properties: - created: - type: integer - description: The Unix timestamp (in seconds) of when the image was created. - data: - type: array - description: The list of generated images. - items: - $ref: '#/components/schemas/Image' - background: - type: string - description: The background parameter used for the image generation. Either `transparent` or `opaque`. - enum: - - transparent - - opaque - output_format: - type: string - description: The output format of the image generation. Either `png`, `webp`, or `jpeg`. - enum: - - png - - webp - - jpeg - size: - type: string - description: The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`. - enum: - - 1024x1024 - - 1024x1536 - - 1536x1024 - quality: - type: string - description: The quality of the image generated. Either `low`, `medium`, or `high`. - enum: - - low - - medium - - high - usage: - $ref: '#/components/schemas/ImageGenUsage' - required: - - created - x-oaiMeta: - name: The image generation response - group: images - example: | - { - "created": 1713833628, - "data": [ - { - "b64_json": "..." - } - ], - "background": "transparent", - "output_format": "png", - "size": "1024x1024", - "quality": "high", - "usage": { - "total_tokens": 100, - "input_tokens": 50, - "output_tokens": 50, - "input_tokens_details": { - "text_tokens": 10, - "image_tokens": 40 - } - } - } - ImagesUsage: - type: object - description: | - For `gpt-image-1` only, the token usage information for the image generation. - required: - - total_tokens - - input_tokens - - output_tokens - - input_tokens_details - properties: - total_tokens: - type: integer - description: | - The total number of tokens (images and text) used for the image generation. - input_tokens: - type: integer - description: The number of tokens (images and text) in the input prompt. - output_tokens: - type: integer - description: The number of image tokens in the output image. - input_tokens_details: - type: object - description: The input tokens detailed information for the image generation. - required: - - text_tokens - - image_tokens - properties: - text_tokens: - type: integer - description: The number of text tokens in the input prompt. - image_tokens: - type: integer - description: The number of image tokens in the input prompt. - InputAudio: - type: object - title: Input audio - description: | - An audio input to the model. - properties: - type: - type: string - description: | - The type of the input item. Always `input_audio`. - enum: - - input_audio - x-stainless-const: true - input_audio: - type: object - properties: - data: - type: string - description: | - Base64-encoded audio data. - format: - type: string - description: | - The format of the audio data. Currently supported formats are `mp3` and - `wav`. - enum: - - mp3 - - wav - required: - - data - - format - required: - - type - - input_audio - InputContent: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/InputTextContent' - - $ref: '#/components/schemas/InputImageContent' - - $ref: '#/components/schemas/InputFileContent' - InputItem: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/EasyInputMessage' - - type: object - title: Item - description: | - An item representing part of the context for the response to be - generated by the model. Can contain text, images, and audio inputs, - as well as previous assistant responses and tool call outputs. - $ref: '#/components/schemas/Item' - - $ref: '#/components/schemas/ItemReferenceParam' - InputMessage: - type: object - title: Input message - description: | - A message input to the model with a role indicating instruction following - hierarchy. Instructions given with the `developer` or `system` role take - precedence over instructions given with the `user` role. - properties: - type: - type: string - description: | - The type of the message input. Always set to `message`. - enum: - - message - x-stainless-const: true - role: - type: string - description: | - The role of the message input. One of `user`, `system`, or `developer`. - enum: - - user - - system - - developer - status: - type: string - description: | - The status of item. One of `in_progress`, `completed`, or - `incomplete`. Populated when items are returned via API. - enum: - - in_progress - - completed - - incomplete - content: - $ref: '#/components/schemas/InputMessageContentList' - required: - - role - - content - InputMessageContentList: - type: array - title: Input item content list - description: | - A list of one or many input items to the model, containing different content - types. - items: - $ref: '#/components/schemas/InputContent' - InputMessageResource: - allOf: - - $ref: '#/components/schemas/InputMessage' - - type: object - properties: - id: - type: string - description: | - The unique ID of the message input. - required: - - id - InputParam: - description: | - Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - anyOf: - - type: string - title: Text input - description: | - A text input to the model, equivalent to a text input with the - `user` role. - - type: array - title: Input item list - description: | - A list of one or many input items to the model, containing - different content types. - items: - $ref: '#/components/schemas/InputItem' - Invite: - type: object - description: Represents an individual `invite` to the organization. - properties: - object: - type: string - enum: - - organization.invite - description: The object type, which is always `organization.invite` - x-stainless-const: true - id: - type: string - description: The identifier, which can be referenced in API endpoints - email: - type: string - description: The email address of the individual to whom the invite was sent - role: - type: string - enum: - - owner - - reader - description: '`owner` or `reader`' - status: - type: string - enum: - - accepted - - expired - - pending - description: '`accepted`,`expired`, or `pending`' - invited_at: - type: integer - description: The Unix timestamp (in seconds) of when the invite was sent. - expires_at: - type: integer - description: The Unix timestamp (in seconds) of when the invite expires. - accepted_at: - type: integer - description: The Unix timestamp (in seconds) of when the invite was accepted. - projects: - type: array - description: The projects that were granted membership upon acceptance of the invite. - items: - type: object - properties: - id: - type: string - description: Project's public ID - role: - type: string - enum: - - member - - owner - description: Project membership role - required: - - object - - id - - email - - role - - status - - invited_at - - expires_at - x-oaiMeta: - name: The invite object - example: | - { - "object": "organization.invite", - "id": "invite-abc", - "email": "user@example.com", - "role": "owner", - "status": "accepted", - "invited_at": 1711471533, - "expires_at": 1711471533, - "accepted_at": 1711471533, - "projects": [ - { - "id": "project-xyz", - "role": "member" - } - ] - } - InviteDeleteResponse: - type: object - properties: - object: - type: string - enum: - - organization.invite.deleted - description: The object type, which is always `organization.invite.deleted` - x-stainless-const: true - id: - type: string - deleted: - type: boolean - required: - - object - - id - - deleted - InviteListResponse: - type: object - properties: - object: - type: string - enum: - - list - description: The object type, which is always `list` - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/Invite' - first_id: - type: string - description: The first `invite_id` in the retrieved `list` - last_id: - type: string - description: The last `invite_id` in the retrieved `list` - has_more: - type: boolean - description: The `has_more` property is used for pagination to indicate there are additional results. - required: - - object - - data - InviteProjectGroupBody: - type: object - description: Request payload for granting a group access to a project. - properties: - group_id: - type: string - description: Identifier of the group to add to the project. - role: - type: string - description: Identifier of the project role to grant to the group. - required: - - group_id - - role - x-oaiMeta: - example: | - { - "group_id": "group_01J1F8ABCDXYZ", - "role": "role_01J1F8PROJ" - } - InviteRequest: - type: object - properties: - email: - type: string - description: Send an email to this address - role: - type: string - enum: - - reader - - owner - description: '`owner` or `reader`' - projects: - type: array - description: >- - An array of projects to which membership is granted at the same time the org invite is accepted. - If omitted, the user will be invited to the default project for compatibility with legacy - behavior. - items: - type: object - properties: - id: - type: string - description: Project's public ID - role: - type: string - enum: - - member - - owner - description: Project membership role - required: - - id - - role - required: - - email - - role - Item: - type: object - description: | - Content item used to generate a response. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/InputMessage' - - $ref: '#/components/schemas/OutputMessage' - - $ref: '#/components/schemas/FileSearchToolCall' - - $ref: '#/components/schemas/ComputerToolCall' - - $ref: '#/components/schemas/ComputerCallOutputItemParam' - - $ref: '#/components/schemas/WebSearchToolCall' - - $ref: '#/components/schemas/FunctionToolCall' - - $ref: '#/components/schemas/FunctionCallOutputItemParam' - - $ref: '#/components/schemas/ReasoningItem' - - $ref: '#/components/schemas/ImageGenToolCall' - - $ref: '#/components/schemas/CodeInterpreterToolCall' - - $ref: '#/components/schemas/LocalShellToolCall' - - $ref: '#/components/schemas/LocalShellToolCallOutput' - - $ref: '#/components/schemas/FunctionShellCallItemParam' - - $ref: '#/components/schemas/FunctionShellCallOutputItemParam' - - $ref: '#/components/schemas/ApplyPatchToolCallItemParam' - - $ref: '#/components/schemas/ApplyPatchToolCallOutputItemParam' - - $ref: '#/components/schemas/MCPListTools' - - $ref: '#/components/schemas/MCPApprovalRequest' - - $ref: '#/components/schemas/MCPApprovalResponse' - - $ref: '#/components/schemas/MCPToolCall' - - $ref: '#/components/schemas/CustomToolCallOutput' - - $ref: '#/components/schemas/CustomToolCall' - ItemResource: - description: | - Content item used to generate a response. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/InputMessageResource' - - $ref: '#/components/schemas/OutputMessage' - - $ref: '#/components/schemas/FileSearchToolCall' - - $ref: '#/components/schemas/ComputerToolCall' - - $ref: '#/components/schemas/ComputerToolCallOutputResource' - - $ref: '#/components/schemas/WebSearchToolCall' - - $ref: '#/components/schemas/FunctionToolCallResource' - - $ref: '#/components/schemas/FunctionToolCallOutputResource' - - $ref: '#/components/schemas/ImageGenToolCall' - - $ref: '#/components/schemas/CodeInterpreterToolCall' - - $ref: '#/components/schemas/LocalShellToolCall' - - $ref: '#/components/schemas/LocalShellToolCallOutput' - - $ref: '#/components/schemas/FunctionShellCall' - - $ref: '#/components/schemas/FunctionShellCallOutput' - - $ref: '#/components/schemas/ApplyPatchToolCall' - - $ref: '#/components/schemas/ApplyPatchToolCallOutput' - - $ref: '#/components/schemas/MCPListTools' - - $ref: '#/components/schemas/MCPApprovalRequest' - - $ref: '#/components/schemas/MCPApprovalResponseResource' - - $ref: '#/components/schemas/MCPToolCall' - ListAssistantsResponse: - type: object - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/AssistantObject' - first_id: - type: string - example: asst_abc123 - last_id: - type: string - example: asst_abc456 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: List assistants response object - group: chat - example: | - { - "object": "list", - "data": [ - { - "id": "asst_abc123", - "object": "assistant", - "created_at": 1698982736, - "name": "Coding Tutor", - "description": null, - "model": "gpt-4o", - "instructions": "You are a helpful assistant designed to make me better at coding!", - "tools": [], - "tool_resources": {}, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - }, - { - "id": "asst_abc456", - "object": "assistant", - "created_at": 1698982718, - "name": "My Assistant", - "description": null, - "model": "gpt-4o", - "instructions": "You are a helpful assistant designed to make me better at coding!", - "tools": [], - "tool_resources": {}, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - }, - { - "id": "asst_abc789", - "object": "assistant", - "created_at": 1698982643, - "name": null, - "description": null, - "model": "gpt-4o", - "instructions": null, - "tools": [], - "tool_resources": {}, - "metadata": {}, - "top_p": 1.0, - "temperature": 1.0, - "response_format": "auto" - } - ], - "first_id": "asst_abc123", - "last_id": "asst_abc789", - "has_more": false - } - ListAuditLogsResponse: - type: object - properties: - object: - type: string - enum: - - list - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/AuditLog' - first_id: - type: string - example: audit_log-defb456h8dks - last_id: - type: string - example: audit_log-hnbkd8s93s - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - ListBatchesResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/Batch' - first_id: - type: string - example: batch_abc123 - last_id: - type: string - example: batch_abc456 - has_more: - type: boolean - object: - type: string - enum: - - list - x-stainless-const: true - required: - - object - - data - - has_more - ListCertificatesResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/Certificate' - first_id: - type: string - example: cert_abc - last_id: - type: string - example: cert_abc - has_more: - type: boolean - object: - type: string - enum: - - list - x-stainless-const: true - required: - - object - - data - - has_more - ListFilesResponse: - type: object - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/OpenAIFile' - first_id: - type: string - example: file-abc123 - last_id: - type: string - example: file-abc456 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - ListFineTuningCheckpointPermissionResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/FineTuningCheckpointPermission' - object: - type: string - enum: - - list - x-stainless-const: true - first_id: - anyOf: - - type: string - - type: 'null' - last_id: - anyOf: - - type: string - - type: 'null' - has_more: - type: boolean - required: - - object - - data - - has_more - ListFineTuningJobCheckpointsResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/FineTuningJobCheckpoint' - object: - type: string - enum: - - list - x-stainless-const: true - first_id: - anyOf: - - type: string - - type: 'null' - last_id: - anyOf: - - type: string - - type: 'null' - has_more: - type: boolean - required: - - object - - data - - has_more - ListFineTuningJobEventsResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/FineTuningJobEvent' - object: - type: string - enum: - - list - x-stainless-const: true - has_more: - type: boolean - required: - - object - - data - - has_more - ListMessagesResponse: - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/MessageObject' - first_id: - type: string - example: msg_abc123 - last_id: - type: string - example: msg_abc123 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - ListModelsResponse: - type: object - properties: - object: - type: string - enum: - - list - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/Model' - required: - - object - - data - ListPaginatedFineTuningJobsResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/FineTuningJob' - has_more: - type: boolean - object: - type: string - enum: - - list - x-stainless-const: true - required: - - object - - data - - has_more - ListRunStepsResponse: - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/RunStepObject' - first_id: - type: string - example: step_abc123 - last_id: - type: string - example: step_abc456 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - ListRunsResponse: - type: object - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/RunObject' - first_id: - type: string - example: run_abc123 - last_id: - type: string - example: run_abc456 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - ListVectorStoreFilesResponse: - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/VectorStoreFileObject' - first_id: - type: string - example: file-abc123 - last_id: - type: string - example: file-abc456 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - ListVectorStoresResponse: - properties: - object: - type: string - example: list - data: - type: array - items: - $ref: '#/components/schemas/VectorStoreObject' - first_id: - type: string - example: vs_abc123 - last_id: - type: string - example: vs_abc456 - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - LocalShellToolCall: - type: object - title: Local shell call - description: | - A tool call to run a command on the local shell. - properties: - type: - type: string - enum: - - local_shell_call - description: | - The type of the local shell call. Always `local_shell_call`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the local shell call. - call_id: - type: string - description: | - The unique ID of the local shell tool call generated by the model. - action: - $ref: '#/components/schemas/LocalShellExecAction' - status: - type: string - enum: - - in_progress - - completed - - incomplete - description: | - The status of the local shell call. - required: - - type - - id - - call_id - - action - - status - LocalShellToolCallOutput: - type: object - title: Local shell call output - description: | - The output of a local shell tool call. - properties: - type: - type: string - enum: - - local_shell_call_output - description: | - The type of the local shell tool call output. Always `local_shell_call_output`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the local shell tool call generated by the model. - output: - type: string - description: | - A JSON string of the output of the local shell tool call. - status: - anyOf: - - type: string - enum: - - in_progress - - completed - - incomplete - description: | - The status of the item. One of `in_progress`, `completed`, or `incomplete`. - - type: 'null' - required: - - id - - type - - call_id - - output - LogProbProperties: - type: object - description: | - A log probability object. - properties: - token: - type: string - description: | - The token that was used to generate the log probability. - logprob: - type: number - description: | - The log probability of the token. - bytes: - type: array - items: - type: integer - description: | - The bytes that were used to generate the log probability. - required: - - token - - logprob - - bytes - MCPApprovalRequest: - type: object - title: MCP approval request - description: | - A request for human approval of a tool invocation. - properties: - type: - type: string - enum: - - mcp_approval_request - description: | - The type of the item. Always `mcp_approval_request`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the approval request. - server_label: - type: string - description: | - The label of the MCP server making the request. - name: - type: string - description: | - The name of the tool to run. - arguments: - type: string - description: | - A JSON string of arguments for the tool. - required: - - type - - id - - server_label - - name - - arguments - MCPApprovalResponse: - type: object - title: MCP approval response - description: | - A response to an MCP approval request. - properties: - type: - type: string - enum: - - mcp_approval_response - description: | - The type of the item. Always `mcp_approval_response`. - x-stainless-const: true - id: - anyOf: - - type: string - description: | - The unique ID of the approval response - - type: 'null' - approval_request_id: - type: string - description: | - The ID of the approval request being answered. - approve: - type: boolean - description: | - Whether the request was approved. - reason: - anyOf: - - type: string - description: | - Optional reason for the decision. - - type: 'null' - required: - - type - - request_id - - approve - - approval_request_id - MCPApprovalResponseResource: - type: object - title: MCP approval response - description: | - A response to an MCP approval request. - properties: - type: - type: string - enum: - - mcp_approval_response - description: | - The type of the item. Always `mcp_approval_response`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the approval response - approval_request_id: - type: string - description: | - The ID of the approval request being answered. - approve: - type: boolean - description: | - Whether the request was approved. - reason: - anyOf: - - type: string - description: | - Optional reason for the decision. - - type: 'null' - required: - - type - - id - - request_id - - approve - - approval_request_id - MCPListTools: - type: object - title: MCP list tools - description: | - A list of tools available on an MCP server. - properties: - type: - type: string - enum: - - mcp_list_tools - description: | - The type of the item. Always `mcp_list_tools`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the list. - server_label: - type: string - description: | - The label of the MCP server. - tools: - type: array - items: - $ref: '#/components/schemas/MCPListToolsTool' - description: | - The tools available on the server. - error: - anyOf: - - type: string - description: | - Error message if the server could not list tools. - - type: 'null' - required: - - type - - id - - server_label - - tools - MCPListToolsTool: - type: object - title: MCP list tools tool - description: | - A tool available on an MCP server. - properties: - name: - type: string - description: | - The name of the tool. - description: - anyOf: - - type: string - description: | - The description of the tool. - - type: 'null' - input_schema: - type: object - description: | - The JSON schema describing the tool's input. - annotations: - anyOf: - - type: object - description: | - Additional annotations about the tool. - - type: 'null' - required: - - name - - input_schema - MCPTool: - type: object - title: MCP tool - description: | - 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). - properties: - type: - type: string - enum: - - mcp - description: The type of the MCP tool. Always `mcp`. - x-stainless-const: true - server_label: - type: string - description: | - A label for this MCP server, used to identify it in tool calls. - server_url: - type: string - description: | - The URL for the MCP server. One of `server_url` or `connector_id` must be - provided. - connector_id: - type: string - enum: - - connector_dropbox - - connector_gmail - - connector_googlecalendar - - connector_googledrive - - connector_microsoftteams - - connector_outlookcalendar - - connector_outlookemail - - connector_sharepoint - description: | - 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` - authorization: - type: string - description: | - 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. - server_description: - type: string - description: | - Optional description of the MCP server, used to provide more context. - headers: - anyOf: - - type: object - additionalProperties: - type: string - description: | - Optional HTTP headers to send to the MCP server. Use for authentication - or other purposes. - - type: 'null' - allowed_tools: - anyOf: - - description: | - List of allowed tool names or a filter object. - anyOf: - - type: array - title: MCP allowed tools - description: A string array of allowed tool names - items: - type: string - - $ref: '#/components/schemas/MCPToolFilter' - - type: 'null' - require_approval: - anyOf: - - description: Specify which of the MCP server's tools require approval. - default: always - anyOf: - - type: object - title: MCP tool approval filter - description: | - Specify which of the MCP server's tools require approval. Can be - `always`, `never`, or a filter object associated with tools - that require approval. - properties: - always: - $ref: '#/components/schemas/MCPToolFilter' - never: - $ref: '#/components/schemas/MCPToolFilter' - additionalProperties: false - - type: string - title: MCP tool approval setting - description: | - 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. - enum: - - always - - never - - type: 'null' - required: - - type - - server_label - MCPToolCall: - type: object - title: MCP tool call - description: | - An invocation of a tool on an MCP server. - properties: - type: - type: string - enum: - - mcp_call - description: | - The type of the item. Always `mcp_call`. - x-stainless-const: true - id: - type: string - description: | - The unique ID of the tool call. - server_label: - type: string - description: | - The label of the MCP server running the tool. - name: - type: string - description: | - The name of the tool that was run. - arguments: - type: string - description: | - A JSON string of the arguments passed to the tool. - output: - anyOf: - - type: string - description: | - The output from the tool call. - - type: 'null' - error: - anyOf: - - type: string - description: | - The error from the tool call, if any. - - type: 'null' - status: - $ref: '#/components/schemas/MCPToolCallStatus' - description: > - The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or - `failed`. - approval_request_id: - anyOf: - - type: string - description: > - Unique identifier for the MCP tool call approval request. - - Include this value in a subsequent `mcp_approval_response` input to approve or reject the - corresponding tool call. - - type: 'null' - required: - - type - - id - - server_label - - name - - arguments - MCPToolFilter: - type: object - title: MCP tool filter - description: | - A filter object to specify which tools are allowed. - properties: - tool_names: - type: array - title: MCP allowed tools - items: - type: string - description: List of allowed tool names. - read_only: - type: boolean - description: > - 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. - required: [] - additionalProperties: false - MessageContentImageFileObject: - title: Image file - type: object - description: >- - References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a - message. - properties: - type: - description: Always `image_file`. - type: string - enum: - - image_file - x-stainless-const: true - image_file: - type: object - properties: - file_id: - description: >- - The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the - message content. Set `purpose="vision"` when uploading the File if you need to later display - the file content. - type: string - detail: - type: string - description: >- - Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you - can opt in to high resolution using `high`. - enum: - - auto - - low - - high - default: auto - required: - - file_id - required: - - type - - image_file - MessageContentImageUrlObject: - title: Image URL - type: object - description: References an image URL in the content of a message. - properties: - type: - type: string - enum: - - image_url - description: The type of the content part. - x-stainless-const: true - image_url: - type: object - properties: - url: - type: string - description: 'The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' - format: uri - detail: - type: string - description: >- - Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high - resolution using `high`. Default value is `auto` - enum: - - auto - - low - - high - default: auto - required: - - url - required: - - type - - image_url - MessageContentRefusalObject: - title: Refusal - type: object - description: The refusal content generated by the assistant. - properties: - type: - description: Always `refusal`. - type: string - enum: - - refusal - x-stainless-const: true - refusal: - type: string - required: - - type - - refusal - MessageContentTextAnnotationsFileCitationObject: - title: File citation - type: object - description: >- - A citation within the message that points to a specific quote from a specific File associated with the - assistant or the message. Generated when the assistant uses the "file_search" tool to search files. - properties: - type: - description: Always `file_citation`. - type: string - enum: - - file_citation - x-stainless-const: true - text: - description: The text in the message content that needs to be replaced. - type: string - file_citation: - type: object - properties: - file_id: - description: The ID of the specific File the citation is from. - type: string - required: - - file_id - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 - required: - - type - - text - - file_citation - - start_index - - end_index - MessageContentTextAnnotationsFilePathObject: - title: File path - type: object - description: >- - A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a - file. - properties: - type: - description: Always `file_path`. - type: string - enum: - - file_path - x-stainless-const: true - text: - description: The text in the message content that needs to be replaced. - type: string - file_path: - type: object - properties: - file_id: - description: The ID of the file that was generated. - type: string - required: - - file_id - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 - required: - - type - - text - - file_path - - start_index - - end_index - MessageContentTextObject: - title: Text - type: object - description: The text content that is part of a message. - properties: - type: - description: Always `text`. - type: string - enum: - - text - x-stainless-const: true - text: - type: object - properties: - value: - description: The data that makes up the text. - type: string - annotations: - type: array - items: - $ref: '#/components/schemas/TextAnnotation' - required: - - value - - annotations - required: - - type - - text - MessageDeltaContentImageFileObject: - title: Image file - type: object - description: >- - References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a - message. - properties: - index: - type: integer - description: The index of the content part in the message. - type: - description: Always `image_file`. - type: string - enum: - - image_file - x-stainless-const: true - image_file: - type: object - properties: - file_id: - description: >- - The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the - message content. Set `purpose="vision"` when uploading the File if you need to later display - the file content. - type: string - detail: - type: string - description: >- - Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you - can opt in to high resolution using `high`. - enum: - - auto - - low - - high - default: auto - required: - - index - - type - MessageDeltaContentImageUrlObject: - title: Image URL - type: object - description: References an image URL in the content of a message. - properties: - index: - type: integer - description: The index of the content part in the message. - type: - description: Always `image_url`. - type: string - enum: - - image_url - x-stainless-const: true - image_url: - type: object - properties: - url: - description: 'The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.' - type: string - detail: - type: string - description: >- - Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high - resolution using `high`. - enum: - - auto - - low - - high - default: auto - required: - - index - - type - MessageDeltaContentRefusalObject: - title: Refusal - type: object - description: The refusal content that is part of a message. - properties: - index: - type: integer - description: The index of the refusal part in the message. - type: - description: Always `refusal`. - type: string - enum: - - refusal - x-stainless-const: true - refusal: - type: string - required: - - index - - type - MessageDeltaContentTextAnnotationsFileCitationObject: - title: File citation - type: object - description: >- - A citation within the message that points to a specific quote from a specific File associated with the - assistant or the message. Generated when the assistant uses the "file_search" tool to search files. - properties: - index: - type: integer - description: The index of the annotation in the text content part. - type: - description: Always `file_citation`. - type: string - enum: - - file_citation - x-stainless-const: true - text: - description: The text in the message content that needs to be replaced. - type: string - file_citation: - type: object - properties: - file_id: - description: The ID of the specific File the citation is from. - type: string - quote: - description: The specific quote in the file. - type: string - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 - required: - - index - - type - MessageDeltaContentTextAnnotationsFilePathObject: - title: File path - type: object - description: >- - A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a - file. - properties: - index: - type: integer - description: The index of the annotation in the text content part. - type: - description: Always `file_path`. - type: string - enum: - - file_path - x-stainless-const: true - text: - description: The text in the message content that needs to be replaced. - type: string - file_path: - type: object - properties: - file_id: - description: The ID of the file that was generated. - type: string - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 - required: - - index - - type - MessageDeltaContentTextObject: - title: Text - type: object - description: The text content that is part of a message. - properties: - index: - type: integer - description: The index of the content part in the message. - type: - description: Always `text`. - type: string - enum: - - text - x-stainless-const: true - text: - type: object - properties: - value: - description: The data that makes up the text. - type: string - annotations: - type: array - items: - $ref: '#/components/schemas/TextAnnotationDelta' - required: - - index - - type - MessageDeltaObject: - type: object - title: Message delta object - description: | - Represents a message delta i.e. any changed fields on a message during streaming. - properties: - id: - description: The identifier of the message, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `thread.message.delta`. - type: string - enum: - - thread.message.delta - x-stainless-const: true - delta: - description: The delta containing the fields that have changed on the Message. - type: object - properties: - role: - description: The entity that produced the message. One of `user` or `assistant`. - type: string - enum: - - user - - assistant - content: - description: The content of the message in array of text and/or images. - type: array - items: - $ref: '#/components/schemas/MessageContentDelta' - required: - - id - - object - - delta - x-oaiMeta: - name: The message delta object - beta: true - example: | - { - "id": "msg_123", - "object": "thread.message.delta", - "delta": { - "content": [ - { - "index": 0, - "type": "text", - "text": { "value": "Hello", "annotations": [] } - } - ] - } - } - MessageObject: - type: object - title: The message object - description: Represents a message within a [thread](https://platform.openai.com/docs/api-reference/threads). - properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `thread.message`. - type: string - enum: - - thread.message - x-stainless-const: true - created_at: - description: The Unix timestamp (in seconds) for when the message was created. - type: integer - thread_id: - description: >- - The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs - to. - type: string - status: - description: The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. - type: string - enum: - - in_progress - - incomplete - - completed - incomplete_details: - anyOf: - - description: On an incomplete message, details about why the message is incomplete. - type: object - properties: - reason: - type: string - description: The reason the message is incomplete. - enum: - - content_filter - - max_tokens - - run_cancelled - - run_expired - - run_failed - required: - - reason - - type: 'null' - completed_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the message was completed. - type: integer - - type: 'null' - incomplete_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the message was marked as incomplete. - type: integer - - type: 'null' - role: - description: The entity that produced the message. One of `user` or `assistant`. - type: string - enum: - - user - - assistant - content: - description: The content of the message in array of text and/or images. - type: array - items: - $ref: '#/components/schemas/MessageContent' - assistant_id: - anyOf: - - description: >- - If applicable, the ID of the - [assistant](https://platform.openai.com/docs/api-reference/assistants) that authored this - message. - type: string - - type: 'null' - run_id: - anyOf: - - description: >- - The ID of the [run](https://platform.openai.com/docs/api-reference/runs) associated with the - creation of this message. Value is `null` when messages are created manually using the create - message or create thread endpoints. - type: string - - type: 'null' - attachments: - anyOf: - - type: array - items: - type: object - properties: - file_id: - type: string - description: The ID of the file to attach to the message. - tools: - description: The tools to add this file to. - type: array - items: - anyOf: - - $ref: '#/components/schemas/AssistantToolsCode' - - $ref: '#/components/schemas/AssistantToolsFileSearchTypeOnly' - description: A list of files attached to the message, and the tools they were added to. - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - required: - - id - - object - - created_at - - thread_id - - status - - incomplete_details - - completed_at - - incomplete_at - - role - - content - - assistant_id - - run_id - - attachments - - metadata - x-oaiMeta: - name: The message object - beta: true - example: | - { - "id": "msg_abc123", - "object": "thread.message", - "created_at": 1698983503, - "thread_id": "thread_abc123", - "role": "assistant", - "content": [ - { - "type": "text", - "text": { - "value": "Hi! How can I help you today?", - "annotations": [] - } - } - ], - "assistant_id": "asst_abc123", - "run_id": "run_abc123", - "attachments": [], - "metadata": {} - } - MessageRequestContentTextObject: - title: Text - type: object - description: The text content that is part of a message. - properties: - type: - description: Always `text`. - type: string - enum: - - text - x-stainless-const: true - text: - type: string - description: Text content to be sent to the model - required: - - type - - text - MessageStreamEvent: - anyOf: - - type: object - properties: - event: - type: string - enum: - - thread.message.created - x-stainless-const: true - data: - $ref: '#/components/schemas/MessageObject' - required: - - event - - data - description: >- - Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) is - created. - x-oaiMeta: - dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - - type: object - properties: - event: - type: string - enum: - - thread.message.in_progress - x-stainless-const: true - data: - $ref: '#/components/schemas/MessageObject' - required: - - event - - data - description: >- - Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) moves to - an `in_progress` state. - x-oaiMeta: - dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - - type: object - properties: - event: - type: string - enum: - - thread.message.delta - x-stainless-const: true - data: - $ref: '#/components/schemas/MessageDeltaObject' - required: - - event - - data - description: >- - Occurs when parts of a [Message](https://platform.openai.com/docs/api-reference/messages/object) - are being streamed. - x-oaiMeta: - dataDescription: '`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)' - - type: object - properties: - event: - type: string - enum: - - thread.message.completed - x-stainless-const: true - data: - $ref: '#/components/schemas/MessageObject' - required: - - event - - data - description: >- - Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) is - completed. - x-oaiMeta: - dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - - type: object - properties: - event: - type: string - enum: - - thread.message.incomplete - x-stainless-const: true - data: - $ref: '#/components/schemas/MessageObject' - required: - - event - - data - description: >- - Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) ends - before it is completed. - x-oaiMeta: - dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' - discriminator: - propertyName: event - Metadata: - anyOf: - - type: object - description: | - 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. - additionalProperties: - type: string - x-oaiTypeLabel: map - - type: 'null' - Model: - title: Model - description: Describes an OpenAI model offering that can be used with the API. - properties: - id: - type: string - description: The model identifier, which can be referenced in the API endpoints. - created: - type: integer - description: The Unix timestamp (in seconds) when the model was created. - object: - type: string - description: The object type, which is always "model". - enum: - - model - x-stainless-const: true - owned_by: - type: string - description: The organization that owns the model. - required: - - id - - object - - created - - owned_by - x-oaiMeta: - name: The model object - example: | - { - "id": "VAR_chat_model_id", - "object": "model", - "created": 1686935002, - "owned_by": "openai" - } - ModelIds: - anyOf: - - $ref: '#/components/schemas/ModelIdsShared' - - $ref: '#/components/schemas/ModelIdsResponses' - ModelIdsResponses: - example: gpt-4o - anyOf: - - $ref: '#/components/schemas/ModelIdsShared' - - type: string - title: ResponsesOnlyModel - enum: - - o1-pro - - o1-pro-2025-03-19 - - o3-pro - - o3-pro-2025-06-10 - - o3-deep-research - - o3-deep-research-2025-06-26 - - o4-mini-deep-research - - o4-mini-deep-research-2025-06-26 - - computer-use-preview - - computer-use-preview-2025-03-11 - - gpt-5-codex - - gpt-5-pro - - gpt-5-pro-2025-10-06 - ModelIdsShared: - example: gpt-4o - anyOf: - - type: string - - $ref: '#/components/schemas/ChatModel' - ModelResponseProperties: - type: object - properties: - metadata: - $ref: '#/components/schemas/Metadata' - top_logprobs: - anyOf: - - description: | - An integer between 0 and 20 specifying the number of most likely tokens to - return at each token position, each with an associated log probability. - type: integer - minimum: 0 - maximum: 20 - - type: 'null' - temperature: - anyOf: - - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - - We generally recommend altering this or `top_p` but not both. - - type: 'null' - top_p: - anyOf: - - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - description: | - An alternative to sampling with temperature, called nucleus sampling, - where the model considers the results of the tokens with top_p probability - mass. So 0.1 means only the tokens comprising the top 10% probability mass - are considered. - - We generally recommend altering this or `temperature` but not both. - - type: 'null' - user: - type: string - example: user-1234 - deprecated: true - description: > - This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` - instead to maintain caching optimizations. - - A stable identifier for your end-users. - - Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and - prevent abuse. [Learn - more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). - safety_identifier: - type: string - example: safety-identifier-1234 - description: > - A stable identifier used to help detect users of your application that may be violating OpenAI's - usage policies. - - The IDs should be a string that uniquely identifies each user. We recommend hashing their username - or email address, in order to avoid sending us any identifying information. [Learn - more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). - prompt_cache_key: - type: string - example: prompt-cache-key-1234 - description: > - Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces - the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching). - service_tier: - $ref: '#/components/schemas/ServiceTier' - prompt_cache_retention: - anyOf: - - type: string - enum: - - in-memory - - 24h - description: > - The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, - which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn - more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention). - - type: 'null' - ModifyAssistantRequest: - type: object - additionalProperties: false - properties: - model: - description: > - ID of the model to use. You can use the [List - models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your - available models, or see our [Model overview](https://platform.openai.com/docs/models) for - descriptions of them. - anyOf: - - type: string - - $ref: '#/components/schemas/AssistantSupportedModels' - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - name: - anyOf: - - description: | - The name of the assistant. The maximum length is 256 characters. - type: string - maxLength: 256 - - type: 'null' - description: - anyOf: - - description: | - The description of the assistant. The maximum length is 512 characters. - type: string - maxLength: 512 - - type: 'null' - instructions: - anyOf: - - description: | - The system instructions that the assistant uses. The maximum length is 256,000 characters. - type: string - maxLength: 256000 - - type: 'null' - tools: - description: > - A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools - can be of types `code_interpreter`, `file_search`, or `function`. - default: [] - type: array - maxItems: 128 - items: - $ref: '#/components/schemas/AssistantTool' - tool_resources: - anyOf: - - type: object - description: > - A set of resources that are used by the assistant's tools. The resources are specific to the - type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the - `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs - made available to the `code_interpreter` tool. There can be a maximum of 20 files - associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - Overrides the [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached - to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - anyOf: - - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - - type: 'null' - top_p: - anyOf: - - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - - We generally recommend altering this or temperature but not both. - - type: 'null' - response_format: - anyOf: - - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - - type: 'null' - ModifyCertificateRequest: - type: object - properties: - name: - type: string - description: The updated name for the certificate - required: - - name - ModifyMessageRequest: - type: object - additionalProperties: false - properties: - metadata: - $ref: '#/components/schemas/Metadata' - ModifyRunRequest: - type: object - additionalProperties: false - properties: - metadata: - $ref: '#/components/schemas/Metadata' - ModifyThreadRequest: - type: object - additionalProperties: false - properties: - tool_resources: - anyOf: - - type: object - description: > - A set of resources that are made available to the assistant's tools in this thread. The - resources are specific to the type of tool. For example, the `code_interpreter` tool requires - a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - available to the `code_interpreter` tool. There can be a maximum of 20 files - associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached - to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: string - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - Move: - type: object - title: Move - description: | - A mouse move action. - properties: - type: - type: string - enum: - - move - default: move - description: | - Specifies the event type. For a move action, this property is - always set to `move`. - x-stainless-const: true - x: - type: integer - description: | - The x-coordinate to move to. - 'y': - type: integer - description: | - The y-coordinate to move to. - required: - - type - - x - - 'y' - NoiseReductionType: - type: string - enum: - - near_field - - far_field - description: > - 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. - OpenAIFile: - title: OpenAIFile - description: The `File` object represents a document that has been uploaded to OpenAI. - properties: - id: - type: string - description: The file identifier, which can be referenced in the API endpoints. - bytes: - type: integer - description: The size of the file, in bytes. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the file was created. - expires_at: - type: integer - description: The Unix timestamp (in seconds) for when the file will expire. - filename: - type: string - description: The name of the file. - object: - type: string - description: The object type, which is always `file`. - enum: - - file - x-stainless-const: true - purpose: - type: string - description: >- - The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, - `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`. - enum: - - assistants - - assistants_output - - batch - - batch_output - - fine-tune - - fine-tune-results - - vision - - user_data - status: - type: string - deprecated: true - description: >- - Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or - `error`. - enum: - - uploaded - - processed - - error - status_details: - type: string - deprecated: true - description: >- - Deprecated. For details on why a fine-tuning training file failed validation, see the `error` - field on `fine_tuning.job`. - required: - - id - - object - - bytes - - created_at - - filename - - purpose - - status - x-oaiMeta: - name: The file object - example: | - { - "id": "file-abc123", - "object": "file", - "bytes": 120000, - "created_at": 1677610602, - "expires_at": 1680202602, - "filename": "salesOverview.pdf", - "purpose": "assistants", - } - OtherChunkingStrategyResponseParam: - type: object - title: Other Chunking Strategy - description: >- - This is returned when the chunking strategy is unknown. Typically, this is because the file was - indexed before the `chunking_strategy` concept was introduced in the API. - additionalProperties: false - properties: - type: - type: string - description: Always `other`. - enum: - - other - x-stainless-const: true - required: - - type - OutputAudio: - type: object - title: Output audio - description: | - An audio output from the model. - properties: - type: - type: string - description: | - The type of the output audio. Always `output_audio`. - enum: - - output_audio - x-stainless-const: true - data: - type: string - description: | - Base64-encoded audio data from the model. - transcript: - type: string - description: | - The transcript of the audio data from the model. - required: - - type - - data - - transcript - OutputContent: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/OutputTextContent' - - $ref: '#/components/schemas/RefusalContent' - - $ref: '#/components/schemas/ReasoningTextContent' - OutputItem: - anyOf: - - $ref: '#/components/schemas/OutputMessage' - - $ref: '#/components/schemas/FileSearchToolCall' - - $ref: '#/components/schemas/FunctionToolCall' - - $ref: '#/components/schemas/WebSearchToolCall' - - $ref: '#/components/schemas/ComputerToolCall' - - $ref: '#/components/schemas/ReasoningItem' - - $ref: '#/components/schemas/ImageGenToolCall' - - $ref: '#/components/schemas/CodeInterpreterToolCall' - - $ref: '#/components/schemas/LocalShellToolCall' - - $ref: '#/components/schemas/FunctionShellCall' - - $ref: '#/components/schemas/FunctionShellCallOutput' - - $ref: '#/components/schemas/ApplyPatchToolCall' - - $ref: '#/components/schemas/ApplyPatchToolCallOutput' - - $ref: '#/components/schemas/MCPToolCall' - - $ref: '#/components/schemas/MCPListTools' - - $ref: '#/components/schemas/MCPApprovalRequest' - - $ref: '#/components/schemas/CustomToolCall' - discriminator: - propertyName: type - OutputMessage: - type: object - title: Output message - description: | - An output message from the model. - properties: - id: - type: string - description: | - The unique ID of the output message. - x-stainless-go-json: omitzero - type: - type: string - description: | - The type of the output message. Always `message`. - enum: - - message - x-stainless-const: true - role: - type: string - description: | - The role of the output message. Always `assistant`. - enum: - - assistant - x-stainless-const: true - content: - type: array - description: | - The content of the output message. - items: - $ref: '#/components/schemas/OutputMessageContent' - status: - type: string - description: | - The status of the message input. One of `in_progress`, `completed`, or - `incomplete`. Populated when input items are returned via API. - enum: - - in_progress - - completed - - incomplete - required: - - id - - type - - role - - content - - status - OutputMessageContent: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/OutputTextContent' - - $ref: '#/components/schemas/RefusalContent' - ParallelToolCalls: - description: >- - Whether to enable [parallel function - calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) - during tool use. - type: boolean - default: true - PartialImages: - anyOf: - - type: integer - maximum: 3 - minimum: 0 - default: 0 - example: 1 - description: | - The number of partial images to generate. This parameter is used for - streaming responses that return partial images. Value must be between 0 and 3. - When set to 0, the response will be a single image sent in one streaming event. - - Note that the final image may be sent before the full number of partial images - are generated if the full image is generated more quickly. - - type: 'null' - PredictionContent: - type: object - title: Static Content - description: | - Static predicted output content, such as the content of a text file that is - being regenerated. - required: - - type - - content - properties: - type: - type: string - enum: - - content - description: | - The type of the predicted content you want to provide. This type is - currently always `content`. - x-stainless-const: true - content: - description: | - The content that should be matched when generating a model response. - If generated tokens would match this content, the entire model response - can be returned much more quickly. - anyOf: - - type: string - title: Text content - description: | - The content used for a Predicted Output. This is often the - text of a file you are regenerating with minor changes. - - type: array - description: >- - An array of content parts with a defined type. Supported options differ based on the - [model](https://platform.openai.com/docs/models) being used to generate the response. Can - contain text inputs. - title: Array of content parts - items: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - minItems: 1 - Project: - type: object - description: Represents an individual project. - properties: - id: - type: string - description: The identifier, which can be referenced in API endpoints - object: - type: string - enum: - - organization.project - description: The object type, which is always `organization.project` - x-stainless-const: true - name: - type: string - description: The name of the project. This appears in reporting. - created_at: - type: integer - description: The Unix timestamp (in seconds) of when the project was created. - archived_at: - anyOf: - - type: integer - description: The Unix timestamp (in seconds) of when the project was archived or `null`. - - type: 'null' - status: - type: string - enum: - - active - - archived - description: '`active` or `archived`' - required: - - id - - object - - name - - created_at - - status - x-oaiMeta: - name: The project object - example: | - { - "id": "proj_abc", - "object": "organization.project", - "name": "Project example", - "created_at": 1711471533, - "archived_at": null, - "status": "active" - } - ProjectApiKey: - type: object - description: Represents an individual API key in a project. - properties: - object: - type: string - enum: - - organization.project.api_key - description: The object type, which is always `organization.project.api_key` - x-stainless-const: true - redacted_value: - type: string - description: The redacted value of the API key - name: - type: string - description: The name of the API key - created_at: - type: integer - description: The Unix timestamp (in seconds) of when the API key was created - last_used_at: - type: integer - description: The Unix timestamp (in seconds) of when the API key was last used. - id: - type: string - description: The identifier, which can be referenced in API endpoints - owner: - type: object - properties: - type: - type: string - enum: - - user - - service_account - description: '`user` or `service_account`' - user: - $ref: '#/components/schemas/ProjectUser' - service_account: - $ref: '#/components/schemas/ProjectServiceAccount' - required: - - object - - redacted_value - - name - - created_at - - last_used_at - - id - - owner - x-oaiMeta: - name: The project API key object - example: | - { - "object": "organization.project.api_key", - "redacted_value": "sk-abc...def", - "name": "My API Key", - "created_at": 1711471533, - "last_used_at": 1711471534, - "id": "key_abc", - "owner": { - "type": "user", - "user": { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "created_at": 1711471533 - } - } - } - ProjectApiKeyDeleteResponse: - type: object - properties: - object: - type: string - enum: - - organization.project.api_key.deleted - x-stainless-const: true - id: - type: string - deleted: - type: boolean - required: - - object - - id - - deleted - ProjectApiKeyListResponse: - type: object - properties: - object: - type: string - enum: - - list - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/ProjectApiKey' - first_id: - type: string - last_id: - type: string - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - ProjectCreateRequest: - type: object - properties: - name: - type: string - description: The friendly name of the project, this name appears in reports. - geography: - type: string - enum: - - US - - EU - - JP - - IN - - KR - - CA - - AU - - SG - description: >- - Create the project with the specified data residency region. Your organization must have access to - Data residency functionality in order to use. See [data residency - controls](https://platform.openai.com/docs/guides/your-data#data-residency-controls) to review the - functionality and limitations of setting this field. - required: - - name - ProjectGroup: - type: object - description: Details about a group's membership in a project. - properties: - object: - type: string - enum: - - project.group - description: Always `project.group`. - x-stainless-const: true - project_id: - type: string - description: Identifier of the project. - group_id: - type: string - description: Identifier of the group that has access to the project. - group_name: - type: string - description: Display name of the group. - created_at: - type: integer - format: int64 - description: Unix timestamp (in seconds) when the group was granted project access. - required: - - object - - project_id - - group_id - - group_name - - created_at - x-oaiMeta: - name: The project group object - example: | - { - "object": "project.group", - "project_id": "proj_abc123", - "group_id": "group_01J1F8ABCDXYZ", - "group_name": "Support Team", - "created_at": 1711471533 - } - ProjectGroupDeletedResource: - type: object - description: Confirmation payload returned after removing a group from a project. - properties: - object: - type: string - enum: - - project.group.deleted - description: Always `project.group.deleted`. - x-stainless-const: true - deleted: - type: boolean - description: Whether the group membership in the project was removed. - required: - - object - - deleted - x-oaiMeta: - name: Project group deletion confirmation - example: | - { - "object": "project.group.deleted", - "deleted": true - } - ProjectGroupListResource: - type: object - description: Paginated list of groups that have access to a project. - properties: - object: - type: string - enum: - - list - description: Always `list`. - x-stainless-const: true - data: - type: array - description: Project group memberships returned in the current page. - items: - $ref: '#/components/schemas/ProjectGroup' - has_more: - type: boolean - description: Whether additional project group memberships are available. - next: - description: Cursor to fetch the next page of results, or `null` when there are no more results. - anyOf: - - type: string - - type: 'null' - required: - - object - - data - - has_more - - next - x-oaiMeta: - name: Project group list - example: | - { - "object": "list", - "data": [ - { - "object": "project.group", - "project_id": "proj_abc123", - "group_id": "group_01J1F8ABCDXYZ", - "group_name": "Support Team", - "created_at": 1711471533 - } - ], - "has_more": false, - "next": null - } - ProjectListResponse: - type: object - properties: - object: - type: string - enum: - - list - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/Project' - first_id: - type: string - last_id: - type: string - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - ProjectRateLimit: - type: object - description: Represents a project rate limit config. - properties: - object: - type: string - enum: - - project.rate_limit - description: The object type, which is always `project.rate_limit` - x-stainless-const: true - id: - type: string - description: The identifier, which can be referenced in API endpoints. - model: - type: string - description: The model this rate limit applies to. - max_requests_per_1_minute: - type: integer - description: The maximum requests per minute. - max_tokens_per_1_minute: - type: integer - description: The maximum tokens per minute. - max_images_per_1_minute: - type: integer - description: The maximum images per minute. Only present for relevant models. - max_audio_megabytes_per_1_minute: - type: integer - description: The maximum audio megabytes per minute. Only present for relevant models. - max_requests_per_1_day: - type: integer - description: The maximum requests per day. Only present for relevant models. - batch_1_day_max_input_tokens: - type: integer - description: The maximum batch input tokens per day. Only present for relevant models. - required: - - object - - id - - model - - max_requests_per_1_minute - - max_tokens_per_1_minute - x-oaiMeta: - name: The project rate limit object - example: | - { - "object": "project.rate_limit", - "id": "rl_ada", - "model": "ada", - "max_requests_per_1_minute": 600, - "max_tokens_per_1_minute": 150000, - "max_images_per_1_minute": 10 - } - ProjectRateLimitListResponse: - type: object - properties: - object: - type: string - enum: - - list - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/ProjectRateLimit' - first_id: - type: string - last_id: - type: string - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - ProjectRateLimitUpdateRequest: - type: object - properties: - max_requests_per_1_minute: - type: integer - description: The maximum requests per minute. - max_tokens_per_1_minute: - type: integer - description: The maximum tokens per minute. - max_images_per_1_minute: - type: integer - description: The maximum images per minute. Only relevant for certain models. - max_audio_megabytes_per_1_minute: - type: integer - description: The maximum audio megabytes per minute. Only relevant for certain models. - max_requests_per_1_day: - type: integer - description: The maximum requests per day. Only relevant for certain models. - batch_1_day_max_input_tokens: - type: integer - description: The maximum batch input tokens per day. Only relevant for certain models. - ProjectServiceAccount: - type: object - description: Represents an individual service account in a project. - properties: - object: - type: string - enum: - - organization.project.service_account - description: The object type, which is always `organization.project.service_account` - x-stainless-const: true - id: - type: string - description: The identifier, which can be referenced in API endpoints - name: - type: string - description: The name of the service account - role: - type: string - enum: - - owner - - member - description: '`owner` or `member`' - created_at: - type: integer - description: The Unix timestamp (in seconds) of when the service account was created - required: - - object - - id - - name - - role - - created_at - x-oaiMeta: - name: The project service account object - example: | - { - "object": "organization.project.service_account", - "id": "svc_acct_abc", - "name": "Service Account", - "role": "owner", - "created_at": 1711471533 - } - ProjectServiceAccountApiKey: - type: object - properties: - object: - type: string - enum: - - organization.project.service_account.api_key - description: The object type, which is always `organization.project.service_account.api_key` - x-stainless-const: true - value: - type: string - name: - type: string - created_at: - type: integer - id: - type: string - required: - - object - - value - - name - - created_at - - id - ProjectServiceAccountCreateRequest: - type: object - properties: - name: - type: string - description: The name of the service account being created. - required: - - name - ProjectServiceAccountCreateResponse: - type: object - properties: - object: - type: string - enum: - - organization.project.service_account - x-stainless-const: true - id: - type: string - name: - type: string - role: - type: string - enum: - - member - description: Service accounts can only have one role of type `member` - x-stainless-const: true - created_at: - type: integer - api_key: - $ref: '#/components/schemas/ProjectServiceAccountApiKey' - required: - - object - - id - - name - - role - - created_at - - api_key - ProjectServiceAccountDeleteResponse: - type: object - properties: - object: - type: string - enum: - - organization.project.service_account.deleted - x-stainless-const: true - id: - type: string - deleted: - type: boolean - required: - - object - - id - - deleted - ProjectServiceAccountListResponse: - type: object - properties: - object: - type: string - enum: - - list - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/ProjectServiceAccount' - first_id: - type: string - last_id: - type: string - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - ProjectUpdateRequest: - type: object - properties: - name: - type: string - description: The updated name of the project, this name appears in reports. - required: - - name - ProjectUser: - type: object - description: Represents an individual user in a project. - properties: - object: - type: string - enum: - - organization.project.user - description: The object type, which is always `organization.project.user` - x-stainless-const: true - id: - type: string - description: The identifier, which can be referenced in API endpoints - name: - type: string - description: The name of the user - email: - type: string - description: The email address of the user - role: - type: string - enum: - - owner - - member - description: '`owner` or `member`' - added_at: - type: integer - description: The Unix timestamp (in seconds) of when the project was added. - required: - - object - - id - - name - - email - - role - - added_at - x-oaiMeta: - name: The project user object - example: | - { - "object": "organization.project.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 - } - ProjectUserCreateRequest: - type: object - properties: - user_id: - type: string - description: The ID of the user. - role: - type: string - enum: - - owner - - member - description: '`owner` or `member`' - required: - - user_id - - role - ProjectUserDeleteResponse: - type: object - properties: - object: - type: string - enum: - - organization.project.user.deleted - x-stainless-const: true - id: - type: string - deleted: - type: boolean - required: - - object - - id - - deleted - ProjectUserListResponse: - type: object - properties: - object: - type: string - data: - type: array - items: - $ref: '#/components/schemas/ProjectUser' - first_id: - type: string - last_id: - type: string - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - ProjectUserUpdateRequest: - type: object - properties: - role: - type: string - enum: - - owner - - member - description: '`owner` or `member`' - required: - - role - Prompt: - anyOf: - - type: object - description: | - Reference to a prompt template and its variables. - [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). - required: - - id - properties: - id: - type: string - description: The unique identifier of the prompt template to use. - version: - anyOf: - - type: string - description: Optional version of the prompt template. - - type: 'null' - variables: - $ref: '#/components/schemas/ResponsePromptVariables' - - type: 'null' - PublicAssignOrganizationGroupRoleBody: - type: object - description: Request payload for assigning a role to a group or user. - properties: - role_id: - type: string - description: Identifier of the role to assign. - required: - - role_id - x-oaiMeta: - example: | - { - "role_id": "role_01J1F8ROLE01" - } - PublicCreateOrganizationRoleBody: - type: object - description: Request payload for creating a custom role. - properties: - role_name: - type: string - description: Unique name for the role. - permissions: - type: array - description: Permissions to grant to the role. - items: - type: string - description: - description: Optional description of the role. - anyOf: - - type: string - - type: 'null' - required: - - role_name - - permissions - x-oaiMeta: - example: | - { - "role_name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "description": "Allows managing organization groups" - } - PublicRoleListResource: - type: object - description: Paginated list of roles available on an organization or project. - properties: - object: - type: string - enum: - - list - description: Always `list`. - x-stainless-const: true - data: - type: array - description: Roles returned in the current page. - items: - $ref: '#/components/schemas/Role' - has_more: - type: boolean - description: Whether more roles are available when paginating. - next: - description: Cursor to fetch the next page of results, or `null` when there are no additional roles. - anyOf: - - type: string - - type: 'null' - required: - - object - - data - - has_more - - next - x-oaiMeta: - name: Role list - example: | - { - "object": "list", - "data": [ - { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - ], - "has_more": false, - "next": null - } - PublicUpdateOrganizationRoleBody: - type: object - description: Request payload for updating an existing role. - properties: - permissions: - description: Updated set of permissions for the role. - anyOf: - - type: array - items: - type: string - - type: 'null' - description: - description: New description for the role. - anyOf: - - type: string - - type: 'null' - role_name: - description: New name for the role. - anyOf: - - type: string - - type: 'null' - x-oaiMeta: - example: | - { - "role_name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "description": "Allows managing organization groups" - } - RealtimeAudioFormats: - anyOf: - - type: object - title: PCM audio format - description: The PCM audio format. Only a 24kHz sample rate is supported. - properties: - type: - type: string - description: The audio format. Always `audio/pcm`. - enum: - - audio/pcm - rate: - type: integer - description: The sample rate of the audio. Always `24000`. - enum: - - 24000 - - type: object - title: PCMU audio format - description: The G.711 μ-law format. - properties: - type: - type: string - description: The audio format. Always `audio/pcmu`. - enum: - - audio/pcmu - - type: object - title: PCMA audio format - description: The G.711 A-law format. - properties: - type: - type: string - description: The audio format. Always `audio/pcma`. - enum: - - audio/pcma - discriminator: - propertyName: type - RealtimeBetaClientEventConversationItemCreate: - type: object - description: | - Add a new Item to the Conversation's context, including messages, function - calls, and function call responses. This event can be used both to populate a - "history" of the conversation and to add new items mid-stream, but has the - current limitation that it cannot populate assistant audio messages. - - If successful, the server will respond with a `conversation.item.created` - event, otherwise an `error` event will be sent. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.create`. - x-stainless-const: true - const: conversation.item.create - previous_item_id: - type: string - description: | - The ID of the preceding item after which the new item will be inserted. - If not set, the new item will be appended to the end of the conversation. - If set to `root`, the new item will be added to the beginning of the conversation. - If set to an existing ID, it allows an item to be inserted mid-conversation. If the - ID cannot be found, an error will be returned and the item will not be added. - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - type - - item - x-oaiMeta: - name: conversation.item.create - group: realtime - example: | - { - "type": "conversation.item.create", - "item": { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hi" - } - ] - }, - "event_id": "b904fba0-0ec4-40af-8bbb-f908a9b26793", - } - RealtimeBetaClientEventConversationItemDelete: - type: object - description: | - Send this event when you want to remove any item from the conversation - history. The server will respond with a `conversation.item.deleted` event, - unless the item does not exist in the conversation history, in which case the - server will respond with an error. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.delete`. - x-stainless-const: true - const: conversation.item.delete - item_id: - type: string - description: The ID of the item to delete. - required: - - type - - item_id - x-oaiMeta: - name: conversation.item.delete - group: realtime - example: | - { - "event_id": "event_901", - "type": "conversation.item.delete", - "item_id": "msg_003" - } - RealtimeBetaClientEventConversationItemRetrieve: - type: object - description: > - Send this event when you want to retrieve the server's representation of a specific item in the - conversation history. This is useful, for example, to inspect user audio after noise cancellation and - VAD. - - The server will respond with a `conversation.item.retrieved` event, - - unless the item does not exist in the conversation history, in which case the - - server will respond with an error. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.retrieve`. - x-stainless-const: true - const: conversation.item.retrieve - item_id: - type: string - description: The ID of the item to retrieve. - required: - - type - - item_id - x-oaiMeta: - name: conversation.item.retrieve - group: realtime - example: | - { - "event_id": "event_901", - "type": "conversation.item.retrieve", - "item_id": "msg_003" - } - RealtimeBetaClientEventConversationItemTruncate: - type: object - description: | - Send this event to truncate a previous assistant message’s audio. The server - will produce audio faster than realtime, so this event is useful when the user - interrupts to truncate audio that has already been sent to the client but not - yet played. This will synchronize the server's understanding of the audio with - the client's playback. - - Truncating audio will delete the server-side text transcript to ensure there - is not text in the context that hasn't been heard by the user. - - If successful, the server will respond with a `conversation.item.truncated` - event. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.truncate`. - x-stainless-const: true - const: conversation.item.truncate - item_id: - type: string - description: | - The ID of the assistant message item to truncate. Only assistant message - items can be truncated. - content_index: - type: integer - description: The index of the content part to truncate. Set this to 0. - audio_end_ms: - type: integer - description: | - Inclusive duration up to which audio is truncated, in milliseconds. If - the audio_end_ms is greater than the actual audio duration, the server - will respond with an error. - required: - - type - - item_id - - content_index - - audio_end_ms - x-oaiMeta: - name: conversation.item.truncate - group: realtime - example: | - { - "event_id": "event_678", - "type": "conversation.item.truncate", - "item_id": "msg_002", - "content_index": 0, - "audio_end_ms": 1500 - } - RealtimeBetaClientEventInputAudioBufferAppend: - type: object - description: | - Send this event to append audio bytes to the input audio buffer. The audio - buffer is temporary storage you can write to and later commit. In Server VAD - mode, the audio buffer is used to detect speech and the server will decide - when to commit. When Server VAD is disabled, you must commit the audio buffer - manually. - - The client may choose how much audio to place in each event up to a maximum - of 15 MiB, for example streaming smaller chunks from the client may allow the - VAD to be more responsive. Unlike made other client events, the server will - not send a confirmation response to this event. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `input_audio_buffer.append`. - x-stainless-const: true - const: input_audio_buffer.append - audio: - type: string - description: | - Base64-encoded audio bytes. This must be in the format specified by the - `input_audio_format` field in the session configuration. - required: - - type - - audio - x-oaiMeta: - name: input_audio_buffer.append - group: realtime - example: | - { - "event_id": "event_456", - "type": "input_audio_buffer.append", - "audio": "Base64EncodedAudioData" - } - RealtimeBetaClientEventInputAudioBufferClear: - type: object - description: | - Send this event to clear the audio bytes in the buffer. The server will - respond with an `input_audio_buffer.cleared` event. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `input_audio_buffer.clear`. - x-stainless-const: true - const: input_audio_buffer.clear - required: - - type - x-oaiMeta: - name: input_audio_buffer.clear - group: realtime - example: | - { - "event_id": "event_012", - "type": "input_audio_buffer.clear" - } - RealtimeBetaClientEventInputAudioBufferCommit: - type: object - description: | - Send this event to commit the user input audio buffer, which will create a - new user message item in the conversation. This event will produce an error - if the input audio buffer is empty. When in Server VAD mode, the client does - not need to send this event, the server will commit the audio buffer - automatically. - - Committing the input audio buffer will trigger input audio transcription - (if enabled in session configuration), but it will not create a response - from the model. The server will respond with an `input_audio_buffer.committed` - event. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `input_audio_buffer.commit`. - x-stainless-const: true - const: input_audio_buffer.commit - required: - - type - x-oaiMeta: - name: input_audio_buffer.commit - group: realtime - example: | - { - "event_id": "event_789", - "type": "input_audio_buffer.commit" - } - RealtimeBetaClientEventOutputAudioBufferClear: - type: object - description: > - **WebRTC Only:** Emit to cut off the current audio response. This will trigger the server to - - stop generating audio and emit a `output_audio_buffer.cleared` event. This - - event should be preceded by a `response.cancel` client event to stop the - - generation of the current response. - - [Learn - more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). - properties: - event_id: - type: string - description: The unique ID of the client event used for error handling. - type: - description: The event type, must be `output_audio_buffer.clear`. - x-stainless-const: true - const: output_audio_buffer.clear - required: - - type - x-oaiMeta: - name: output_audio_buffer.clear - group: realtime - example: | - { - "event_id": "optional_client_event_id", - "type": "output_audio_buffer.clear" - } - RealtimeBetaClientEventResponseCancel: - type: object - description: | - Send this event to cancel an in-progress response. The server will respond - with a `response.done` event with a status of `response.status=cancelled`. If - there is no response to cancel, the server will respond with an error. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `response.cancel`. - x-stainless-const: true - const: response.cancel - response_id: - type: string - description: | - A specific response ID to cancel - if not provided, will cancel an - in-progress response in the default conversation. - required: - - type - x-oaiMeta: - name: response.cancel - group: realtime - example: | - { - "event_id": "event_567", - "type": "response.cancel" - } - RealtimeBetaClientEventResponseCreate: - type: object - description: | - This event instructs the server to create a Response, which means triggering - model inference. When in Server VAD mode, the server will create Responses - automatically. - - A Response will include at least one Item, and may have two, in which case - the second will be a function call. These Items will be appended to the - conversation history. - - The server will respond with a `response.created` event, events for Items - and content created, and finally a `response.done` event to indicate the - Response is complete. - - The `response.create` event can optionally include inference configuration like - `instructions`, and `temperature`. These fields will override the Session's - configuration for this Response only. - - Responses can be created out-of-band of the default Conversation, meaning that they can - have arbitrary input, and it's possible to disable writing the output to the Conversation. - Only one Response can write to the default Conversation at a time, but otherwise multiple - Responses can be created in parallel. - - Clients can set `conversation` to `none` to create a Response that does not write to the default - Conversation. Arbitrary input can be provided with the `input` field, which is an array accepting - raw Items and references to existing Items. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `response.create`. - x-stainless-const: true - const: response.create - response: - $ref: '#/components/schemas/RealtimeBetaResponseCreateParams' - required: - - type - x-oaiMeta: - name: response.create - group: realtime - example: | - // Trigger a response with the default Conversation and no special parameters - { - "type": "response.create", - } - - // Trigger an out-of-band response that does not write to the default Conversation - { - "type": "response.create", - "response": { - "instructions": "Provide a concise answer.", - "tools": [], // clear any session tools - "conversation": "none", - "output_modalities": ["text"], - "input": [ - { - "type": "item_reference", - "id": "item_12345", - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "Summarize the above message in one sentence." - } - ] - } - ], - } - } - RealtimeBetaClientEventSessionUpdate: - type: object - description: | - Send this event to update the session’s default configuration. - The client may send this event at any time to update any field, - except for `voice`. However, note that once a session has been - initialized with a particular `model`, it can’t be changed to - another model using `session.update`. - - When the server receives a `session.update`, it will respond - with a `session.updated` event showing the full, effective configuration. - Only the fields that are present are updated. To clear a field like - `instructions`, pass an empty string. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `session.update`. - x-stainless-const: true - const: session.update - session: - $ref: '#/components/schemas/RealtimeSessionCreateRequest' - required: - - type - - session - x-oaiMeta: - name: session.update - group: realtime - example: | - { - "type": "session.update", - "session": { - "tools": [ - { - "type": "function", - "name": "display_color_palette", - "description": "\nCall this function when a user asks for a color palette.\n", - "parameters": { - "type": "object", - "strict": true, - "properties": { - "theme": { - "type": "string", - "description": "Description of the theme for the color scheme." - }, - "colors": { - "type": "array", - "description": "Array of five hex color codes based on the theme.", - "items": { - "type": "string", - "description": "Hex color code" - } - } - }, - "required": [ - "theme", - "colors" - ] - } - } - ], - "tool_choice": "auto" - }, - "event_id": "5fc543c4-f59c-420f-8fb9-68c45d1546a7", - "timestamp": "2:30:32 PM" - } - RealtimeBetaClientEventTranscriptionSessionUpdate: - type: object - description: | - Send this event to update a transcription session. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `transcription_session.update`. - x-stainless-const: true - const: transcription_session.update - session: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' - required: - - type - - session - x-oaiMeta: - name: transcription_session.update - group: realtime - example: | - { - "type": "transcription_session.update", - "session": { - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "prompt": "", - "language": "" - }, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 500, - "create_response": true, - }, - "input_audio_noise_reduction": { - "type": "near_field" - }, - "include": [ - "item.input_audio_transcription.logprobs", - ] - } - } - RealtimeBetaResponse: - type: object - description: The response resource. - properties: - id: - type: string - description: The unique ID of the response. - object: - description: The object type, must be `realtime.response`. - x-stainless-const: true - const: realtime.response - status: - type: string - enum: - - completed - - cancelled - - failed - - incomplete - - in_progress - description: | - The final status of the response (`completed`, `cancelled`, `failed`, or - `incomplete`, `in_progress`). - status_details: - type: object - description: Additional details about the status. - properties: - type: - type: string - enum: - - completed - - cancelled - - incomplete - - failed - description: | - The type of error that caused the response to fail, corresponding - with the `status` field (`completed`, `cancelled`, `incomplete`, - `failed`). - reason: - type: string - enum: - - turn_detected - - client_cancelled - - max_output_tokens - - content_filter - description: | - The reason the Response did not complete. For a `cancelled` Response, - one of `turn_detected` (the server VAD detected a new start of speech) - or `client_cancelled` (the client sent a cancel event). For an - `incomplete` Response, one of `max_output_tokens` or `content_filter` - (the server-side safety filter activated and cut off the response). - error: - type: object - description: | - A description of the error that caused the response to fail, - populated when the `status` is `failed`. - properties: - type: - type: string - description: The type of error. - code: - type: string - description: Error code, if any. - output: - type: array - description: The list of output items generated by the response. - items: - $ref: '#/components/schemas/RealtimeConversationItem' - metadata: - $ref: '#/components/schemas/Metadata' - usage: - type: object - description: | - Usage statistics for the Response, this will correspond to billing. A - Realtime API session will maintain a conversation context and append new - Items to the Conversation, thus output from previous turns (text and - audio tokens) will become the input for later turns. - properties: - total_tokens: - type: integer - description: | - The total number of tokens in the Response including input and output - text and audio tokens. - input_tokens: - type: integer - description: | - The number of input tokens used in the Response, including text and - audio tokens. - output_tokens: - type: integer - description: | - The number of output tokens sent in the Response, including text and - audio tokens. - input_token_details: - type: object - description: Details about the input tokens used in the Response. - properties: - cached_tokens: - type: integer - description: The number of cached tokens used as input for the Response. - text_tokens: - type: integer - description: The number of text tokens used as input for the Response. - image_tokens: - type: integer - description: The number of image tokens used as input for the Response. - audio_tokens: - type: integer - description: The number of audio tokens used as input for the Response. - cached_tokens_details: - type: object - description: Details about the cached tokens used as input for the Response. - properties: - text_tokens: - type: integer - description: The number of cached text tokens used as input for the Response. - image_tokens: - type: integer - description: The number of cached image tokens used as input for the Response. - audio_tokens: - type: integer - description: The number of cached audio tokens used as input for the Response. - output_token_details: - type: object - description: Details about the output tokens used in the Response. - properties: - text_tokens: - type: integer - description: The number of text tokens used in the Response. - audio_tokens: - type: integer - description: The number of audio tokens used in the Response. - conversation_id: - description: | - Which conversation the response is added to, determined by the `conversation` - field in the `response.create` event. If `auto`, the response will be added to - the default conversation and the value of `conversation_id` will be an id like - `conv_1234`. If `none`, the response will not be added to any conversation and - the value of `conversation_id` will be `null`. If responses are being triggered - by server VAD, the response will be added to the default conversation, thus - the `conversation_id` will be an id like `conv_1234`. - type: string - voice: - $ref: '#/components/schemas/VoiceIdsShared' - description: | - The voice the model used to respond. - Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, - `shimmer`, and `verse`. - modalities: - type: array - description: | - The set of modalities the model used to respond. If there are multiple modalities, - the model will pick one, for example if `modalities` is `["text", "audio"]`, the model - could be responding in either text or audio. - items: - type: string - enum: - - text - - audio - output_audio_format: - type: string - enum: - - pcm16 - - g711_ulaw - - g711_alaw - description: | - The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. - temperature: - type: number - description: | - Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. - max_output_tokens: - description: | - Maximum number of output tokens for a single assistant response, - inclusive of tool calls, that was used in this response. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - RealtimeBetaResponseCreateParams: - type: object - description: Create a new Realtime response with these parameters - properties: - modalities: - type: array - description: | - The set of modalities the model can respond with. To disable audio, - set this to ["text"]. - items: - type: string - enum: - - text - - audio - instructions: - type: string - description: | - 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. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - description: | - 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`, and `verse`. - output_audio_format: - type: string - enum: - - pcm16 - - g711_ulaw - - g711_alaw - description: | - The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. - tools: - type: array - description: Tools (functions) available to the model. - items: - type: object - properties: - type: - type: string - enum: - - function - description: The type of the tool, i.e. `function`. - x-stainless-const: true - name: - type: string - description: The name of the function. - description: - type: string - description: | - 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). - parameters: - type: object - description: Parameters of the function in JSON Schema. - tool_choice: - description: | - How the model chooses tools. Provide one of the string modes or force a specific - function/MCP tool. - default: auto - anyOf: - - $ref: '#/components/schemas/ToolChoiceOptions' - - $ref: '#/components/schemas/ToolChoiceFunction' - - $ref: '#/components/schemas/ToolChoiceMCP' - temperature: - type: number - description: | - Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. - max_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - conversation: - description: | - Controls which conversation the response is added to. Currently supports - `auto` and `none`, with `auto` as the default value. The `auto` value - means that the contents of the response will be added to the default - conversation. Set this to `none` to create an out-of-band response which - will not add items to default conversation. - anyOf: - - type: string - - type: string - default: auto - enum: - - auto - - none - metadata: - $ref: '#/components/schemas/Metadata' - prompt: - $ref: '#/components/schemas/Prompt' - input: - type: array - description: | - Input items to include in the prompt for the model. Using this field - creates a new context for this Response instead of using the default - conversation. An empty array `[]` will clear the context for this Response. - Note that this can include references to items from the default conversation. - items: - $ref: '#/components/schemas/RealtimeConversationItem' - RealtimeBetaServerEventConversationItemCreated: - type: object - description: | - Returned when a conversation item is created. There are several scenarios that produce this event: - - The server is generating a Response, which if successful will produce - either one or two Items, which will be of type `message` - (role `assistant`) or type `function_call`. - - The input audio buffer has been committed, either by the client or the - server (in `server_vad` mode). The server will take the content of the - input audio buffer and add it to a new user message Item. - - The client has sent a `conversation.item.create` event to add a new Item - to the Conversation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.created`. - x-stainless-const: true - const: conversation.item.created - previous_item_id: - anyOf: - - type: string - description: | - The ID of the preceding item in the Conversation context, allows the - client to understand the order of the conversation. Can be `null` if the - item has no predecessor. - - type: 'null' - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - item - x-oaiMeta: - name: conversation.item.created - group: realtime - example: | - { - "event_id": "event_1920", - "type": "conversation.item.created", - "previous_item_id": "msg_002", - "item": { - "id": "msg_003", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "user", - "content": [] - } - } - RealtimeBetaServerEventConversationItemDeleted: - type: object - description: | - Returned when an item in the conversation is deleted by the client with a - `conversation.item.delete` event. This event is used to synchronize the - server's understanding of the conversation history with the client's view. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.deleted`. - x-stainless-const: true - const: conversation.item.deleted - item_id: - type: string - description: The ID of the item that was deleted. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: conversation.item.deleted - group: realtime - example: | - { - "event_id": "event_2728", - "type": "conversation.item.deleted", - "item_id": "msg_005" - } - RealtimeBetaServerEventConversationItemInputAudioTranscriptionCompleted: - type: object - description: | - This event is the output of audio transcription for user audio written to the - user audio buffer. Transcription begins when the input audio buffer is - committed by the client or server (in `server_vad` mode). Transcription runs - asynchronously with Response creation, so this event may come before or after - the Response events. - - Realtime API models accept audio natively, and thus input transcription is a - separate process run on a separate ASR (Automatic Speech Recognition) model. - The transcript may diverge somewhat from the model's interpretation, and - should be treated as a rough guide. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - type: string - enum: - - conversation.item.input_audio_transcription.completed - description: | - The event type, must be - `conversation.item.input_audio_transcription.completed`. - x-stainless-const: true - item_id: - type: string - description: The ID of the user message item containing the audio. - content_index: - type: integer - description: The index of the content part containing the audio. - transcript: - type: string - description: The transcribed text. - logprobs: - anyOf: - - type: array - description: The log probabilities of the transcription. - items: - $ref: '#/components/schemas/LogProbProperties' - - type: 'null' - usage: - type: object - description: Usage statistics for the transcription. - anyOf: - - $ref: '#/components/schemas/TranscriptTextUsageTokens' - title: Token Usage - - $ref: '#/components/schemas/TranscriptTextUsageDuration' - title: Duration Usage - required: - - event_id - - type - - item_id - - content_index - - transcript - - usage - x-oaiMeta: - name: conversation.item.input_audio_transcription.completed - group: realtime - example: | - { - "event_id": "event_2122", - "type": "conversation.item.input_audio_transcription.completed", - "item_id": "msg_003", - "content_index": 0, - "transcript": "Hello, how are you?", - "usage": { - "type": "tokens", - "total_tokens": 48, - "input_tokens": 38, - "input_token_details": { - "text_tokens": 10, - "audio_tokens": 28, - }, - "output_tokens": 10, - } - } - RealtimeBetaServerEventConversationItemInputAudioTranscriptionDelta: - type: object - description: | - Returned when the text value of an input audio transcription content part is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.input_audio_transcription.delta`. - x-stainless-const: true - const: conversation.item.input_audio_transcription.delta - item_id: - type: string - description: The ID of the item. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: The text delta. - logprobs: - anyOf: - - type: array - description: The log probabilities of the transcription. - items: - $ref: '#/components/schemas/LogProbProperties' - - type: 'null' - required: - - event_id - - type - - item_id - x-oaiMeta: - name: conversation.item.input_audio_transcription.delta - group: realtime - example: | - { - "type": "conversation.item.input_audio_transcription.delta", - "event_id": "event_001", - "item_id": "item_001", - "content_index": 0, - "delta": "Hello" - } - RealtimeBetaServerEventConversationItemInputAudioTranscriptionFailed: - type: object - description: | - Returned when input audio transcription is configured, and a transcription - request for a user message failed. These events are separate from other - `error` events so that the client can identify the related Item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - type: string - enum: - - conversation.item.input_audio_transcription.failed - description: | - The event type, must be - `conversation.item.input_audio_transcription.failed`. - x-stainless-const: true - item_id: - type: string - description: The ID of the user message item. - content_index: - type: integer - description: The index of the content part containing the audio. - error: - type: object - description: Details of the transcription error. - properties: - type: - type: string - description: The type of error. - code: - type: string - description: Error code, if any. - message: - type: string - description: A human-readable error message. - param: - type: string - description: Parameter related to the error, if any. - required: - - event_id - - type - - item_id - - content_index - - error - x-oaiMeta: - name: conversation.item.input_audio_transcription.failed - group: realtime - example: | - { - "event_id": "event_2324", - "type": "conversation.item.input_audio_transcription.failed", - "item_id": "msg_003", - "content_index": 0, - "error": { - "type": "transcription_error", - "code": "audio_unintelligible", - "message": "The audio could not be transcribed.", - "param": null - } - } - RealtimeBetaServerEventConversationItemInputAudioTranscriptionSegment: - type: object - description: Returned when an input audio transcription segment is identified for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.input_audio_transcription.segment`. - x-stainless-const: true - const: conversation.item.input_audio_transcription.segment - item_id: - type: string - description: The ID of the item containing the input audio content. - content_index: - type: integer - description: The index of the input audio content part within the item. - text: - type: string - description: The text for this segment. - id: - type: string - description: The segment identifier. - speaker: - type: string - description: The detected speaker label for this segment. - start: - type: number - format: float - description: Start time of the segment in seconds. - end: - type: number - format: float - description: End time of the segment in seconds. - required: - - event_id - - type - - item_id - - content_index - - text - - id - - speaker - - start - - end - x-oaiMeta: - name: conversation.item.input_audio_transcription.segment - group: realtime - example: | - { - "event_id": "event_6501", - "type": "conversation.item.input_audio_transcription.segment", - "item_id": "msg_011", - "content_index": 0, - "text": "hello", - "id": "seg_0001", - "speaker": "spk_1", - "start": 0.0, - "end": 0.4 - } - RealtimeBetaServerEventConversationItemRetrieved: - type: object - description: | - Returned when a conversation item is retrieved with `conversation.item.retrieve`. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.retrieved`. - x-stainless-const: true - const: conversation.item.retrieved - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - item - x-oaiMeta: - name: conversation.item.retrieved - group: realtime - example: | - { - "event_id": "event_1920", - "type": "conversation.item.created", - "previous_item_id": "msg_002", - "item": { - "id": "msg_003", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "user", - "content": [ - { - "type": "input_audio", - "transcript": "hello how are you", - "audio": "base64encodedaudio==" - } - ] - } - } - RealtimeBetaServerEventConversationItemTruncated: - type: object - description: | - Returned when an earlier assistant audio message item is truncated by the - client with a `conversation.item.truncate` event. This event is used to - synchronize the server's understanding of the audio with the client's playback. - - This action will truncate the audio and remove the server-side text transcript - to ensure there is no text in the context that hasn't been heard by the user. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.truncated`. - x-stainless-const: true - const: conversation.item.truncated - item_id: - type: string - description: The ID of the assistant message item that was truncated. - content_index: - type: integer - description: The index of the content part that was truncated. - audio_end_ms: - type: integer - description: | - The duration up to which the audio was truncated, in milliseconds. - required: - - event_id - - type - - item_id - - content_index - - audio_end_ms - x-oaiMeta: - name: conversation.item.truncated - group: realtime - example: | - { - "event_id": "event_2526", - "type": "conversation.item.truncated", - "item_id": "msg_004", - "content_index": 0, - "audio_end_ms": 1500 - } - RealtimeBetaServerEventError: - type: object - description: | - Returned when an error occurs, which could be a client problem or a server - problem. Most errors are recoverable and the session will stay open, we - recommend to implementors to monitor and log error messages by default. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `error`. - x-stainless-const: true - const: error - error: - type: object - description: Details of the error. - required: - - type - - message - properties: - type: - type: string - description: | - The type of error (e.g., "invalid_request_error", "server_error"). - code: - anyOf: - - type: string - description: Error code, if any. - - type: 'null' - message: - type: string - description: A human-readable error message. - param: - anyOf: - - type: string - description: Parameter related to the error, if any. - - type: 'null' - event_id: - anyOf: - - type: string - description: | - The event_id of the client event that caused the error, if applicable. - - type: 'null' - required: - - event_id - - type - - error - x-oaiMeta: - name: error - group: realtime - example: | - { - "event_id": "event_890", - "type": "error", - "error": { - "type": "invalid_request_error", - "code": "invalid_event", - "message": "The 'type' field is missing.", - "param": null, - "event_id": "event_567" - } - } - RealtimeBetaServerEventInputAudioBufferCleared: - type: object - description: | - Returned when the input audio buffer is cleared by the client with a - `input_audio_buffer.clear` event. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.cleared`. - x-stainless-const: true - const: input_audio_buffer.cleared - required: - - event_id - - type - x-oaiMeta: - name: input_audio_buffer.cleared - group: realtime - example: | - { - "event_id": "event_1314", - "type": "input_audio_buffer.cleared" - } - RealtimeBetaServerEventInputAudioBufferCommitted: - type: object - description: | - Returned when an input audio buffer is committed, either by the client or - automatically in server VAD mode. The `item_id` property is the ID of the user - message item that will be created, thus a `conversation.item.created` event - will also be sent to the client. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.committed`. - x-stainless-const: true - const: input_audio_buffer.committed - previous_item_id: - anyOf: - - type: string - description: | - The ID of the preceding item after which the new item will be inserted. - Can be `null` if the item has no predecessor. - - type: 'null' - item_id: - type: string - description: The ID of the user message item that will be created. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: input_audio_buffer.committed - group: realtime - example: | - { - "event_id": "event_1121", - "type": "input_audio_buffer.committed", - "previous_item_id": "msg_001", - "item_id": "msg_002" - } - RealtimeBetaServerEventInputAudioBufferSpeechStarted: - type: object - description: | - Sent by the server when in `server_vad` mode to indicate that speech has been - detected in the audio buffer. This can happen any time audio is added to the - buffer (unless speech is already detected). The client may want to use this - event to interrupt audio playback or provide visual feedback to the user. - - The client should expect to receive a `input_audio_buffer.speech_stopped` event - when speech stops. The `item_id` property is the ID of the user message item - that will be created when speech stops and will also be included in the - `input_audio_buffer.speech_stopped` event (unless the client manually commits - the audio buffer during VAD activation). - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.speech_started`. - x-stainless-const: true - const: input_audio_buffer.speech_started - audio_start_ms: - type: integer - description: | - Milliseconds from the start of all audio written to the buffer during the - session when speech was first detected. This will correspond to the - beginning of audio sent to the model, and thus includes the - `prefix_padding_ms` configured in the Session. - item_id: - type: string - description: | - The ID of the user message item that will be created when speech stops. - required: - - event_id - - type - - audio_start_ms - - item_id - x-oaiMeta: - name: input_audio_buffer.speech_started - group: realtime - example: | - { - "event_id": "event_1516", - "type": "input_audio_buffer.speech_started", - "audio_start_ms": 1000, - "item_id": "msg_003" - } - RealtimeBetaServerEventInputAudioBufferSpeechStopped: - type: object - description: | - Returned in `server_vad` mode when the server detects the end of speech in - the audio buffer. The server will also send an `conversation.item.created` - event with the user message item that is created from the audio buffer. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.speech_stopped`. - x-stainless-const: true - const: input_audio_buffer.speech_stopped - audio_end_ms: - type: integer - description: | - Milliseconds since the session started when speech stopped. This will - correspond to the end of audio sent to the model, and thus includes the - `min_silence_duration_ms` configured in the Session. - item_id: - type: string - description: The ID of the user message item that will be created. - required: - - event_id - - type - - audio_end_ms - - item_id - x-oaiMeta: - name: input_audio_buffer.speech_stopped - group: realtime - example: | - { - "event_id": "event_1718", - "type": "input_audio_buffer.speech_stopped", - "audio_end_ms": 2000, - "item_id": "msg_003" - } - RealtimeBetaServerEventMCPListToolsCompleted: - type: object - description: Returned when listing MCP tools has completed for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `mcp_list_tools.completed`. - x-stainless-const: true - const: mcp_list_tools.completed - item_id: - type: string - description: The ID of the MCP list tools item. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: mcp_list_tools.completed - group: realtime - example: | - { - "event_id": "event_6102", - "type": "mcp_list_tools.completed", - "item_id": "mcp_list_tools_001" - } - RealtimeBetaServerEventMCPListToolsFailed: - type: object - description: Returned when listing MCP tools has failed for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `mcp_list_tools.failed`. - x-stainless-const: true - const: mcp_list_tools.failed - item_id: - type: string - description: The ID of the MCP list tools item. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: mcp_list_tools.failed - group: realtime - example: | - { - "event_id": "event_6103", - "type": "mcp_list_tools.failed", - "item_id": "mcp_list_tools_001" - } - RealtimeBetaServerEventMCPListToolsInProgress: - type: object - description: Returned when listing MCP tools is in progress for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `mcp_list_tools.in_progress`. - x-stainless-const: true - const: mcp_list_tools.in_progress - item_id: - type: string - description: The ID of the MCP list tools item. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: mcp_list_tools.in_progress - group: realtime - example: | - { - "event_id": "event_6101", - "type": "mcp_list_tools.in_progress", - "item_id": "mcp_list_tools_001" - } - RealtimeBetaServerEventRateLimitsUpdated: - type: object - description: | - Emitted at the beginning of a Response to indicate the updated rate limits. - When a Response is created some tokens will be "reserved" for the output - tokens, the rate limits shown here reflect that reservation, which is then - adjusted accordingly once the Response is completed. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `rate_limits.updated`. - x-stainless-const: true - const: rate_limits.updated - rate_limits: - type: array - description: List of rate limit information. - items: - type: object - properties: - name: - type: string - enum: - - requests - - tokens - description: | - The name of the rate limit (`requests`, `tokens`). - limit: - type: integer - description: The maximum allowed value for the rate limit. - remaining: - type: integer - description: The remaining value before the limit is reached. - reset_seconds: - type: number - description: Seconds until the rate limit resets. - required: - - event_id - - type - - rate_limits - x-oaiMeta: - name: rate_limits.updated - group: realtime - example: | - { - "event_id": "event_5758", - "type": "rate_limits.updated", - "rate_limits": [ - { - "name": "requests", - "limit": 1000, - "remaining": 999, - "reset_seconds": 60 - }, - { - "name": "tokens", - "limit": 50000, - "remaining": 49950, - "reset_seconds": 60 - } - ] - } - RealtimeBetaServerEventResponseAudioDelta: - type: object - description: Returned when the model-generated audio is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio.delta`. - x-stainless-const: true - const: response.output_audio.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: Base64-encoded audio data delta. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - delta - x-oaiMeta: - name: response.output_audio.delta - group: realtime - example: | - { - "event_id": "event_4950", - "type": "response.output_audio.delta", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0, - "delta": "Base64EncodedAudioDelta" - } - RealtimeBetaServerEventResponseAudioDone: - type: object - description: | - Returned when the model-generated audio is done. Also emitted when a Response - is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio.done`. - x-stainless-const: true - const: response.output_audio.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - x-oaiMeta: - name: response.output_audio.done - group: realtime - example: | - { - "event_id": "event_5152", - "type": "response.output_audio.done", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0 - } - RealtimeBetaServerEventResponseAudioTranscriptDelta: - type: object - description: | - Returned when the model-generated transcription of audio output is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio_transcript.delta`. - x-stainless-const: true - const: response.output_audio_transcript.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: The transcript delta. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - delta - x-oaiMeta: - name: response.output_audio_transcript.delta - group: realtime - example: | - { - "event_id": "event_4546", - "type": "response.output_audio_transcript.delta", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0, - "delta": "Hello, how can I a" - } - RealtimeBetaServerEventResponseAudioTranscriptDone: - type: object - description: | - Returned when the model-generated transcription of audio output is done - streaming. Also emitted when a Response is interrupted, incomplete, or - cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio_transcript.done`. - x-stainless-const: true - const: response.output_audio_transcript.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - transcript: - type: string - description: The final transcript of the audio. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - transcript - x-oaiMeta: - name: response.output_audio_transcript.done - group: realtime - example: | - { - "event_id": "event_4748", - "type": "response.output_audio_transcript.done", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0, - "transcript": "Hello, how can I assist you today?" - } - RealtimeBetaServerEventResponseContentPartAdded: - type: object - description: | - Returned when a new content part is added to an assistant message item during - response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.content_part.added`. - x-stainless-const: true - const: response.content_part.added - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item to which the content part was added. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - part: - type: object - description: The content part that was added. - properties: - type: - type: string - enum: - - text - - audio - description: The content type ("text", "audio"). - text: - type: string - description: The text content (if type is "text"). - audio: - type: string - description: Base64-encoded audio data (if type is "audio"). - transcript: - type: string - description: The transcript of the audio (if type is "audio"). - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - part - x-oaiMeta: - name: response.content_part.added - group: realtime - example: | - { - "event_id": "event_3738", - "type": "response.content_part.added", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "part": { - "type": "text", - "text": "" - } - } - RealtimeBetaServerEventResponseContentPartDone: - type: object - description: | - Returned when a content part is done streaming in an assistant message item. - Also emitted when a Response is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.content_part.done`. - x-stainless-const: true - const: response.content_part.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - part: - type: object - description: The content part that is done. - properties: - type: - type: string - enum: - - text - - audio - description: The content type ("text", "audio"). - text: - type: string - description: The text content (if type is "text"). - audio: - type: string - description: Base64-encoded audio data (if type is "audio"). - transcript: - type: string - description: The transcript of the audio (if type is "audio"). - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - part - x-oaiMeta: - name: response.content_part.done - group: realtime - example: | - { - "event_id": "event_3940", - "type": "response.content_part.done", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "part": { - "type": "text", - "text": "Sure, I can help with that." - } - } - RealtimeBetaServerEventResponseCreated: - type: object - description: | - Returned when a new Response is created. The first event of response creation, - where the response is in an initial state of `in_progress`. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.created`. - x-stainless-const: true - const: response.created - response: - $ref: '#/components/schemas/RealtimeBetaResponse' - required: - - event_id - - type - - response - x-oaiMeta: - name: response.created - group: realtime - example: | - { - "type": "response.created", - "event_id": "event_C9G8pqbTEddBSIxbBN6Os", - "response": { - "object": "realtime.response", - "id": "resp_C9G8p7IH2WxLbkgPNouYL", - "status": "in_progress", - "status_details": null, - "output": [], - "conversation_id": "conv_C9G8mmBkLhQJwCon3hoJN", - "output_modalities": [ - "audio" - ], - "max_output_tokens": "inf", - "audio": { - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "marin" - } - }, - "usage": null, - "metadata": null - }, - "timestamp": "2:30:35 PM" - } - RealtimeBetaServerEventResponseDone: - type: object - description: | - Returned when a Response is done streaming. Always emitted, no matter the - final state. The Response object included in the `response.done` event will - include all output Items in the Response but will omit the raw audio data. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.done`. - x-stainless-const: true - const: response.done - response: - $ref: '#/components/schemas/RealtimeBetaResponse' - required: - - event_id - - type - - response - x-oaiMeta: - name: response.done - group: realtime - example: | - { - "event_id": "event_3132", - "type": "response.done", - "response": { - "id": "resp_001", - "object": "realtime.response", - "status": "completed", - "status_details": null, - "output": [ - { - "id": "msg_006", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "text", - "text": "Sure, how can I assist you today?" - } - ] - } - ], - "usage": { - "total_tokens":275, - "input_tokens":127, - "output_tokens":148, - "input_token_details": { - "cached_tokens":384, - "text_tokens":119, - "audio_tokens":8, - "cached_tokens_details": { - "text_tokens": 128, - "audio_tokens": 256 - } - }, - "output_token_details": { - "text_tokens":36, - "audio_tokens":112 - } - } - } - } - RealtimeBetaServerEventResponseFunctionCallArgumentsDelta: - type: object - description: | - Returned when the model-generated function call arguments are updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: | - The event type, must be `response.function_call_arguments.delta`. - x-stainless-const: true - const: response.function_call_arguments.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the function call item. - output_index: - type: integer - description: The index of the output item in the response. - call_id: - type: string - description: The ID of the function call. - delta: - type: string - description: The arguments delta as a JSON string. - required: - - event_id - - type - - response_id - - item_id - - output_index - - call_id - - delta - x-oaiMeta: - name: response.function_call_arguments.delta - group: realtime - example: | - { - "event_id": "event_5354", - "type": "response.function_call_arguments.delta", - "response_id": "resp_002", - "item_id": "fc_001", - "output_index": 0, - "call_id": "call_001", - "delta": "{\"location\": \"San\"" - } - RealtimeBetaServerEventResponseFunctionCallArgumentsDone: - type: object - description: | - Returned when the model-generated function call arguments are done streaming. - Also emitted when a Response is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: | - The event type, must be `response.function_call_arguments.done`. - x-stainless-const: true - const: response.function_call_arguments.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the function call item. - output_index: - type: integer - description: The index of the output item in the response. - call_id: - type: string - description: The ID of the function call. - arguments: - type: string - description: The final arguments as a JSON string. - required: - - event_id - - type - - response_id - - item_id - - output_index - - call_id - - arguments - x-oaiMeta: - name: response.function_call_arguments.done - group: realtime - example: | - { - "event_id": "event_5556", - "type": "response.function_call_arguments.done", - "response_id": "resp_002", - "item_id": "fc_001", - "output_index": 0, - "call_id": "call_001", - "arguments": "{\"location\": \"San Francisco\"}" - } - RealtimeBetaServerEventResponseMCPCallArgumentsDelta: - type: object - description: Returned when MCP tool call arguments are updated during response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call_arguments.delta`. - x-stainless-const: true - const: response.mcp_call_arguments.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the MCP tool call item. - output_index: - type: integer - description: The index of the output item in the response. - delta: - type: string - description: The JSON-encoded arguments delta. - obfuscation: - anyOf: - - type: string - description: If present, indicates the delta text was obfuscated. - - type: 'null' - required: - - event_id - - type - - response_id - - item_id - - output_index - - delta - x-oaiMeta: - name: response.mcp_call_arguments.delta - group: realtime - example: | - { - "event_id": "event_6201", - "type": "response.mcp_call_arguments.delta", - "response_id": "resp_001", - "item_id": "mcp_call_001", - "output_index": 0, - "delta": "{\"partial\":true}" - } - RealtimeBetaServerEventResponseMCPCallArgumentsDone: - type: object - description: Returned when MCP tool call arguments are finalized during response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call_arguments.done`. - x-stainless-const: true - const: response.mcp_call_arguments.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the MCP tool call item. - output_index: - type: integer - description: The index of the output item in the response. - arguments: - type: string - description: The final JSON-encoded arguments string. - required: - - event_id - - type - - response_id - - item_id - - output_index - - arguments - x-oaiMeta: - name: response.mcp_call_arguments.done - group: realtime - example: | - { - "event_id": "event_6202", - "type": "response.mcp_call_arguments.done", - "response_id": "resp_001", - "item_id": "mcp_call_001", - "output_index": 0, - "arguments": "{\"q\":\"docs\"}" - } - RealtimeBetaServerEventResponseMCPCallCompleted: - type: object - description: Returned when an MCP tool call has completed successfully. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call.completed`. - x-stainless-const: true - const: response.mcp_call.completed - output_index: - type: integer - description: The index of the output item in the response. - item_id: - type: string - description: The ID of the MCP tool call item. - required: - - event_id - - type - - output_index - - item_id - x-oaiMeta: - name: response.mcp_call.completed - group: realtime - example: | - { - "event_id": "event_6302", - "type": "response.mcp_call.completed", - "output_index": 0, - "item_id": "mcp_call_001" - } - RealtimeBetaServerEventResponseMCPCallFailed: - type: object - description: Returned when an MCP tool call has failed. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call.failed`. - x-stainless-const: true - const: response.mcp_call.failed - output_index: - type: integer - description: The index of the output item in the response. - item_id: - type: string - description: The ID of the MCP tool call item. - required: - - event_id - - type - - output_index - - item_id - x-oaiMeta: - name: response.mcp_call.failed - group: realtime - example: | - { - "event_id": "event_6303", - "type": "response.mcp_call.failed", - "output_index": 0, - "item_id": "mcp_call_001" - } - RealtimeBetaServerEventResponseMCPCallInProgress: - type: object - description: Returned when an MCP tool call has started and is in progress. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call.in_progress`. - x-stainless-const: true - const: response.mcp_call.in_progress - output_index: - type: integer - description: The index of the output item in the response. - item_id: - type: string - description: The ID of the MCP tool call item. - required: - - event_id - - type - - output_index - - item_id - x-oaiMeta: - name: response.mcp_call.in_progress - group: realtime - example: | - { - "event_id": "event_6301", - "type": "response.mcp_call.in_progress", - "output_index": 0, - "item_id": "mcp_call_001" - } - RealtimeBetaServerEventResponseOutputItemAdded: - type: object - description: Returned when a new Item is created during Response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_item.added`. - x-stainless-const: true - const: response.output_item.added - response_id: - type: string - description: The ID of the Response to which the item belongs. - output_index: - type: integer - description: The index of the output item in the Response. - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - response_id - - output_index - - item - x-oaiMeta: - name: response.output_item.added - group: realtime - example: | - { - "event_id": "event_3334", - "type": "response.output_item.added", - "response_id": "resp_001", - "output_index": 0, - "item": { - "id": "msg_007", - "object": "realtime.item", - "type": "message", - "status": "in_progress", - "role": "assistant", - "content": [] - } - } - RealtimeBetaServerEventResponseOutputItemDone: - type: object - description: | - Returned when an Item is done streaming. Also emitted when a Response is - interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_item.done`. - x-stainless-const: true - const: response.output_item.done - response_id: - type: string - description: The ID of the Response to which the item belongs. - output_index: - type: integer - description: The index of the output item in the Response. - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - response_id - - output_index - - item - x-oaiMeta: - name: response.output_item.done - group: realtime - example: | - { - "event_id": "event_3536", - "type": "response.output_item.done", - "response_id": "resp_001", - "output_index": 0, - "item": { - "id": "msg_007", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "text", - "text": "Sure, I can help with that." - } - ] - } - } - RealtimeBetaServerEventResponseTextDelta: - type: object - description: Returned when the text value of an "output_text" content part is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_text.delta`. - x-stainless-const: true - const: response.output_text.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: The text delta. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - delta - x-oaiMeta: - name: response.output_text.delta - group: realtime - example: | - { - "event_id": "event_4142", - "type": "response.output_text.delta", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "delta": "Sure, I can h" - } - RealtimeBetaServerEventResponseTextDone: - type: object - description: | - Returned when the text value of an "output_text" content part is done streaming. Also - emitted when a Response is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_text.done`. - x-stainless-const: true - const: response.output_text.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - text: - type: string - description: The final text content. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - text - x-oaiMeta: - name: response.output_text.done - group: realtime - example: | - { - "event_id": "event_4344", - "type": "response.output_text.done", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "text": "Sure, I can help with that." - } - RealtimeBetaServerEventSessionCreated: - type: object - description: | - Returned when a Session is created. Emitted automatically when a new - connection is established as the first server event. This event will contain - the default Session configuration. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `session.created`. - x-stainless-const: true - const: session.created - session: - $ref: '#/components/schemas/RealtimeSession' - required: - - event_id - - type - - session - x-oaiMeta: - name: session.created - group: realtime - example: | - { - "type": "session.created", - "event_id": "event_C9G5RJeJ2gF77mV7f2B1j", - "session": { - "object": "realtime.session", - "id": "sess_C9G5QPteg4UIbotdKLoYQ", - "model": "gpt-realtime-2025-08-28", - "modalities": [ - "audio" - ], - "instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.", - "tools": [], - "tool_choice": "auto", - "max_response_output_tokens": "inf", - "tracing": null, - "prompt": null, - "expires_at": 1756324625, - "input_audio_format": "pcm16", - "input_audio_transcription": null, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200, - "idle_timeout_ms": null, - "create_response": true, - "interrupt_response": true - }, - "output_audio_format": "pcm16", - "voice": "marin", - "include": null - } - } - RealtimeBetaServerEventSessionUpdated: - type: object - description: | - Returned when a session is updated with a `session.update` event, unless - there is an error. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `session.updated`. - x-stainless-const: true - const: session.updated - session: - $ref: '#/components/schemas/RealtimeSession' - required: - - event_id - - type - - session - x-oaiMeta: - name: session.updated - group: realtime - example: | - { - "event_id": "event_5678", - "type": "session.updated", - "session": { - "id": "sess_001", - "object": "realtime.session", - "model": "gpt-realtime", - "modalities": ["text"], - "instructions": "New instructions", - "voice": "sage", - "input_audio_format": "pcm16", - "output_audio_format": "pcm16", - "input_audio_transcription": { - "model": "whisper-1" - }, - "turn_detection": null, - "tools": [], - "tool_choice": "none", - "temperature": 0.7, - "max_response_output_tokens": 200, - "speed": 1.1, - "tracing": "auto" - } - } - RealtimeBetaServerEventTranscriptionSessionCreated: - type: object - description: | - Returned when a transcription session is created. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `transcription_session.created`. - x-stainless-const: true - const: transcription_session.created - session: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' - required: - - event_id - - type - - session - x-oaiMeta: - name: transcription_session.created - group: realtime - example: | - { - "event_id": "event_5566", - "type": "transcription_session.created", - "session": { - "id": "sess_001", - "object": "realtime.transcription_session", - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "prompt": "", - "language": "" - }, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 500 - }, - "input_audio_noise_reduction": { - "type": "near_field" - }, - "include": [] - } - } - RealtimeBetaServerEventTranscriptionSessionUpdated: - type: object - description: | - Returned when a transcription session is updated with a `transcription_session.update` event, unless - there is an error. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `transcription_session.updated`. - x-stainless-const: true - const: transcription_session.updated - session: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' - required: - - event_id - - type - - session - x-oaiMeta: - name: transcription_session.updated - group: realtime - example: | - { - "event_id": "event_5678", - "type": "transcription_session.updated", - "session": { - "id": "sess_001", - "object": "realtime.transcription_session", - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "prompt": "", - "language": "" - }, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 500, - "create_response": true, - // "interrupt_response": false -- this will NOT be returned - }, - "input_audio_noise_reduction": { - "type": "near_field" - }, - "include": [ - "item.input_audio_transcription.avg_logprob", - ], - } - } - RealtimeCallCreateRequest: - title: Realtime call creation request - type: object - description: |- - Parameters required to initiate a realtime call and receive the SDP answer - needed to complete a WebRTC peer connection. Provide an SDP offer generated - by your client and optionally configure the session that will answer the call. - required: - - sdp - properties: - sdp: - type: string - description: WebRTC Session Description Protocol (SDP) offer generated by the caller. - session: - title: Session configuration - allOf: - - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' - description: >- - Optional session configuration to apply before the realtime session is - - created. Use the same parameters you would send in a [`create client - secret`](https://platform.openai.com/docs/api-reference/realtime-sessions/create-realtime-client-secret) - - request. - additionalProperties: false - RealtimeCallReferRequest: - title: Realtime call refer request - type: object - description: |- - Parameters required to transfer a SIP call to a new destination using the - Realtime API. - required: - - target_uri - properties: - target_uri: - type: string - description: |- - URI that should appear in the SIP Refer-To header. Supports values like - `tel:+14155550123` or `sip:agent@example.com`. - example: tel:+14155550123 - additionalProperties: false - RealtimeCallRejectRequest: - title: Realtime call reject request - type: object - description: Parameters used to decline an incoming SIP call handled by the Realtime API. - properties: - status_code: - type: integer - description: |- - SIP response code to send back to the caller. Defaults to `603` (Decline) - when omitted. - example: 486 - additionalProperties: false - RealtimeClientEvent: - discriminator: - propertyName: type - description: | - A realtime client event. - anyOf: - - $ref: '#/components/schemas/RealtimeClientEventConversationItemCreate' - - $ref: '#/components/schemas/RealtimeClientEventConversationItemDelete' - - $ref: '#/components/schemas/RealtimeClientEventConversationItemRetrieve' - - $ref: '#/components/schemas/RealtimeClientEventConversationItemTruncate' - - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferAppend' - - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferClear' - - $ref: '#/components/schemas/RealtimeClientEventOutputAudioBufferClear' - - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferCommit' - - $ref: '#/components/schemas/RealtimeClientEventResponseCancel' - - $ref: '#/components/schemas/RealtimeClientEventResponseCreate' - - $ref: '#/components/schemas/RealtimeClientEventSessionUpdate' - RealtimeClientEventConversationItemCreate: - type: object - description: | - Add a new Item to the Conversation's context, including messages, function - calls, and function call responses. This event can be used both to populate a - "history" of the conversation and to add new items mid-stream, but has the - current limitation that it cannot populate assistant audio messages. - - If successful, the server will respond with a `conversation.item.created` - event, otherwise an `error` event will be sent. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.create`. - x-stainless-const: true - const: conversation.item.create - previous_item_id: - type: string - description: | - The ID of the preceding item after which the new item will be inserted. - If not set, the new item will be appended to the end of the conversation. - If set to `root`, the new item will be added to the beginning of the conversation. - If set to an existing ID, it allows an item to be inserted mid-conversation. If the - ID cannot be found, an error will be returned and the item will not be added. - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - type - - item - x-oaiMeta: - name: conversation.item.create - group: realtime - example: | - { - "type": "conversation.item.create", - "item": { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hi" - } - ] - }, - "event_id": "b904fba0-0ec4-40af-8bbb-f908a9b26793", - } - RealtimeClientEventConversationItemDelete: - type: object - description: | - Send this event when you want to remove any item from the conversation - history. The server will respond with a `conversation.item.deleted` event, - unless the item does not exist in the conversation history, in which case the - server will respond with an error. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.delete`. - x-stainless-const: true - const: conversation.item.delete - item_id: - type: string - description: The ID of the item to delete. - required: - - type - - item_id - x-oaiMeta: - name: conversation.item.delete - group: realtime - example: | - { - "event_id": "event_901", - "type": "conversation.item.delete", - "item_id": "item_003" - } - RealtimeClientEventConversationItemRetrieve: - type: object - description: > - Send this event when you want to retrieve the server's representation of a specific item in the - conversation history. This is useful, for example, to inspect user audio after noise cancellation and - VAD. - - The server will respond with a `conversation.item.retrieved` event, - - unless the item does not exist in the conversation history, in which case the - - server will respond with an error. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.retrieve`. - x-stainless-const: true - const: conversation.item.retrieve - item_id: - type: string - description: The ID of the item to retrieve. - required: - - type - - item_id - x-oaiMeta: - name: conversation.item.retrieve - group: realtime - example: | - { - "event_id": "event_901", - "type": "conversation.item.retrieve", - "item_id": "item_003" - } - RealtimeClientEventConversationItemTruncate: - type: object - description: | - Send this event to truncate a previous assistant message’s audio. The server - will produce audio faster than realtime, so this event is useful when the user - interrupts to truncate audio that has already been sent to the client but not - yet played. This will synchronize the server's understanding of the audio with - the client's playback. - - Truncating audio will delete the server-side text transcript to ensure there - is not text in the context that hasn't been heard by the user. - - If successful, the server will respond with a `conversation.item.truncated` - event. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `conversation.item.truncate`. - x-stainless-const: true - const: conversation.item.truncate - item_id: - type: string - description: | - The ID of the assistant message item to truncate. Only assistant message - items can be truncated. - content_index: - type: integer - description: The index of the content part to truncate. Set this to `0`. - audio_end_ms: - type: integer - description: | - Inclusive duration up to which audio is truncated, in milliseconds. If - the audio_end_ms is greater than the actual audio duration, the server - will respond with an error. - required: - - type - - item_id - - content_index - - audio_end_ms - x-oaiMeta: - name: conversation.item.truncate - group: realtime - example: | - { - "event_id": "event_678", - "type": "conversation.item.truncate", - "item_id": "item_002", - "content_index": 0, - "audio_end_ms": 1500 - } - RealtimeClientEventInputAudioBufferAppend: - type: object - description: | - Send this event to append audio bytes to the input audio buffer. The audio - buffer is temporary storage you can write to and later commit. A "commit" will create a new - user message item in the conversation history from the buffer content and clear the buffer. - Input audio transcription (if enabled) will be generated when the buffer is committed. - - If VAD is enabled the audio buffer is used to detect speech and the server will decide - when to commit. When Server VAD is disabled, you must commit the audio buffer - manually. Input audio noise reduction operates on writes to the audio buffer. - - The client may choose how much audio to place in each event up to a maximum - of 15 MiB, for example streaming smaller chunks from the client may allow the - VAD to be more responsive. Unlike most other client events, the server will - not send a confirmation response to this event. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `input_audio_buffer.append`. - x-stainless-const: true - const: input_audio_buffer.append - audio: - type: string - description: | - Base64-encoded audio bytes. This must be in the format specified by the - `input_audio_format` field in the session configuration. - required: - - type - - audio - x-oaiMeta: - name: input_audio_buffer.append - group: realtime - example: | - { - "event_id": "event_456", - "type": "input_audio_buffer.append", - "audio": "Base64EncodedAudioData" - } - RealtimeClientEventInputAudioBufferClear: - type: object - description: | - Send this event to clear the audio bytes in the buffer. The server will - respond with an `input_audio_buffer.cleared` event. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `input_audio_buffer.clear`. - x-stainless-const: true - const: input_audio_buffer.clear - required: - - type - x-oaiMeta: - name: input_audio_buffer.clear - group: realtime - example: | - { - "event_id": "event_012", - "type": "input_audio_buffer.clear" - } - RealtimeClientEventInputAudioBufferCommit: - type: object - description: > - Send this event to commit the user input audio buffer, which will create a new user message item in - the conversation. This event will produce an error if the input audio buffer is empty. When in Server - VAD mode, the client does not need to send this event, the server will commit the audio buffer - automatically. - - - Committing the input audio buffer will trigger input audio transcription (if enabled in session - configuration), but it will not create a response from the model. The server will respond with an - `input_audio_buffer.committed` event. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `input_audio_buffer.commit`. - x-stainless-const: true - const: input_audio_buffer.commit - required: - - type - x-oaiMeta: - name: input_audio_buffer.commit - group: realtime - example: | - { - "event_id": "event_789", - "type": "input_audio_buffer.commit" - } - RealtimeClientEventOutputAudioBufferClear: - type: object - description: > - **WebRTC Only:** Emit to cut off the current audio response. This will trigger the server to - - stop generating audio and emit a `output_audio_buffer.cleared` event. This - - event should be preceded by a `response.cancel` client event to stop the - - generation of the current response. - - [Learn - more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). - properties: - event_id: - type: string - description: The unique ID of the client event used for error handling. - type: - description: The event type, must be `output_audio_buffer.clear`. - x-stainless-const: true - const: output_audio_buffer.clear - required: - - type - x-oaiMeta: - name: output_audio_buffer.clear - group: realtime - example: | - { - "event_id": "optional_client_event_id", - "type": "output_audio_buffer.clear" - } - RealtimeClientEventResponseCancel: - type: object - description: | - Send this event to cancel an in-progress response. The server will respond - with a `response.done` event with a status of `response.status=cancelled`. If - there is no response to cancel, the server will respond with an error. It's safe - to call `response.cancel` even if no response is in progress, an error will be - returned the session will remain unaffected. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `response.cancel`. - x-stainless-const: true - const: response.cancel - response_id: - type: string - description: | - A specific response ID to cancel - if not provided, will cancel an - in-progress response in the default conversation. - required: - - type - x-oaiMeta: - name: response.cancel - group: realtime - example: | - { - "type": "response.cancel" - "response_id": "resp_12345", - } - RealtimeClientEventResponseCreate: - type: object - description: | - This event instructs the server to create a Response, which means triggering - model inference. When in Server VAD mode, the server will create Responses - automatically. - - A Response will include at least one Item, and may have two, in which case - the second will be a function call. These Items will be appended to the - conversation history by default. - - The server will respond with a `response.created` event, events for Items - and content created, and finally a `response.done` event to indicate the - Response is complete. - - The `response.create` event includes inference configuration like - `instructions` and `tools`. If these are set, they will override the Session's - configuration for this Response only. - - Responses can be created out-of-band of the default Conversation, meaning that they can - have arbitrary input, and it's possible to disable writing the output to the Conversation. - Only one Response can write to the default Conversation at a time, but otherwise multiple - Responses can be created in parallel. The `metadata` field is a good way to disambiguate - multiple simultaneous Responses. - - Clients can set `conversation` to `none` to create a Response that does not write to the default - Conversation. Arbitrary input can be provided with the `input` field, which is an array accepting - raw Items and references to existing Items. - properties: - event_id: - type: string - maxLength: 512 - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `response.create`. - x-stainless-const: true - const: response.create - response: - $ref: '#/components/schemas/RealtimeResponseCreateParams' - required: - - type - x-oaiMeta: - name: response.create - group: realtime - example: | - // Trigger a response with the default Conversation and no special parameters - { - "type": "response.create", - } - - // Trigger an out-of-band response that does not write to the default Conversation - { - "type": "response.create", - "response": { - "instructions": "Provide a concise answer.", - "tools": [], // clear any session tools - "conversation": "none", - "output_modalities": ["text"], - "metadata": { - "response_purpose": "summarization" - }, - "input": [ - { - "type": "item_reference", - "id": "item_12345", - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "Summarize the above message in one sentence." - } - ] - } - ], - } - } - RealtimeClientEventSessionUpdate: - type: object - description: > - Send this event to update the session’s configuration. - - The client may send this event at any time to update any field - - except for `voice` and `model`. `voice` can be updated only if there have been no other audio outputs - yet. - - - When the server receives a `session.update`, it will respond - - with a `session.updated` event showing the full, effective configuration. - - Only the fields that are present in the `session.update` are updated. To clear a field like - - `instructions`, pass an empty string. To clear a field like `tools`, pass an empty array. - - To clear a field like `turn_detection`, pass `null`. - properties: - event_id: - type: string - maxLength: 512 - description: >- - Optional client-generated ID used to identify this event. This is an arbitrary string that a - client may assign. It will be passed back if there is an error with the event, but the - corresponding `session.updated` event will not include it. - type: - description: The event type, must be `session.update`. - x-stainless-const: true - const: session.update - session: - type: object - description: | - Update the Realtime session. Choose either a realtime - session or a transcription session. - anyOf: - - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' - - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' - required: - - type - - session - x-oaiMeta: - name: session.update - group: realtime - example: | - { - "type": "session.update", - "session": { - "type": "realtime", - "instructions": "You are a creative assistant that helps with design tasks.", - "tools": [ - { - "type": "function", - "name": "display_color_palette", - "description": "Call this function when a user asks for a color palette.", - "parameters": { - "type": "object", - "strict": true, - "properties": { - "theme": { - "type": "string", - "description": "Description of the theme for the color scheme." - }, - "colors": { - "type": "array", - "description": "Array of five hex color codes based on the theme.", - "items": { - "type": "string", - "description": "Hex color code" - } - } - }, - "required": [ - "theme", - "colors" - ] - } - } - ], - "tool_choice": "auto" - }, - "event_id": "5fc543c4-f59c-420f-8fb9-68c45d1546a7", - } - RealtimeClientEventTranscriptionSessionUpdate: - type: object - description: | - Send this event to update a transcription session. - properties: - event_id: - type: string - description: Optional client-generated ID used to identify this event. - type: - description: The event type, must be `transcription_session.update`. - x-stainless-const: true - const: transcription_session.update - session: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' - required: - - type - - session - x-oaiMeta: - name: transcription_session.update - group: realtime - example: | - { - "type": "transcription_session.update", - "session": { - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "prompt": "", - "language": "" - }, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 500, - "create_response": true, - }, - "input_audio_noise_reduction": { - "type": "near_field" - }, - "include": [ - "item.input_audio_transcription.logprobs", - ] - } - } - RealtimeConversationItem: - description: A single item within a Realtime conversation. - anyOf: - - $ref: '#/components/schemas/RealtimeConversationItemMessageSystem' - - $ref: '#/components/schemas/RealtimeConversationItemMessageUser' - - $ref: '#/components/schemas/RealtimeConversationItemMessageAssistant' - - $ref: '#/components/schemas/RealtimeConversationItemFunctionCall' - - $ref: '#/components/schemas/RealtimeConversationItemFunctionCallOutput' - - $ref: '#/components/schemas/RealtimeMCPApprovalResponse' - - $ref: '#/components/schemas/RealtimeMCPListTools' - - $ref: '#/components/schemas/RealtimeMCPToolCall' - - $ref: '#/components/schemas/RealtimeMCPApprovalRequest' - discriminator: - propertyName: type - RealtimeConversationItemFunctionCall: - type: object - title: Realtime function call item - description: A function call item in a Realtime conversation. - properties: - id: - type: string - description: The unique ID of the item. This may be provided by the client or generated by the server. - object: - type: string - enum: - - realtime.item - description: >- - Identifier for the API object being returned - always `realtime.item`. Optional when creating a - new item. - x-stainless-const: true - type: - type: string - enum: - - function_call - description: The type of the item. Always `function_call`. - x-stainless-const: true - status: - type: string - enum: - - completed - - incomplete - - in_progress - description: The status of the item. Has no effect on the conversation. - call_id: - type: string - description: The ID of the function call. - name: - type: string - description: The name of the function being called. - arguments: - type: string - description: >- - The arguments of the function call. This is a JSON-encoded string representing the arguments - passed to the function, for example `{"arg1": "value1", "arg2": 42}`. - required: - - type - - name - - arguments - RealtimeConversationItemFunctionCallOutput: - type: object - title: Realtime function call output item - description: A function call output item in a Realtime conversation. - properties: - id: - type: string - description: The unique ID of the item. This may be provided by the client or generated by the server. - object: - type: string - enum: - - realtime.item - description: >- - Identifier for the API object being returned - always `realtime.item`. Optional when creating a - new item. - x-stainless-const: true - type: - type: string - enum: - - function_call_output - description: The type of the item. Always `function_call_output`. - x-stainless-const: true - status: - type: string - enum: - - completed - - incomplete - - in_progress - description: The status of the item. Has no effect on the conversation. - call_id: - type: string - description: The ID of the function call this output is for. - output: - type: string - description: >- - The output of the function call, this is free text and can contain any information or simply be - empty. - required: - - type - - call_id - - output - RealtimeConversationItemMessageAssistant: - type: object - title: Realtime assistant message item - description: An assistant message item in a Realtime conversation. - properties: - id: - type: string - description: The unique ID of the item. This may be provided by the client or generated by the server. - object: - type: string - enum: - - realtime.item - description: >- - Identifier for the API object being returned - always `realtime.item`. Optional when creating a - new item. - x-stainless-const: true - type: - type: string - enum: - - message - description: The type of the item. Always `message`. - x-stainless-const: true - status: - type: string - enum: - - completed - - incomplete - - in_progress - description: The status of the item. Has no effect on the conversation. - role: - type: string - enum: - - assistant - description: The role of the message sender. Always `assistant`. - x-stainless-const: true - content: - type: array - description: The content of the message. - items: - type: object - properties: - type: - type: string - enum: - - output_text - - output_audio - description: >- - The content type, `output_text` or `output_audio` depending on the session - `output_modalities` configuration. - text: - type: string - description: The text content. - audio: - type: string - description: >- - Base64-encoded audio bytes, these will be parsed as the format specified in the session - output audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified. - transcript: - type: string - description: >- - The transcript of the audio content, this will always be present if the output type is - `audio`. - required: - - type - - role - - content - RealtimeConversationItemMessageSystem: - type: object - title: Realtime system message item - description: >- - A system message in a Realtime conversation can be used to provide additional context or instructions - to the model. This is similar but distinct from the instruction prompt provided at the start of a - conversation, as system messages can be added at any point in the conversation. For major changes to - the conversation's behavior, use instructions, but for smaller updates (e.g. "the user is now asking - about a different topic"), use system messages. - properties: - id: - type: string - description: The unique ID of the item. This may be provided by the client or generated by the server. - object: - type: string - enum: - - realtime.item - description: >- - Identifier for the API object being returned - always `realtime.item`. Optional when creating a - new item. - x-stainless-const: true - type: - type: string - enum: - - message - description: The type of the item. Always `message`. - x-stainless-const: true - status: - type: string - enum: - - completed - - incomplete - - in_progress - description: The status of the item. Has no effect on the conversation. - role: - type: string - enum: - - system - description: The role of the message sender. Always `system`. - x-stainless-const: true - content: - type: array - description: The content of the message. - items: - type: object - properties: - type: - type: string - enum: - - input_text - description: The content type. Always `input_text` for system messages. - x-stainless-const: true - text: - type: string - description: The text content. - required: - - type - - role - - content - RealtimeConversationItemMessageUser: - type: object - title: Realtime user message item - description: A user message item in a Realtime conversation. - properties: - id: - type: string - description: The unique ID of the item. This may be provided by the client or generated by the server. - object: - type: string - enum: - - realtime.item - description: >- - Identifier for the API object being returned - always `realtime.item`. Optional when creating a - new item. - x-stainless-const: true - type: - type: string - enum: - - message - description: The type of the item. Always `message`. - x-stainless-const: true - status: - type: string - enum: - - completed - - incomplete - - in_progress - description: The status of the item. Has no effect on the conversation. - role: - type: string - enum: - - user - description: The role of the message sender. Always `user`. - x-stainless-const: true - content: - type: array - description: The content of the message. - items: - type: object - properties: - type: - type: string - enum: - - input_text - - input_audio - - input_image - description: The content type (`input_text`, `input_audio`, or `input_image`). - text: - type: string - description: The text content (for `input_text`). - audio: - type: string - description: >- - Base64-encoded audio bytes (for `input_audio`), these will be parsed as the format specified - in the session input audio type configuration. This defaults to PCM 16-bit 24kHz mono if not - specified. - image_url: - type: string - description: >- - Base64-encoded image bytes (for `input_image`) as a data URI. For example - `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...`. Supported formats are PNG and JPEG. - detail: - type: string - description: The detail level of the image (for `input_image`). `auto` will default to `high`. - default: auto - enum: - - auto - - low - - high - transcript: - type: string - description: >- - Transcript of the audio (for `input_audio`). This is not sent to the model, but will be - attached to the message item for reference. - required: - - type - - role - - content - RealtimeConversationItemWithReference: - type: object - description: The item to add to the conversation. - properties: - id: - type: string - description: | - For an item of type (`message` | `function_call` | `function_call_output`) - this field allows the client to assign the unique ID of the item. It is - not required because the server will generate one if not provided. - - For an item of type `item_reference`, this field is required and is a - reference to any item that has previously existed in the conversation. - type: - type: string - enum: - - message - - function_call - - function_call_output - - item_reference - description: | - The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`). - object: - type: string - enum: - - realtime.item - description: | - Identifier for the API object being returned - always `realtime.item`. - x-stainless-const: true - status: - type: string - enum: - - completed - - incomplete - - in_progress - description: | - The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect - on the conversation, but are accepted for consistency with the - `conversation.item.created` event. - role: - type: string - enum: - - user - - assistant - - system - description: | - The role of the message sender (`user`, `assistant`, `system`), only - applicable for `message` items. - content: - type: array - description: | - The content of the message, applicable for `message` items. - - Message items of role `system` support only `input_text` content - - Message items of role `user` support `input_text` and `input_audio` - content - - Message items of role `assistant` support `text` content. - items: - type: object - properties: - type: - type: string - enum: - - input_text - - input_audio - - item_reference - - text - description: | - The content type (`input_text`, `input_audio`, `item_reference`, `text`). - text: - type: string - description: | - The text content, used for `input_text` and `text` content types. - id: - type: string - description: | - ID of a previous conversation item to reference (for `item_reference` - content types in `response.create` events). These can reference both - client and server created items. - audio: - type: string - description: | - Base64-encoded audio bytes, used for `input_audio` content type. - transcript: - type: string - description: | - The transcript of the audio, used for `input_audio` content type. - call_id: - type: string - description: | - The ID of the function call (for `function_call` and - `function_call_output` items). If passed on a `function_call_output` - item, the server will check that a `function_call` item with the same - ID exists in the conversation history. - name: - type: string - description: | - The name of the function being called (for `function_call` items). - arguments: - type: string - description: | - The arguments of the function call (for `function_call` items). - output: - type: string - description: | - The output of the function call (for `function_call_output` items). - RealtimeCreateClientSecretRequest: - type: object - title: Realtime client secret creation request - description: | - Create a session and client secret for the Realtime API. The request can specify - either a realtime or a transcription session configuration. - [Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime). - properties: - expires_after: - type: object - title: Client secret expiration - description: | - Configuration for the client secret expiration. Expiration refers to the time after which - a client secret will no longer be valid for creating sessions. The session itself may - continue after that time once started. A secret can be used to create multiple sessions - until it expires. - properties: - anchor: - type: string - enum: - - created_at - description: > - The anchor point for the client secret expiration, meaning that `seconds` will be added to the - `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` - is currently supported. - default: created_at - x-stainless-const: true - seconds: - type: integer - description: > - The number of seconds from the anchor point to the expiration. Select a value between `10` and - `7200` (2 hours). This default to 600 seconds (10 minutes) if not specified. - minimum: 10 - maximum: 7200 - default: 600 - session: - title: Session configuration - description: | - Session configuration to use for the client secret. Choose either a realtime - session or a transcription session. - anyOf: - - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' - - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' - discriminator: - propertyName: type - RealtimeCreateClientSecretResponse: - type: object - title: Realtime session and client secret - description: | - Response from creating a session and client secret for the Realtime API. - properties: - value: - type: string - description: The generated client secret value. - expires_at: - type: integer - description: Expiration timestamp for the client secret, in seconds since epoch. - session: - title: Session configuration - description: | - The session configuration for either a realtime or transcription session. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/RealtimeSessionCreateResponseGA' - - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponseGA' - required: - - value - - expires_at - - session - x-oaiMeta: - name: Session response object - group: realtime - example: | - { - "value": "ek_68af296e8e408191a1120ab6383263c2", - "expires_at": 1756310470, - "session": { - "type": "realtime", - "object": "realtime.session", - "id": "sess_C9CiUVUzUzYIssh3ELY1d", - "model": "gpt-realtime-2025-08-25", - "output_modalities": [ - "audio" - ], - "instructions": "You are a friendly assistant.", - "tools": [], - "tool_choice": "auto", - "max_output_tokens": "inf", - "tracing": null, - "truncation": "auto", - "prompt": null, - "expires_at": 0, - "audio": { - "input": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "transcription": null, - "noise_reduction": null, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200, - "idle_timeout_ms": null, - "create_response": true, - "interrupt_response": true - } - }, - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "alloy", - "speed": 1.0 - } - }, - "include": null - } - } - RealtimeFunctionTool: - type: object - title: Function tool - properties: - type: - type: string - enum: - - function - description: The type of the tool, i.e. `function`. - x-stainless-const: true - name: - type: string - description: The name of the function. - description: - type: string - description: | - 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). - parameters: - type: object - description: Parameters of the function in JSON Schema. - RealtimeMCPApprovalRequest: - type: object - title: Realtime MCP approval request - description: | - A Realtime item requesting human approval of a tool invocation. - properties: - type: - type: string - enum: - - mcp_approval_request - description: The type of the item. Always `mcp_approval_request`. - x-stainless-const: true - id: - type: string - description: The unique ID of the approval request. - server_label: - type: string - description: The label of the MCP server making the request. - name: - type: string - description: The name of the tool to run. - arguments: - type: string - description: A JSON string of arguments for the tool. - required: - - type - - id - - server_label - - name - - arguments - RealtimeMCPApprovalResponse: - type: object - title: Realtime MCP approval response - description: | - A Realtime item responding to an MCP approval request. - properties: - type: - type: string - enum: - - mcp_approval_response - description: The type of the item. Always `mcp_approval_response`. - x-stainless-const: true - id: - type: string - description: The unique ID of the approval response. - approval_request_id: - type: string - description: The ID of the approval request being answered. - approve: - type: boolean - description: Whether the request was approved. - reason: - anyOf: - - type: string - description: Optional reason for the decision. - - type: 'null' - required: - - type - - id - - approval_request_id - - approve - RealtimeMCPHTTPError: - type: object - title: Realtime MCP HTTP error - properties: - type: - type: string - enum: - - http_error - x-stainless-const: true - code: - type: integer - message: - type: string - required: - - type - - code - - message - RealtimeMCPListTools: - type: object - title: Realtime MCP list tools - description: | - A Realtime item listing tools available on an MCP server. - properties: - type: - type: string - enum: - - mcp_list_tools - description: The type of the item. Always `mcp_list_tools`. - x-stainless-const: true - id: - type: string - description: The unique ID of the list. - server_label: - type: string - description: The label of the MCP server. - tools: - type: array - items: - $ref: '#/components/schemas/MCPListToolsTool' - description: The tools available on the server. - required: - - type - - server_label - - tools - RealtimeMCPProtocolError: - type: object - title: Realtime MCP protocol error - properties: - type: - type: string - enum: - - protocol_error - x-stainless-const: true - code: - type: integer - message: - type: string - required: - - type - - code - - message - RealtimeMCPToolCall: - type: object - title: Realtime MCP tool call - description: | - A Realtime item representing an invocation of a tool on an MCP server. - properties: - type: - type: string - enum: - - mcp_call - description: The type of the item. Always `mcp_call`. - x-stainless-const: true - id: - type: string - description: The unique ID of the tool call. - server_label: - type: string - description: The label of the MCP server running the tool. - name: - type: string - description: The name of the tool that was run. - arguments: - type: string - description: A JSON string of the arguments passed to the tool. - approval_request_id: - anyOf: - - type: string - description: The ID of an associated approval request, if any. - - type: 'null' - output: - anyOf: - - type: string - description: The output from the tool call. - - type: 'null' - error: - anyOf: - - description: The error from the tool call, if any. - anyOf: - - $ref: '#/components/schemas/RealtimeMCPProtocolError' - - $ref: '#/components/schemas/RealtimeMCPToolExecutionError' - - $ref: '#/components/schemas/RealtimeMCPHTTPError' - discriminator: - propertyName: type - - type: 'null' - required: - - type - - id - - server_label - - name - - arguments - RealtimeMCPToolExecutionError: - type: object - title: Realtime MCP tool execution error - properties: - type: - type: string - enum: - - tool_execution_error - x-stainless-const: true - message: - type: string - required: - - type - - message - RealtimeResponse: - type: object - description: The response resource. - properties: - id: - type: string - description: The unique ID of the response, will look like `resp_1234`. - object: - description: The object type, must be `realtime.response`. - x-stainless-const: true - const: realtime.response - status: - type: string - enum: - - completed - - cancelled - - failed - - incomplete - - in_progress - description: | - The final status of the response (`completed`, `cancelled`, `failed`, or - `incomplete`, `in_progress`). - status_details: - type: object - description: Additional details about the status. - properties: - type: - type: string - enum: - - completed - - cancelled - - incomplete - - failed - description: | - The type of error that caused the response to fail, corresponding - with the `status` field (`completed`, `cancelled`, `incomplete`, - `failed`). - reason: - type: string - enum: - - turn_detected - - client_cancelled - - max_output_tokens - - content_filter - description: > - The reason the Response did not complete. For a `cancelled` Response, one of `turn_detected` - (the server VAD detected a new start of speech) or `client_cancelled` (the client sent a - cancel event). For an `incomplete` Response, one of `max_output_tokens` or `content_filter` - (the server-side safety filter activated and cut off the response). - error: - type: object - description: | - A description of the error that caused the response to fail, - populated when the `status` is `failed`. - properties: - type: - type: string - description: The type of error. - code: - type: string - description: Error code, if any. - output: - type: array - description: The list of output items generated by the response. - items: - $ref: '#/components/schemas/RealtimeConversationItem' - metadata: - $ref: '#/components/schemas/Metadata' - audio: - type: object - description: Configuration for audio output. - properties: - output: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - description: The format of the output audio. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - default: alloy - description: | - 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`. We recommend `marin` and `cedar` for - best quality. - usage: - type: object - description: | - Usage statistics for the Response, this will correspond to billing. A - Realtime API session will maintain a conversation context and append new - Items to the Conversation, thus output from previous turns (text and - audio tokens) will become the input for later turns. - properties: - total_tokens: - type: integer - description: | - The total number of tokens in the Response including input and output - text and audio tokens. - input_tokens: - type: integer - description: | - The number of input tokens used in the Response, including text and - audio tokens. - output_tokens: - type: integer - description: | - The number of output tokens sent in the Response, including text and - audio tokens. - input_token_details: - type: object - description: >- - Details about the input tokens used in the Response. Cached tokens are tokens from previous - turns in the conversation that are included as context for the current response. Cached tokens - here are counted as a subset of input tokens, meaning input tokens will include cached and - uncached tokens. - properties: - cached_tokens: - type: integer - description: The number of cached tokens used as input for the Response. - text_tokens: - type: integer - description: The number of text tokens used as input for the Response. - image_tokens: - type: integer - description: The number of image tokens used as input for the Response. - audio_tokens: - type: integer - description: The number of audio tokens used as input for the Response. - cached_tokens_details: - type: object - description: Details about the cached tokens used as input for the Response. - properties: - text_tokens: - type: integer - description: The number of cached text tokens used as input for the Response. - image_tokens: - type: integer - description: The number of cached image tokens used as input for the Response. - audio_tokens: - type: integer - description: The number of cached audio tokens used as input for the Response. - output_token_details: - type: object - description: Details about the output tokens used in the Response. - properties: - text_tokens: - type: integer - description: The number of text tokens used in the Response. - audio_tokens: - type: integer - description: The number of audio tokens used in the Response. - conversation_id: - description: | - Which conversation the response is added to, determined by the `conversation` - field in the `response.create` event. If `auto`, the response will be added to - the default conversation and the value of `conversation_id` will be an id like - `conv_1234`. If `none`, the response will not be added to any conversation and - the value of `conversation_id` will be `null`. If responses are being triggered - automatically by VAD the response will be added to the default conversation - type: string - output_modalities: - type: array - description: | - The set of modalities the model used to respond, currently the only possible values are - `[\"audio\"]`, `[\"text\"]`. Audio output always include a text transcript. Setting the - output to mode `text` will disable audio output from the model. - items: - type: string - enum: - - text - - audio - max_output_tokens: - description: | - Maximum number of output tokens for a single assistant response, - inclusive of tool calls, that was used in this response. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - RealtimeResponseCreateParams: - type: object - description: Create a new Realtime response with these parameters - properties: - output_modalities: - type: array - description: | - The set of modalities the model used to respond, currently the only possible values are - `[\"audio\"]`, `[\"text\"]`. Audio output always include a text transcript. Setting the - output to mode `text` will disable audio output from the model. - items: - type: string - enum: - - text - - audio - instructions: - type: string - description: > - 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. - audio: - type: object - description: Configuration for audio input and output. - properties: - output: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - description: The format of the output audio. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - default: alloy - description: | - 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`. We recommend `marin` and `cedar` for - best quality. - tools: - type: array - description: Tools available to the model. - items: - anyOf: - - $ref: '#/components/schemas/RealtimeFunctionTool' - - $ref: '#/components/schemas/MCPTool' - tool_choice: - description: | - How the model chooses tools. Provide one of the string modes or force a specific - function/MCP tool. - default: auto - anyOf: - - $ref: '#/components/schemas/ToolChoiceOptions' - - $ref: '#/components/schemas/ToolChoiceFunction' - - $ref: '#/components/schemas/ToolChoiceMCP' - max_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - conversation: - description: | - Controls which conversation the response is added to. Currently supports - `auto` and `none`, with `auto` as the default value. The `auto` value - means that the contents of the response will be added to the default - conversation. Set this to `none` to create an out-of-band response which - will not add items to default conversation. - anyOf: - - type: string - - type: string - default: auto - enum: - - auto - - none - metadata: - $ref: '#/components/schemas/Metadata' - prompt: - $ref: '#/components/schemas/Prompt' - input: - type: array - description: | - Input items to include in the prompt for the model. Using this field - creates a new context for this Response instead of using the default - conversation. An empty array `[]` will clear the context for this Response. - Note that this can include references to items that previously appeared in the session - using their id. - items: - $ref: '#/components/schemas/RealtimeConversationItem' - RealtimeServerEvent: - discriminator: - propertyName: type - description: | - A realtime server event. - anyOf: - - $ref: '#/components/schemas/RealtimeServerEventConversationCreated' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemCreated' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemDeleted' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionCompleted' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionDelta' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionFailed' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemRetrieved' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemTruncated' - - $ref: '#/components/schemas/RealtimeServerEventError' - - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferCleared' - - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferCommitted' - - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStarted' - - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStopped' - - $ref: '#/components/schemas/RealtimeServerEventRateLimitsUpdated' - - $ref: '#/components/schemas/RealtimeServerEventResponseAudioDelta' - - $ref: '#/components/schemas/RealtimeServerEventResponseAudioDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDelta' - - $ref: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseContentPartAdded' - - $ref: '#/components/schemas/RealtimeServerEventResponseContentPartDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseCreated' - - $ref: '#/components/schemas/RealtimeServerEventResponseDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDelta' - - $ref: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseOutputItemAdded' - - $ref: '#/components/schemas/RealtimeServerEventResponseOutputItemDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseTextDelta' - - $ref: '#/components/schemas/RealtimeServerEventResponseTextDone' - - $ref: '#/components/schemas/RealtimeServerEventSessionCreated' - - $ref: '#/components/schemas/RealtimeServerEventSessionUpdated' - - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferStarted' - - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferStopped' - - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferCleared' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemAdded' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemDone' - - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferTimeoutTriggered' - - $ref: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionSegment' - - $ref: '#/components/schemas/RealtimeServerEventMCPListToolsInProgress' - - $ref: '#/components/schemas/RealtimeServerEventMCPListToolsCompleted' - - $ref: '#/components/schemas/RealtimeServerEventMCPListToolsFailed' - - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDelta' - - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDone' - - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallInProgress' - - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallCompleted' - - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallFailed' - RealtimeServerEventConversationCreated: - type: object - description: | - Returned when a conversation is created. Emitted right after session creation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.created`. - x-stainless-const: true - const: conversation.created - conversation: - type: object - description: The conversation resource. - properties: - id: - type: string - description: The unique ID of the conversation. - object: - description: The object type, must be `realtime.conversation`. - const: realtime.conversation - required: - - event_id - - type - - conversation - x-oaiMeta: - name: conversation.created - group: realtime - example: | - { - "event_id": "event_9101", - "type": "conversation.created", - "conversation": { - "id": "conv_001", - "object": "realtime.conversation" - } - } - RealtimeServerEventConversationItemAdded: - type: object - description: > - Sent by the server when an Item is added to the default Conversation. This can happen in several - cases: - - - When the client sends a `conversation.item.create` event. - - - When the input audio buffer is committed. In this case the item will be a user message containing - the audio from the buffer. - - - When the model is generating a Response. In this case the `conversation.item.added` event will be - sent when the model starts generating a specific Item, and thus it will not yet have any content (and - `status` will be `in_progress`). - - - The event will include the full content of the Item (except when model is generating a Response) - except for audio data, which can be retrieved separately with a `conversation.item.retrieve` event if - necessary. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.added`. - x-stainless-const: true - const: conversation.item.added - previous_item_id: - anyOf: - - type: string - description: | - The ID of the item that precedes this one, if any. This is used to - maintain ordering when items are inserted. - - type: 'null' - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - item - x-oaiMeta: - name: conversation.item.added - group: realtime - example: | - { - "type": "conversation.item.added", - "event_id": "event_C9G8pjSJCfRNEhMEnYAVy", - "previous_item_id": null, - "item": { - "id": "item_C9G8pGVKYnaZu8PH5YQ9O", - "type": "message", - "status": "completed", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hi" - } - ] - } - } - RealtimeServerEventConversationItemCreated: - type: object - description: | - Returned when a conversation item is created. There are several scenarios that produce this event: - - The server is generating a Response, which if successful will produce - either one or two Items, which will be of type `message` - (role `assistant`) or type `function_call`. - - The input audio buffer has been committed, either by the client or the - server (in `server_vad` mode). The server will take the content of the - input audio buffer and add it to a new user message Item. - - The client has sent a `conversation.item.create` event to add a new Item - to the Conversation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.created`. - x-stainless-const: true - const: conversation.item.created - previous_item_id: - anyOf: - - type: string - description: | - The ID of the preceding item in the Conversation context, allows the - client to understand the order of the conversation. Can be `null` if the - item has no predecessor. - - type: 'null' - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - item - x-oaiMeta: - name: conversation.item.created - group: realtime - example: | - { - "event_id": "event_1920", - "type": "conversation.item.created", - "previous_item_id": "msg_002", - "item": { - "id": "msg_003", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "user", - "content": [] - } - } - RealtimeServerEventConversationItemDeleted: - type: object - description: | - Returned when an item in the conversation is deleted by the client with a - `conversation.item.delete` event. This event is used to synchronize the - server's understanding of the conversation history with the client's view. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.deleted`. - x-stainless-const: true - const: conversation.item.deleted - item_id: - type: string - description: The ID of the item that was deleted. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: conversation.item.deleted - group: realtime - example: | - { - "event_id": "event_2728", - "type": "conversation.item.deleted", - "item_id": "msg_005" - } - RealtimeServerEventConversationItemDone: - type: object - description: > - Returned when a conversation item is finalized. - - - The event will include the full content of the Item except for audio data, which can be retrieved - separately with a `conversation.item.retrieve` event if needed. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.done`. - x-stainless-const: true - const: conversation.item.done - previous_item_id: - anyOf: - - type: string - description: | - The ID of the item that precedes this one, if any. This is used to - maintain ordering when items are inserted. - - type: 'null' - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - item - x-oaiMeta: - name: conversation.item.done - group: realtime - example: | - { - "type": "conversation.item.done", - "event_id": "event_CCXLgMZPo3qioWCeQa4WH", - "previous_item_id": "item_CCXLecNJVIVR2HUy3ABLj", - "item": { - "id": "item_CCXLfxmM5sXVJVz4mCa2S", - "type": "message", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_audio", - "transcript": "Oh, I can hear you loud and clear! Sounds like we're connected just fine. What can I help you with today?" - } - ] - } - } - RealtimeServerEventConversationItemInputAudioTranscriptionCompleted: - type: object - description: | - This event is the output of audio transcription for user audio written to the - user audio buffer. Transcription begins when the input audio buffer is - committed by the client or server (when VAD is enabled). Transcription runs - asynchronously with Response creation, so this event may come before or after - the Response events. - - Realtime API models accept audio natively, and thus input transcription is a - separate process run on a separate ASR (Automatic Speech Recognition) model. - The transcript may diverge somewhat from the model's interpretation, and - should be treated as a rough guide. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - type: string - enum: - - conversation.item.input_audio_transcription.completed - description: | - The event type, must be - `conversation.item.input_audio_transcription.completed`. - x-stainless-const: true - item_id: - type: string - description: The ID of the item containing the audio that is being transcribed. - content_index: - type: integer - description: The index of the content part containing the audio. - transcript: - type: string - description: The transcribed text. - logprobs: - anyOf: - - type: array - description: The log probabilities of the transcription. - items: - $ref: '#/components/schemas/LogProbProperties' - - type: 'null' - usage: - type: object - description: >- - Usage statistics for the transcription, this is billed according to the ASR model's pricing rather - than the realtime model's pricing. - anyOf: - - $ref: '#/components/schemas/TranscriptTextUsageTokens' - title: TranscriptTextUsageTokens - - $ref: '#/components/schemas/TranscriptTextUsageDuration' - title: TranscriptTextUsageDuration - required: - - event_id - - type - - item_id - - content_index - - transcript - - usage - x-oaiMeta: - name: conversation.item.input_audio_transcription.completed - group: realtime - example: | - { - "type": "conversation.item.input_audio_transcription.completed", - "event_id": "event_CCXGRvtUVrax5SJAnNOWZ", - "item_id": "item_CCXGQ4e1ht4cOraEYcuR2", - "content_index": 0, - "transcript": "Hey, can you hear me?", - "usage": { - "type": "tokens", - "total_tokens": 22, - "input_tokens": 13, - "input_token_details": { - "text_tokens": 0, - "audio_tokens": 13 - }, - "output_tokens": 9 - } - } - RealtimeServerEventConversationItemInputAudioTranscriptionDelta: - type: object - description: > - Returned when the text value of an input audio transcription content part is updated with incremental - transcription results. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.input_audio_transcription.delta`. - x-stainless-const: true - const: conversation.item.input_audio_transcription.delta - item_id: - type: string - description: The ID of the item containing the audio that is being transcribed. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: The text delta. - logprobs: - anyOf: - - type: array - description: >- - The log probabilities of the transcription. These can be enabled by configurating the session - with `"include": ["item.input_audio_transcription.logprobs"]`. Each entry in the array - corresponds a log probability of which token would be selected for this chunk of - transcription. This can help to identify if it was possible there were multiple valid options - for a given chunk of transcription. - items: - $ref: '#/components/schemas/LogProbProperties' - - type: 'null' - required: - - event_id - - type - - item_id - x-oaiMeta: - name: conversation.item.input_audio_transcription.delta - group: realtime - example: | - { - "type": "conversation.item.input_audio_transcription.delta", - "event_id": "event_CCXGRxsAimPAs8kS2Wc7Z", - "item_id": "item_CCXGQ4e1ht4cOraEYcuR2", - "content_index": 0, - "delta": "Hey", - "obfuscation": "aLxx0jTEciOGe" - } - RealtimeServerEventConversationItemInputAudioTranscriptionFailed: - type: object - description: | - Returned when input audio transcription is configured, and a transcription - request for a user message failed. These events are separate from other - `error` events so that the client can identify the related Item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - type: string - enum: - - conversation.item.input_audio_transcription.failed - description: | - The event type, must be - `conversation.item.input_audio_transcription.failed`. - x-stainless-const: true - item_id: - type: string - description: The ID of the user message item. - content_index: - type: integer - description: The index of the content part containing the audio. - error: - type: object - description: Details of the transcription error. - properties: - type: - type: string - description: The type of error. - code: - type: string - description: Error code, if any. - message: - type: string - description: A human-readable error message. - param: - type: string - description: Parameter related to the error, if any. - required: - - event_id - - type - - item_id - - content_index - - error - x-oaiMeta: - name: conversation.item.input_audio_transcription.failed - group: realtime - example: | - { - "event_id": "event_2324", - "type": "conversation.item.input_audio_transcription.failed", - "item_id": "msg_003", - "content_index": 0, - "error": { - "type": "transcription_error", - "code": "audio_unintelligible", - "message": "The audio could not be transcribed.", - "param": null - } - } - RealtimeServerEventConversationItemInputAudioTranscriptionSegment: - type: object - description: Returned when an input audio transcription segment is identified for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.input_audio_transcription.segment`. - x-stainless-const: true - const: conversation.item.input_audio_transcription.segment - item_id: - type: string - description: The ID of the item containing the input audio content. - content_index: - type: integer - description: The index of the input audio content part within the item. - text: - type: string - description: The text for this segment. - id: - type: string - description: The segment identifier. - speaker: - type: string - description: The detected speaker label for this segment. - start: - type: number - format: float - description: Start time of the segment in seconds. - end: - type: number - format: float - description: End time of the segment in seconds. - required: - - event_id - - type - - item_id - - content_index - - text - - id - - speaker - - start - - end - x-oaiMeta: - name: conversation.item.input_audio_transcription.segment - group: realtime - example: | - { - "event_id": "event_6501", - "type": "conversation.item.input_audio_transcription.segment", - "item_id": "msg_011", - "content_index": 0, - "text": "hello", - "id": "seg_0001", - "speaker": "spk_1", - "start": 0.0, - "end": 0.4 - } - RealtimeServerEventConversationItemRetrieved: - type: object - description: > - Returned when a conversation item is retrieved with `conversation.item.retrieve`. This is provided as - a way to fetch the server's representation of an item, for example to get access to the post-processed - audio data after noise cancellation and VAD. It includes the full content of the Item, including audio - data. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.retrieved`. - x-stainless-const: true - const: conversation.item.retrieved - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - item - x-oaiMeta: - name: conversation.item.retrieved - group: realtime - example: | - { - "type": "conversation.item.retrieved", - "event_id": "event_CCXGSizgEppa2d4XbKA7K", - "item": { - "id": "item_CCXGRxbY0n6WE4EszhF5w", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "audio", - "transcript": "Yes, I can hear you loud and clear. How can I help you today?", - "audio": "8//2//v/9//q/+//+P/s...", - "format": "pcm16" - } - ] - } - } - RealtimeServerEventConversationItemTruncated: - type: object - description: | - Returned when an earlier assistant audio message item is truncated by the - client with a `conversation.item.truncate` event. This event is used to - synchronize the server's understanding of the audio with the client's playback. - - This action will truncate the audio and remove the server-side text transcript - to ensure there is no text in the context that hasn't been heard by the user. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `conversation.item.truncated`. - x-stainless-const: true - const: conversation.item.truncated - item_id: - type: string - description: The ID of the assistant message item that was truncated. - content_index: - type: integer - description: The index of the content part that was truncated. - audio_end_ms: - type: integer - description: | - The duration up to which the audio was truncated, in milliseconds. - required: - - event_id - - type - - item_id - - content_index - - audio_end_ms - x-oaiMeta: - name: conversation.item.truncated - group: realtime - example: | - { - "event_id": "event_2526", - "type": "conversation.item.truncated", - "item_id": "msg_004", - "content_index": 0, - "audio_end_ms": 1500 - } - RealtimeServerEventError: - type: object - description: | - Returned when an error occurs, which could be a client problem or a server - problem. Most errors are recoverable and the session will stay open, we - recommend to implementors to monitor and log error messages by default. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `error`. - x-stainless-const: true - const: error - error: - type: object - description: Details of the error. - required: - - type - - message - properties: - type: - type: string - description: | - The type of error (e.g., "invalid_request_error", "server_error"). - code: - anyOf: - - type: string - description: Error code, if any. - - type: 'null' - message: - type: string - description: A human-readable error message. - param: - anyOf: - - type: string - description: Parameter related to the error, if any. - - type: 'null' - event_id: - anyOf: - - type: string - description: | - The event_id of the client event that caused the error, if applicable. - - type: 'null' - required: - - event_id - - type - - error - x-oaiMeta: - name: error - group: realtime - example: | - { - "event_id": "event_890", - "type": "error", - "error": { - "type": "invalid_request_error", - "code": "invalid_event", - "message": "The 'type' field is missing.", - "param": null, - "event_id": "event_567" - } - } - RealtimeServerEventInputAudioBufferCleared: - type: object - description: | - Returned when the input audio buffer is cleared by the client with a - `input_audio_buffer.clear` event. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.cleared`. - x-stainless-const: true - const: input_audio_buffer.cleared - required: - - event_id - - type - x-oaiMeta: - name: input_audio_buffer.cleared - group: realtime - example: | - { - "event_id": "event_1314", - "type": "input_audio_buffer.cleared" - } - RealtimeServerEventInputAudioBufferCommitted: - type: object - description: | - Returned when an input audio buffer is committed, either by the client or - automatically in server VAD mode. The `item_id` property is the ID of the user - message item that will be created, thus a `conversation.item.created` event - will also be sent to the client. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.committed`. - x-stainless-const: true - const: input_audio_buffer.committed - previous_item_id: - anyOf: - - type: string - description: | - The ID of the preceding item after which the new item will be inserted. - Can be `null` if the item has no predecessor. - - type: 'null' - item_id: - type: string - description: The ID of the user message item that will be created. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: input_audio_buffer.committed - group: realtime - example: | - { - "event_id": "event_1121", - "type": "input_audio_buffer.committed", - "previous_item_id": "msg_001", - "item_id": "msg_002" - } - RealtimeServerEventInputAudioBufferSpeechStarted: - type: object - description: | - Sent by the server when in `server_vad` mode to indicate that speech has been - detected in the audio buffer. This can happen any time audio is added to the - buffer (unless speech is already detected). The client may want to use this - event to interrupt audio playback or provide visual feedback to the user. - - The client should expect to receive a `input_audio_buffer.speech_stopped` event - when speech stops. The `item_id` property is the ID of the user message item - that will be created when speech stops and will also be included in the - `input_audio_buffer.speech_stopped` event (unless the client manually commits - the audio buffer during VAD activation). - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.speech_started`. - x-stainless-const: true - const: input_audio_buffer.speech_started - audio_start_ms: - type: integer - description: | - Milliseconds from the start of all audio written to the buffer during the - session when speech was first detected. This will correspond to the - beginning of audio sent to the model, and thus includes the - `prefix_padding_ms` configured in the Session. - item_id: - type: string - description: | - The ID of the user message item that will be created when speech stops. - required: - - event_id - - type - - audio_start_ms - - item_id - x-oaiMeta: - name: input_audio_buffer.speech_started - group: realtime - example: | - { - "event_id": "event_1516", - "type": "input_audio_buffer.speech_started", - "audio_start_ms": 1000, - "item_id": "msg_003" - } - RealtimeServerEventInputAudioBufferSpeechStopped: - type: object - description: | - Returned in `server_vad` mode when the server detects the end of speech in - the audio buffer. The server will also send an `conversation.item.created` - event with the user message item that is created from the audio buffer. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.speech_stopped`. - x-stainless-const: true - const: input_audio_buffer.speech_stopped - audio_end_ms: - type: integer - description: | - Milliseconds since the session started when speech stopped. This will - correspond to the end of audio sent to the model, and thus includes the - `min_silence_duration_ms` configured in the Session. - item_id: - type: string - description: The ID of the user message item that will be created. - required: - - event_id - - type - - audio_end_ms - - item_id - x-oaiMeta: - name: input_audio_buffer.speech_stopped - group: realtime - example: | - { - "event_id": "event_1718", - "type": "input_audio_buffer.speech_stopped", - "audio_end_ms": 2000, - "item_id": "msg_003" - } - RealtimeServerEventInputAudioBufferTimeoutTriggered: - type: object - description: | - Returned when the Server VAD timeout is triggered for the input audio buffer. This is configured - with `idle_timeout_ms` in the `turn_detection` settings of the session, and it indicates that - there hasn't been any speech detected for the configured duration. - - The `audio_start_ms` and `audio_end_ms` fields indicate the segment of audio after the last - model response up to the triggering time, as an offset from the beginning of audio written - to the input audio buffer. This means it demarcates the segment of audio that was silent and - the difference between the start and end values will roughly match the configured timeout. - - The empty audio will be committed to the conversation as an `input_audio` item (there will be a - `input_audio_buffer.committed` event) and a model response will be generated. There may be speech - that didn't trigger VAD but is still detected by the model, so the model may respond with - something relevant to the conversation or a prompt to continue speaking. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `input_audio_buffer.timeout_triggered`. - x-stainless-const: true - const: input_audio_buffer.timeout_triggered - audio_start_ms: - type: integer - description: >- - Millisecond offset of audio written to the input audio buffer that was after the playback time of - the last model response. - audio_end_ms: - type: integer - description: >- - Millisecond offset of audio written to the input audio buffer at the time the timeout was - triggered. - item_id: - type: string - description: The ID of the item associated with this segment. - required: - - event_id - - type - - audio_start_ms - - audio_end_ms - - item_id - x-oaiMeta: - name: input_audio_buffer.timeout_triggered - group: realtime - example: | - { - "type":"input_audio_buffer.timeout_triggered", - "event_id":"event_CEKKrf1KTGvemCPyiJTJ2", - "audio_start_ms":13216, - "audio_end_ms":19232, - "item_id":"item_CEKKrWH0GiwN0ET97NUZc" - } - RealtimeServerEventMCPListToolsCompleted: - type: object - description: Returned when listing MCP tools has completed for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `mcp_list_tools.completed`. - x-stainless-const: true - const: mcp_list_tools.completed - item_id: - type: string - description: The ID of the MCP list tools item. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: mcp_list_tools.completed - group: realtime - example: | - { - "event_id": "event_6102", - "type": "mcp_list_tools.completed", - "item_id": "mcp_list_tools_001" - } - RealtimeServerEventMCPListToolsFailed: - type: object - description: Returned when listing MCP tools has failed for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `mcp_list_tools.failed`. - x-stainless-const: true - const: mcp_list_tools.failed - item_id: - type: string - description: The ID of the MCP list tools item. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: mcp_list_tools.failed - group: realtime - example: | - { - "event_id": "event_6103", - "type": "mcp_list_tools.failed", - "item_id": "mcp_list_tools_001" - } - RealtimeServerEventMCPListToolsInProgress: - type: object - description: Returned when listing MCP tools is in progress for an item. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `mcp_list_tools.in_progress`. - x-stainless-const: true - const: mcp_list_tools.in_progress - item_id: - type: string - description: The ID of the MCP list tools item. - required: - - event_id - - type - - item_id - x-oaiMeta: - name: mcp_list_tools.in_progress - group: realtime - example: | - { - "event_id": "event_6101", - "type": "mcp_list_tools.in_progress", - "item_id": "mcp_list_tools_001" - } - RealtimeServerEventOutputAudioBufferCleared: - type: object - description: > - **WebRTC Only:** Emitted when the output audio buffer is cleared. This happens either in VAD - - mode when the user has interrupted (`input_audio_buffer.speech_started`), - - or when the client has emitted the `output_audio_buffer.clear` event to manually - - cut off the current audio response. - - [Learn - more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `output_audio_buffer.cleared`. - x-stainless-const: true - const: output_audio_buffer.cleared - response_id: - type: string - description: The unique ID of the response that produced the audio. - required: - - event_id - - type - - response_id - x-oaiMeta: - name: output_audio_buffer.cleared - group: realtime - example: | - { - "event_id": "event_abc123", - "type": "output_audio_buffer.cleared", - "response_id": "resp_abc123" - } - RealtimeServerEventOutputAudioBufferStarted: - type: object - description: > - **WebRTC Only:** Emitted when the server begins streaming audio to the client. This event is - - emitted after an audio content part has been added (`response.content_part.added`) - - to the response. - - [Learn - more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `output_audio_buffer.started`. - x-stainless-const: true - const: output_audio_buffer.started - response_id: - type: string - description: The unique ID of the response that produced the audio. - required: - - event_id - - type - - response_id - x-oaiMeta: - name: output_audio_buffer.started - group: realtime - example: | - { - "event_id": "event_abc123", - "type": "output_audio_buffer.started", - "response_id": "resp_abc123" - } - RealtimeServerEventOutputAudioBufferStopped: - type: object - description: > - **WebRTC Only:** Emitted when the output audio buffer has been completely drained on the server, - - and no more audio is forthcoming. This event is emitted after the full response - - data has been sent to the client (`response.done`). - - [Learn - more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `output_audio_buffer.stopped`. - x-stainless-const: true - const: output_audio_buffer.stopped - response_id: - type: string - description: The unique ID of the response that produced the audio. - required: - - event_id - - type - - response_id - x-oaiMeta: - name: output_audio_buffer.stopped - group: realtime - example: | - { - "event_id": "event_abc123", - "type": "output_audio_buffer.stopped", - "response_id": "resp_abc123" - } - RealtimeServerEventRateLimitsUpdated: - type: object - description: | - Emitted at the beginning of a Response to indicate the updated rate limits. - When a Response is created some tokens will be "reserved" for the output - tokens, the rate limits shown here reflect that reservation, which is then - adjusted accordingly once the Response is completed. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `rate_limits.updated`. - x-stainless-const: true - const: rate_limits.updated - rate_limits: - type: array - description: List of rate limit information. - items: - type: object - properties: - name: - type: string - enum: - - requests - - tokens - description: | - The name of the rate limit (`requests`, `tokens`). - limit: - type: integer - description: The maximum allowed value for the rate limit. - remaining: - type: integer - description: The remaining value before the limit is reached. - reset_seconds: - type: number - description: Seconds until the rate limit resets. - required: - - event_id - - type - - rate_limits - x-oaiMeta: - name: rate_limits.updated - group: realtime - example: | - { - "event_id": "event_5758", - "type": "rate_limits.updated", - "rate_limits": [ - { - "name": "requests", - "limit": 1000, - "remaining": 999, - "reset_seconds": 60 - }, - { - "name": "tokens", - "limit": 50000, - "remaining": 49950, - "reset_seconds": 60 - } - ] - } - RealtimeServerEventResponseAudioDelta: - type: object - description: Returned when the model-generated audio is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio.delta`. - x-stainless-const: true - const: response.output_audio.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: Base64-encoded audio data delta. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - delta - x-oaiMeta: - name: response.output_audio.delta - group: realtime - example: | - { - "event_id": "event_4950", - "type": "response.output_audio.delta", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0, - "delta": "Base64EncodedAudioDelta" - } - RealtimeServerEventResponseAudioDone: - type: object - description: | - Returned when the model-generated audio is done. Also emitted when a Response - is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio.done`. - x-stainless-const: true - const: response.output_audio.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - x-oaiMeta: - name: response.output_audio.done - group: realtime - example: | - { - "event_id": "event_5152", - "type": "response.output_audio.done", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0 - } - RealtimeServerEventResponseAudioTranscriptDelta: - type: object - description: | - Returned when the model-generated transcription of audio output is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio_transcript.delta`. - x-stainless-const: true - const: response.output_audio_transcript.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: The transcript delta. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - delta - x-oaiMeta: - name: response.output_audio_transcript.delta - group: realtime - example: | - { - "event_id": "event_4546", - "type": "response.output_audio_transcript.delta", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0, - "delta": "Hello, how can I a" - } - RealtimeServerEventResponseAudioTranscriptDone: - type: object - description: | - Returned when the model-generated transcription of audio output is done - streaming. Also emitted when a Response is interrupted, incomplete, or - cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_audio_transcript.done`. - x-stainless-const: true - const: response.output_audio_transcript.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - transcript: - type: string - description: The final transcript of the audio. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - transcript - x-oaiMeta: - name: response.output_audio_transcript.done - group: realtime - example: | - { - "event_id": "event_4748", - "type": "response.output_audio_transcript.done", - "response_id": "resp_001", - "item_id": "msg_008", - "output_index": 0, - "content_index": 0, - "transcript": "Hello, how can I assist you today?" - } - RealtimeServerEventResponseContentPartAdded: - type: object - description: | - Returned when a new content part is added to an assistant message item during - response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.content_part.added`. - x-stainless-const: true - const: response.content_part.added - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item to which the content part was added. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - part: - type: object - description: The content part that was added. - properties: - type: - type: string - enum: - - text - - audio - description: The content type ("text", "audio"). - text: - type: string - description: The text content (if type is "text"). - audio: - type: string - description: Base64-encoded audio data (if type is "audio"). - transcript: - type: string - description: The transcript of the audio (if type is "audio"). - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - part - x-oaiMeta: - name: response.content_part.added - group: realtime - example: | - { - "event_id": "event_3738", - "type": "response.content_part.added", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "part": { - "type": "text", - "text": "" - } - } - RealtimeServerEventResponseContentPartDone: - type: object - description: | - Returned when a content part is done streaming in an assistant message item. - Also emitted when a Response is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.content_part.done`. - x-stainless-const: true - const: response.content_part.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - part: - type: object - description: The content part that is done. - properties: - type: - type: string - enum: - - text - - audio - description: The content type ("text", "audio"). - text: - type: string - description: The text content (if type is "text"). - audio: - type: string - description: Base64-encoded audio data (if type is "audio"). - transcript: - type: string - description: The transcript of the audio (if type is "audio"). - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - part - x-oaiMeta: - name: response.content_part.done - group: realtime - example: | - { - "event_id": "event_3940", - "type": "response.content_part.done", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "part": { - "type": "text", - "text": "Sure, I can help with that." - } - } - RealtimeServerEventResponseCreated: - type: object - description: | - Returned when a new Response is created. The first event of response creation, - where the response is in an initial state of `in_progress`. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.created`. - x-stainless-const: true - const: response.created - response: - $ref: '#/components/schemas/RealtimeResponse' - required: - - event_id - - type - - response - x-oaiMeta: - name: response.created - group: realtime - example: | - { - "type": "response.created", - "event_id": "event_C9G8pqbTEddBSIxbBN6Os", - "response": { - "object": "realtime.response", - "id": "resp_C9G8p7IH2WxLbkgPNouYL", - "status": "in_progress", - "status_details": null, - "output": [], - "conversation_id": "conv_C9G8mmBkLhQJwCon3hoJN", - "output_modalities": [ - "audio" - ], - "max_output_tokens": "inf", - "audio": { - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "marin" - } - }, - "usage": null, - "metadata": null - }, - } - RealtimeServerEventResponseDone: - type: object - description: | - Returned when a Response is done streaming. Always emitted, no matter the - final state. The Response object included in the `response.done` event will - include all output Items in the Response but will omit the raw audio data. - - Clients should check the `status` field of the Response to determine if it was successful - (`completed`) or if there was another outcome: `cancelled`, `failed`, or `incomplete`. - - A response will contain all output items that were generated during the response, excluding - any audio content. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.done`. - x-stainless-const: true - const: response.done - response: - $ref: '#/components/schemas/RealtimeResponse' - required: - - event_id - - type - - response - x-oaiMeta: - name: response.done - group: realtime - example: | - { - "type": "response.done", - "event_id": "event_CCXHxcMy86rrKhBLDdqCh", - "response": { - "object": "realtime.response", - "id": "resp_CCXHw0UJld10EzIUXQCNh", - "status": "completed", - "status_details": null, - "output": [ - { - "id": "item_CCXHwGjjDUfOXbiySlK7i", - "type": "message", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "output_audio", - "transcript": "Loud and clear! I can hear you perfectly. How can I help you today?" - } - ] - } - ], - "conversation_id": "conv_CCXHsurMKcaVxIZvaCI5m", - "output_modalities": [ - "audio" - ], - "max_output_tokens": "inf", - "audio": { - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "alloy" - } - }, - "usage": { - "total_tokens": 253, - "input_tokens": 132, - "output_tokens": 121, - "input_token_details": { - "text_tokens": 119, - "audio_tokens": 13, - "image_tokens": 0, - "cached_tokens": 64, - "cached_tokens_details": { - "text_tokens": 64, - "audio_tokens": 0, - "image_tokens": 0 - } - }, - "output_token_details": { - "text_tokens": 30, - "audio_tokens": 91 - } - }, - "metadata": null - } - } - RealtimeServerEventResponseFunctionCallArgumentsDelta: - type: object - description: | - Returned when the model-generated function call arguments are updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: | - The event type, must be `response.function_call_arguments.delta`. - x-stainless-const: true - const: response.function_call_arguments.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the function call item. - output_index: - type: integer - description: The index of the output item in the response. - call_id: - type: string - description: The ID of the function call. - delta: - type: string - description: The arguments delta as a JSON string. - required: - - event_id - - type - - response_id - - item_id - - output_index - - call_id - - delta - x-oaiMeta: - name: response.function_call_arguments.delta - group: realtime - example: | - { - "event_id": "event_5354", - "type": "response.function_call_arguments.delta", - "response_id": "resp_002", - "item_id": "fc_001", - "output_index": 0, - "call_id": "call_001", - "delta": "{\"location\": \"San\"" - } - RealtimeServerEventResponseFunctionCallArgumentsDone: - type: object - description: | - Returned when the model-generated function call arguments are done streaming. - Also emitted when a Response is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: | - The event type, must be `response.function_call_arguments.done`. - x-stainless-const: true - const: response.function_call_arguments.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the function call item. - output_index: - type: integer - description: The index of the output item in the response. - call_id: - type: string - description: The ID of the function call. - arguments: - type: string - description: The final arguments as a JSON string. - required: - - event_id - - type - - response_id - - item_id - - output_index - - call_id - - arguments - x-oaiMeta: - name: response.function_call_arguments.done - group: realtime - example: | - { - "event_id": "event_5556", - "type": "response.function_call_arguments.done", - "response_id": "resp_002", - "item_id": "fc_001", - "output_index": 0, - "call_id": "call_001", - "arguments": "{\"location\": \"San Francisco\"}" - } - RealtimeServerEventResponseMCPCallArgumentsDelta: - type: object - description: Returned when MCP tool call arguments are updated during response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call_arguments.delta`. - x-stainless-const: true - const: response.mcp_call_arguments.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the MCP tool call item. - output_index: - type: integer - description: The index of the output item in the response. - delta: - type: string - description: The JSON-encoded arguments delta. - obfuscation: - anyOf: - - type: string - description: If present, indicates the delta text was obfuscated. - - type: 'null' - required: - - event_id - - type - - response_id - - item_id - - output_index - - delta - x-oaiMeta: - name: response.mcp_call_arguments.delta - group: realtime - example: | - { - "event_id": "event_6201", - "type": "response.mcp_call_arguments.delta", - "response_id": "resp_001", - "item_id": "mcp_call_001", - "output_index": 0, - "delta": "{\"partial\":true}" - } - RealtimeServerEventResponseMCPCallArgumentsDone: - type: object - description: Returned when MCP tool call arguments are finalized during response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call_arguments.done`. - x-stainless-const: true - const: response.mcp_call_arguments.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the MCP tool call item. - output_index: - type: integer - description: The index of the output item in the response. - arguments: - type: string - description: The final JSON-encoded arguments string. - required: - - event_id - - type - - response_id - - item_id - - output_index - - arguments - x-oaiMeta: - name: response.mcp_call_arguments.done - group: realtime - example: | - { - "event_id": "event_6202", - "type": "response.mcp_call_arguments.done", - "response_id": "resp_001", - "item_id": "mcp_call_001", - "output_index": 0, - "arguments": "{\"q\":\"docs\"}" - } - RealtimeServerEventResponseMCPCallCompleted: - type: object - description: Returned when an MCP tool call has completed successfully. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call.completed`. - x-stainless-const: true - const: response.mcp_call.completed - output_index: - type: integer - description: The index of the output item in the response. - item_id: - type: string - description: The ID of the MCP tool call item. - required: - - event_id - - type - - output_index - - item_id - x-oaiMeta: - name: response.mcp_call.completed - group: realtime - example: | - { - "event_id": "event_6302", - "type": "response.mcp_call.completed", - "output_index": 0, - "item_id": "mcp_call_001" - } - RealtimeServerEventResponseMCPCallFailed: - type: object - description: Returned when an MCP tool call has failed. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call.failed`. - x-stainless-const: true - const: response.mcp_call.failed - output_index: - type: integer - description: The index of the output item in the response. - item_id: - type: string - description: The ID of the MCP tool call item. - required: - - event_id - - type - - output_index - - item_id - x-oaiMeta: - name: response.mcp_call.failed - group: realtime - example: | - { - "event_id": "event_6303", - "type": "response.mcp_call.failed", - "output_index": 0, - "item_id": "mcp_call_001" - } - RealtimeServerEventResponseMCPCallInProgress: - type: object - description: Returned when an MCP tool call has started and is in progress. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.mcp_call.in_progress`. - x-stainless-const: true - const: response.mcp_call.in_progress - output_index: - type: integer - description: The index of the output item in the response. - item_id: - type: string - description: The ID of the MCP tool call item. - required: - - event_id - - type - - output_index - - item_id - x-oaiMeta: - name: response.mcp_call.in_progress - group: realtime - example: | - { - "event_id": "event_6301", - "type": "response.mcp_call.in_progress", - "output_index": 0, - "item_id": "mcp_call_001" - } - RealtimeServerEventResponseOutputItemAdded: - type: object - description: Returned when a new Item is created during Response generation. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_item.added`. - x-stainless-const: true - const: response.output_item.added - response_id: - type: string - description: The ID of the Response to which the item belongs. - output_index: - type: integer - description: The index of the output item in the Response. - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - response_id - - output_index - - item - x-oaiMeta: - name: response.output_item.added - group: realtime - example: | - { - "event_id": "event_3334", - "type": "response.output_item.added", - "response_id": "resp_001", - "output_index": 0, - "item": { - "id": "msg_007", - "object": "realtime.item", - "type": "message", - "status": "in_progress", - "role": "assistant", - "content": [] - } - } - RealtimeServerEventResponseOutputItemDone: - type: object - description: | - Returned when an Item is done streaming. Also emitted when a Response is - interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_item.done`. - x-stainless-const: true - const: response.output_item.done - response_id: - type: string - description: The ID of the Response to which the item belongs. - output_index: - type: integer - description: The index of the output item in the Response. - item: - $ref: '#/components/schemas/RealtimeConversationItem' - required: - - event_id - - type - - response_id - - output_index - - item - x-oaiMeta: - name: response.output_item.done - group: realtime - example: | - { - "event_id": "event_3536", - "type": "response.output_item.done", - "response_id": "resp_001", - "output_index": 0, - "item": { - "id": "msg_007", - "object": "realtime.item", - "type": "message", - "status": "completed", - "role": "assistant", - "content": [ - { - "type": "text", - "text": "Sure, I can help with that." - } - ] - } - } - RealtimeServerEventResponseTextDelta: - type: object - description: Returned when the text value of an "output_text" content part is updated. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_text.delta`. - x-stainless-const: true - const: response.output_text.delta - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - delta: - type: string - description: The text delta. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - delta - x-oaiMeta: - name: response.output_text.delta - group: realtime - example: | - { - "event_id": "event_4142", - "type": "response.output_text.delta", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "delta": "Sure, I can h" - } - RealtimeServerEventResponseTextDone: - type: object - description: | - Returned when the text value of an "output_text" content part is done streaming. Also - emitted when a Response is interrupted, incomplete, or cancelled. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `response.output_text.done`. - x-stainless-const: true - const: response.output_text.done - response_id: - type: string - description: The ID of the response. - item_id: - type: string - description: The ID of the item. - output_index: - type: integer - description: The index of the output item in the response. - content_index: - type: integer - description: The index of the content part in the item's content array. - text: - type: string - description: The final text content. - required: - - event_id - - type - - response_id - - item_id - - output_index - - content_index - - text - x-oaiMeta: - name: response.output_text.done - group: realtime - example: | - { - "event_id": "event_4344", - "type": "response.output_text.done", - "response_id": "resp_001", - "item_id": "msg_007", - "output_index": 0, - "content_index": 0, - "text": "Sure, I can help with that." - } - RealtimeServerEventSessionCreated: - type: object - description: | - Returned when a Session is created. Emitted automatically when a new - connection is established as the first server event. This event will contain - the default Session configuration. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `session.created`. - x-stainless-const: true - const: session.created - session: - description: The session configuration. - anyOf: - - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' - - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' - required: - - event_id - - type - - session - x-oaiMeta: - name: session.created - group: realtime - example: | - { - "type": "session.created", - "event_id": "event_C9G5RJeJ2gF77mV7f2B1j", - "session": { - "type": "realtime", - "object": "realtime.session", - "id": "sess_C9G5QPteg4UIbotdKLoYQ", - "model": "gpt-realtime-2025-08-28", - "output_modalities": [ - "audio" - ], - "instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.", - "tools": [], - "tool_choice": "auto", - "max_output_tokens": "inf", - "tracing": null, - "prompt": null, - "expires_at": 1756324625, - "audio": { - "input": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "transcription": null, - "noise_reduction": null, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200, - "idle_timeout_ms": null, - "create_response": true, - "interrupt_response": true - } - }, - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "marin", - "speed": 1 - } - }, - "include": null - }, - } - RealtimeServerEventSessionUpdated: - type: object - description: | - Returned when a session is updated with a `session.update` event, unless - there is an error. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `session.updated`. - x-stainless-const: true - const: session.updated - session: - description: The session configuration. - anyOf: - - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' - - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' - required: - - event_id - - type - - session - x-oaiMeta: - name: session.updated - group: realtime - example: | - { - "type": "session.updated", - "event_id": "event_C9G8mqI3IucaojlVKE8Cs", - "session": { - "type": "realtime", - "object": "realtime.session", - "id": "sess_C9G8l3zp50uFv4qgxfJ8o", - "model": "gpt-realtime-2025-08-28", - "output_modalities": [ - "audio" - ], - "instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.", - "tools": [ - { - "type": "function", - "name": "display_color_palette", - "description": "\nCall this function when a user asks for a color palette.\n", - "parameters": { - "type": "object", - "strict": true, - "properties": { - "theme": { - "type": "string", - "description": "Description of the theme for the color scheme." - }, - "colors": { - "type": "array", - "description": "Array of five hex color codes based on the theme.", - "items": { - "type": "string", - "description": "Hex color code" - } - } - }, - "required": [ - "theme", - "colors" - ] - } - } - ], - "tool_choice": "auto", - "max_output_tokens": "inf", - "tracing": null, - "prompt": null, - "expires_at": 1756324832, - "audio": { - "input": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "transcription": null, - "noise_reduction": null, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200, - "idle_timeout_ms": null, - "create_response": true, - "interrupt_response": true - } - }, - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "marin", - "speed": 1 - } - }, - "include": null - }, - } - RealtimeServerEventTranscriptionSessionUpdated: - type: object - description: | - Returned when a transcription session is updated with a `transcription_session.update` event, unless - there is an error. - properties: - event_id: - type: string - description: The unique ID of the server event. - type: - description: The event type, must be `transcription_session.updated`. - x-stainless-const: true - const: transcription_session.updated - session: - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' - required: - - event_id - - type - - session - x-oaiMeta: - name: transcription_session.updated - group: realtime - example: | - { - "event_id": "event_5678", - "type": "transcription_session.updated", - "session": { - "id": "sess_001", - "object": "realtime.transcription_session", - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "prompt": "", - "language": "" - }, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 500, - "create_response": true, - // "interrupt_response": false -- this will NOT be returned - }, - "input_audio_noise_reduction": { - "type": "near_field" - }, - "include": [ - "item.input_audio_transcription.avg_logprob", - ], - } - } - RealtimeSession: - type: object - description: Realtime session object for the beta interface. - properties: - id: - type: string - description: | - Unique identifier for the session that looks like `sess_1234567890abcdef`. - object: - type: string - enum: - - realtime.session - description: The object type. Always `realtime.session`. - modalities: - description: | - The set of modalities the model can respond with. To disable audio, - set this to ["text"]. - items: - type: string - enum: - - text - - audio - model: - type: string - description: | - The Realtime model used for this session. - enum: - - gpt-realtime - - gpt-realtime-2025-08-28 - - gpt-4o-realtime-preview - - gpt-4o-realtime-preview-2024-10-01 - - gpt-4o-realtime-preview-2024-12-17 - - gpt-4o-realtime-preview-2025-06-03 - - gpt-4o-mini-realtime-preview - - gpt-4o-mini-realtime-preview-2024-12-17 - - gpt-realtime-mini - - gpt-realtime-mini-2025-10-06 - - gpt-audio-mini - - gpt-audio-mini-2025-10-06 - instructions: - type: string - description: | - 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. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - description: | - 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`, and `verse`. - input_audio_format: - type: string - default: pcm16 - enum: - - pcm16 - - g711_ulaw - - g711_alaw - description: | - 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. - output_audio_format: - type: string - default: pcm16 - enum: - - pcm16 - - g711_ulaw - - g711_alaw - description: | - The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. - For `pcm16`, output audio is sampled at a rate of 24kHz. - input_audio_transcription: - anyOf: - - allOf: - - $ref: '#/components/schemas/AudioTranscription' - description: > - 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: 'null' - turn_detection: - $ref: '#/components/schemas/RealtimeTurnDetection' - input_audio_noise_reduction: - type: object - description: > - 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. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - speed: - type: number - default: 1 - maximum: 1.5 - minimum: 0.25 - description: | - 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. - tracing: - anyOf: - - title: Tracing Configuration - description: | - 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. - anyOf: - - type: string - default: auto - description: | - Default tracing mode for the session. - enum: - - auto - x-stainless-const: true - - type: object - title: Tracing Configuration - description: | - Granular configuration for tracing. - properties: - workflow_name: - type: string - description: | - The name of the workflow to attach to this trace. This is used to - name the trace in the traces dashboard. - group_id: - type: string - description: | - The group id to attach to this trace to enable filtering and - grouping in the traces dashboard. - metadata: - type: object - description: | - The arbitrary metadata to attach to this trace to enable - filtering in the traces dashboard. - - type: 'null' - tools: - type: array - description: Tools (functions) available to the model. - items: - $ref: '#/components/schemas/RealtimeFunctionTool' - tool_choice: - type: string - default: auto - description: | - How the model chooses tools. Options are `auto`, `none`, `required`, or - specify a function. - temperature: - type: number - default: 0.8 - description: > - 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. - max_response_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - expires_at: - type: integer - description: Expiration timestamp for the session, in seconds since epoch. - prompt: - anyOf: - - $ref: '#/components/schemas/Prompt' - - type: 'null' - include: - anyOf: - - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - Additional fields to include in server outputs. - - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. - - type: 'null' - RealtimeSessionCreateRequest: - type: object - description: | - A new Realtime session configuration, with an ephemeral key. Default TTL - for keys is one minute. - properties: - client_secret: - type: object - description: Ephemeral key returned by the API. - properties: - value: - type: string - description: | - Ephemeral key usable in client environments to authenticate connections - to the Realtime API. Use this in client-side environments rather than - a standard API token, which should only be used server-side. - expires_at: - type: integer - description: | - Timestamp for when the token expires. Currently, all tokens expire - after one minute. - required: - - value - - expires_at - modalities: - description: | - The set of modalities the model can respond with. To disable audio, - set this to ["text"]. - items: - type: string - enum: - - text - - audio - instructions: - type: string - description: > - 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. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - description: | - 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`, and `verse`. - input_audio_format: - type: string - description: | - The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. - output_audio_format: - type: string - description: | - The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. - input_audio_transcription: - type: object - description: | - 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 and should be treated as rough guidance - rather than the representation understood by the model. - properties: - model: - type: string - description: | - The model to use for transcription. - speed: - type: number - default: 1 - maximum: 1.5 - minimum: 0.25 - description: | - 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. - tracing: - title: Tracing Configuration - description: | - 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. - anyOf: - - type: string - default: auto - description: | - Default tracing mode for the session. - enum: - - auto - x-stainless-const: true - - type: object - title: Tracing Configuration - description: | - Granular configuration for tracing. - properties: - workflow_name: - type: string - description: | - The name of the workflow to attach to this trace. This is used to - name the trace in the traces dashboard. - group_id: - type: string - description: | - The group id to attach to this trace to enable filtering and - grouping in the traces dashboard. - metadata: - type: object - description: | - The arbitrary metadata to attach to this trace to enable - filtering in the traces dashboard. - turn_detection: - type: object - description: | - 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. - properties: - type: - type: string - description: | - Type of turn detection, only `server_vad` is currently supported. - threshold: - type: number - description: | - 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. - prefix_padding_ms: - type: integer - description: | - Amount of audio to include before the VAD detected speech (in - milliseconds). Defaults to 300ms. - silence_duration_ms: - type: integer - description: | - 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. - tools: - type: array - description: Tools (functions) available to the model. - items: - type: object - properties: - type: - type: string - enum: - - function - description: The type of the tool, i.e. `function`. - x-stainless-const: true - name: - type: string - description: The name of the function. - description: - type: string - description: | - 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). - parameters: - type: object - description: Parameters of the function in JSON Schema. - tool_choice: - type: string - description: | - How the model chooses tools. Options are `auto`, `none`, `required`, or - specify a function. - temperature: - type: number - description: | - Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. - max_response_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - truncation: - $ref: '#/components/schemas/RealtimeTruncation' - prompt: - $ref: '#/components/schemas/Prompt' - required: - - client_secret - x-oaiMeta: - name: The session object - group: realtime - example: | - { - "id": "sess_001", - "object": "realtime.session", - "model": "gpt-realtime-2025-08-25", - "modalities": ["audio", "text"], - "instructions": "You are a friendly assistant.", - "voice": "alloy", - "input_audio_format": "pcm16", - "output_audio_format": "pcm16", - "input_audio_transcription": { - "model": "whisper-1" - }, - "turn_detection": null, - "tools": [], - "tool_choice": "none", - "temperature": 0.7, - "speed": 1.1, - "tracing": "auto", - "max_response_output_tokens": 200, - "truncation": "auto", - "prompt": null, - "client_secret": { - "value": "ek_abc123", - "expires_at": 1234567890 - } - } - RealtimeSessionCreateRequestGA: - type: object - title: Realtime session configuration - description: Realtime session object configuration. - properties: - type: - type: string - description: | - The type of session to create. Always `realtime` for the Realtime API. - enum: - - realtime - x-stainless-const: true - output_modalities: - type: array - description: > - The set of modalities the model can respond with. It defaults to `["audio"]`, indicating - - that the model will respond with audio plus a transcript. `["text"]` can be used to make - - the model respond with text only. It is not possible to request both `text` and `audio` at the - same time. - default: - - audio - items: - type: string - enum: - - text - - audio - model: - anyOf: - - type: string - - type: string - enum: - - gpt-realtime - - gpt-realtime-2025-08-28 - - gpt-4o-realtime-preview - - gpt-4o-realtime-preview-2024-10-01 - - gpt-4o-realtime-preview-2024-12-17 - - gpt-4o-realtime-preview-2025-06-03 - - gpt-4o-mini-realtime-preview - - gpt-4o-mini-realtime-preview-2024-12-17 - - gpt-realtime-mini - - gpt-realtime-mini-2025-10-06 - - gpt-audio-mini - - gpt-audio-mini-2025-10-06 - x-stainless-nominal: false - description: | - The Realtime model used for this session. - instructions: - type: string - description: > - 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. - audio: - type: object - description: | - Configuration for input and output audio. - properties: - input: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - description: The format of the input audio. - transcription: - description: > - 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. - $ref: '#/components/schemas/AudioTranscription' - noise_reduction: - type: object - description: > - 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. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - turn_detection: - $ref: '#/components/schemas/RealtimeTurnDetection' - output: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - description: The format of the output audio. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - default: alloy - description: | - 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`. We recommend `marin` and `cedar` for - best quality. - speed: - type: number - default: 1 - maximum: 1.5 - minimum: 0.25 - description: > - The speed of the model's spoken response as a multiple of the original speed. - - 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. - - - This parameter is a post-processing adjustment to the audio after it is generated, it's - - also possible to prompt the model to speak faster or slower. - include: - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - Additional fields to include in server outputs. - - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. - tracing: - title: Tracing Configuration - description: > - Realtime API can write session traces to the [Traces Dashboard](/logs?api=traces). 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. - nullable: true - anyOf: - - type: string - title: auto - default: auto - description: | - Enables tracing and sets default values for tracing configuration options. Always `auto`. - enum: - - auto - x-stainless-const: true - - type: object - title: Tracing Configuration - description: | - Granular configuration for tracing. - properties: - workflow_name: - type: string - description: | - The name of the workflow to attach to this trace. This is used to - name the trace in the Traces Dashboard. - group_id: - type: string - description: | - The group id to attach to this trace to enable filtering and - grouping in the Traces Dashboard. - metadata: - type: object - description: | - The arbitrary metadata to attach to this trace to enable - filtering in the Traces Dashboard. - tools: - type: array - description: Tools available to the model. - items: - anyOf: - - $ref: '#/components/schemas/RealtimeFunctionTool' - - $ref: '#/components/schemas/MCPTool' - discriminator: - propertyName: type - tool_choice: - description: | - How the model chooses tools. Provide one of the string modes or force a specific - function/MCP tool. - default: auto - anyOf: - - $ref: '#/components/schemas/ToolChoiceOptions' - - $ref: '#/components/schemas/ToolChoiceFunction' - - $ref: '#/components/schemas/ToolChoiceMCP' - max_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - truncation: - $ref: '#/components/schemas/RealtimeTruncation' - prompt: - $ref: '#/components/schemas/Prompt' - required: - - type - RealtimeSessionCreateResponse: - type: object - title: Realtime session configuration object - description: | - A Realtime session configuration object. - properties: - id: - type: string - description: | - Unique identifier for the session that looks like `sess_1234567890abcdef`. - object: - type: string - description: The object type. Always `realtime.session`. - expires_at: - type: integer - description: Expiration timestamp for the session, in seconds since epoch. - include: - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - Additional fields to include in server outputs. - - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. - model: - type: string - description: The Realtime model used for this session. - output_modalities: - description: | - The set of modalities the model can respond with. To disable audio, - set this to ["text"]. - items: - type: string - enum: - - text - - audio - instructions: - type: string - description: | - 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. - audio: - type: object - description: | - Configuration for input and output audio for the session. - properties: - input: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - transcription: - description: | - Configuration for input audio transcription. - $ref: '#/components/schemas/AudioTranscription' - noise_reduction: - type: object - description: | - Configuration for input audio noise reduction. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - turn_detection: - type: object - description: | - Configuration for turn detection. - properties: - type: - type: string - description: | - Type of turn detection, only `server_vad` is currently supported. - threshold: - type: number - prefix_padding_ms: - type: integer - silence_duration_ms: - type: integer - output: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - voice: - $ref: '#/components/schemas/VoiceIdsShared' - speed: - type: number - tracing: - title: Tracing Configuration - description: | - 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. - anyOf: - - type: string - default: auto - description: | - Default tracing mode for the session. - enum: - - auto - x-stainless-const: true - - type: object - title: Tracing Configuration - description: | - Granular configuration for tracing. - properties: - workflow_name: - type: string - description: | - The name of the workflow to attach to this trace. This is used to - name the trace in the traces dashboard. - group_id: - type: string - description: | - The group id to attach to this trace to enable filtering and - grouping in the traces dashboard. - metadata: - type: object - description: | - The arbitrary metadata to attach to this trace to enable - filtering in the traces dashboard. - turn_detection: - type: object - description: | - 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. - properties: - type: - type: string - description: | - Type of turn detection, only `server_vad` is currently supported. - threshold: - type: number - description: | - 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. - prefix_padding_ms: - type: integer - description: | - Amount of audio to include before the VAD detected speech (in - milliseconds). Defaults to 300ms. - silence_duration_ms: - type: integer - description: | - 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. - tools: - type: array - description: Tools (functions) available to the model. - items: - $ref: '#/components/schemas/RealtimeFunctionTool' - tool_choice: - type: string - description: | - How the model chooses tools. Options are `auto`, `none`, `required`, or - specify a function. - max_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - x-oaiMeta: - name: The session object - group: realtime - example: | - { - "id": "sess_001", - "object": "realtime.session", - "expires_at": 1742188264, - "model": "gpt-realtime", - "output_modalities": ["audio"], - "instructions": "You are a friendly assistant.", - "tools": [], - "tool_choice": "none", - "max_output_tokens": "inf", - "tracing": "auto", - "truncation": "auto", - "prompt": null, - "audio": { - "input": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "transcription": { "model": "whisper-1" }, - "noise_reduction": null, - "turn_detection": null - }, - "output": { - "format": { - "type": "audio/pcm", - "rate": 24000 - }, - "voice": "alloy", - "speed": 1.0 - } - } - } - RealtimeSessionCreateResponseGA: - type: object - description: | - A new Realtime session configuration, with an ephemeral key. Default TTL - for keys is one minute. - properties: - client_secret: - type: object - description: Ephemeral key returned by the API. - properties: - value: - type: string - description: > - Ephemeral key usable in client environments to authenticate connections to the Realtime API. - Use this in client-side environments rather than a standard API token, which should only be - used server-side. - expires_at: - type: integer - description: | - Timestamp for when the token expires. Currently, all tokens expire - after one minute. - required: - - value - - expires_at - type: - type: string - description: | - The type of session to create. Always `realtime` for the Realtime API. - enum: - - realtime - x-stainless-const: true - output_modalities: - type: array - description: > - The set of modalities the model can respond with. It defaults to `["audio"]`, indicating - - that the model will respond with audio plus a transcript. `["text"]` can be used to make - - the model respond with text only. It is not possible to request both `text` and `audio` at the - same time. - default: - - audio - items: - type: string - enum: - - text - - audio - model: - anyOf: - - type: string - - type: string - enum: - - gpt-realtime - - gpt-realtime-2025-08-28 - - gpt-4o-realtime-preview - - gpt-4o-realtime-preview-2024-10-01 - - gpt-4o-realtime-preview-2024-12-17 - - gpt-4o-realtime-preview-2025-06-03 - - gpt-4o-mini-realtime-preview - - gpt-4o-mini-realtime-preview-2024-12-17 - - gpt-realtime-mini - - gpt-realtime-mini-2025-10-06 - - gpt-audio-mini - - gpt-audio-mini-2025-10-06 - description: | - The Realtime model used for this session. - instructions: - type: string - description: > - 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. - audio: - type: object - description: | - Configuration for input and output audio. - properties: - input: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - description: The format of the input audio. - transcription: - description: > - 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. - $ref: '#/components/schemas/AudioTranscription' - noise_reduction: - type: object - description: > - 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. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - turn_detection: - $ref: '#/components/schemas/RealtimeTurnDetection' - output: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - description: The format of the output audio. - voice: - $ref: '#/components/schemas/VoiceIdsShared' - default: alloy - description: | - 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`. We recommend `marin` and `cedar` for - best quality. - speed: - type: number - default: 1 - maximum: 1.5 - minimum: 0.25 - description: > - The speed of the model's spoken response as a multiple of the original speed. - - 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. - - - This parameter is a post-processing adjustment to the audio after it is generated, it's - - also possible to prompt the model to speak faster or slower. - include: - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - Additional fields to include in server outputs. - - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. - tracing: - anyOf: - - title: Tracing Configuration - description: > - Realtime API can write session traces to the [Traces Dashboard](/logs?api=traces). 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. - anyOf: - - type: string - title: auto - default: auto - description: | - Enables tracing and sets default values for tracing configuration options. Always `auto`. - enum: - - auto - x-stainless-const: true - - type: object - title: Tracing Configuration - description: | - Granular configuration for tracing. - properties: - workflow_name: - type: string - description: | - The name of the workflow to attach to this trace. This is used to - name the trace in the Traces Dashboard. - group_id: - type: string - description: | - The group id to attach to this trace to enable filtering and - grouping in the Traces Dashboard. - metadata: - type: object - description: | - The arbitrary metadata to attach to this trace to enable - filtering in the Traces Dashboard. - - type: 'null' - tools: - type: array - description: Tools available to the model. - items: - anyOf: - - $ref: '#/components/schemas/RealtimeFunctionTool' - - $ref: '#/components/schemas/MCPTool' - tool_choice: - description: | - How the model chooses tools. Provide one of the string modes or force a specific - function/MCP tool. - default: auto - anyOf: - - $ref: '#/components/schemas/ToolChoiceOptions' - - $ref: '#/components/schemas/ToolChoiceFunction' - - $ref: '#/components/schemas/ToolChoiceMCP' - max_output_tokens: - description: | - 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`. - anyOf: - - type: integer - - type: string - enum: - - inf - x-stainless-const: true - truncation: - $ref: '#/components/schemas/RealtimeTruncation' - prompt: - $ref: '#/components/schemas/Prompt' - required: - - client_secret - - type - x-oaiMeta: - name: The session object - group: realtime - RealtimeTranscriptionSessionCreateRequest: - type: object - title: Realtime transcription session configuration - description: Realtime transcription session object configuration. - properties: - turn_detection: - type: object - description: > - 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. - properties: - type: - type: string - description: | - Type of turn detection. Only `server_vad` is currently supported for transcription sessions. - enum: - - server_vad - threshold: - type: number - description: | - 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. - prefix_padding_ms: - type: integer - description: | - Amount of audio to include before the VAD detected speech (in - milliseconds). Defaults to 300ms. - silence_duration_ms: - type: integer - description: | - 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. - input_audio_noise_reduction: - type: object - description: > - 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. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - input_audio_format: - type: string - default: pcm16 - enum: - - pcm16 - - g711_ulaw - - g711_alaw - description: | - 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. - input_audio_transcription: - description: > - Configuration for input audio transcription. The client can optionally set the language and prompt - for transcription, these offer additional guidance to the transcription service. - $ref: '#/components/schemas/AudioTranscription' - include: - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - The set of items to include in the transcription. Current available items are: - `item.input_audio_transcription.logprobs` - RealtimeTranscriptionSessionCreateRequestGA: - type: object - title: Realtime transcription session configuration - description: Realtime transcription session object configuration. - properties: - type: - type: string - description: | - The type of session to create. Always `transcription` for transcription sessions. - enum: - - transcription - x-stainless-const: true - audio: - type: object - description: | - Configuration for input and output audio. - properties: - input: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - transcription: - description: > - 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. - $ref: '#/components/schemas/AudioTranscription' - noise_reduction: - type: object - description: > - 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. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - turn_detection: - $ref: '#/components/schemas/RealtimeTurnDetection' - include: - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - Additional fields to include in server outputs. - - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. - required: - - type - RealtimeTranscriptionSessionCreateResponse: - type: object - description: | - A new Realtime transcription session configuration. - - When a session is created on the server via REST API, the session object - also contains an ephemeral key. Default TTL for keys is 10 minutes. This - property is not present when a session is updated via the WebSocket API. - properties: - client_secret: - type: object - description: | - Ephemeral key returned by the API. Only present when the session is - created on the server via REST API. - properties: - value: - type: string - description: | - Ephemeral key usable in client environments to authenticate connections - to the Realtime API. Use this in client-side environments rather than - a standard API token, which should only be used server-side. - expires_at: - type: integer - description: | - Timestamp for when the token expires. Currently, all tokens expire - after one minute. - required: - - value - - expires_at - modalities: - description: | - The set of modalities the model can respond with. To disable audio, - set this to ["text"]. - items: - type: string - enum: - - text - - audio - input_audio_format: - type: string - description: | - The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. - input_audio_transcription: - description: | - Configuration of the transcription model. - $ref: '#/components/schemas/AudioTranscription' - turn_detection: - type: object - description: | - 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. - properties: - type: - type: string - description: | - Type of turn detection, only `server_vad` is currently supported. - threshold: - type: number - description: | - 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. - prefix_padding_ms: - type: integer - description: | - Amount of audio to include before the VAD detected speech (in - milliseconds). Defaults to 300ms. - silence_duration_ms: - type: integer - description: | - 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. - required: - - client_secret - x-oaiMeta: - name: The transcription session object - group: realtime - example: | - { - "id": "sess_BBwZc7cFV3XizEyKGDCGL", - "object": "realtime.transcription_session", - "expires_at": 1742188264, - "modalities": ["audio", "text"], - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200 - }, - "input_audio_format": "pcm16", - "input_audio_transcription": { - "model": "gpt-4o-transcribe", - "language": null, - "prompt": "" - }, - "client_secret": null - } - RealtimeTranscriptionSessionCreateResponseGA: - type: object - title: Realtime transcription session configuration object - description: | - A Realtime transcription session configuration object. - properties: - type: - type: string - description: | - The type of session. Always `transcription` for transcription sessions. - enum: - - transcription - x-stainless-const: true - id: - type: string - description: | - Unique identifier for the session that looks like `sess_1234567890abcdef`. - object: - type: string - description: The object type. Always `realtime.transcription_session`. - expires_at: - type: integer - description: Expiration timestamp for the session, in seconds since epoch. - include: - type: array - items: - type: string - enum: - - item.input_audio_transcription.logprobs - description: | - Additional fields to include in server outputs. - - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. - audio: - type: object - description: | - Configuration for input audio for the session. - properties: - input: - type: object - properties: - format: - $ref: '#/components/schemas/RealtimeAudioFormats' - transcription: - description: | - Configuration of the transcription model. - $ref: '#/components/schemas/AudioTranscription' - noise_reduction: - type: object - description: | - Configuration for input audio noise reduction. - properties: - type: - $ref: '#/components/schemas/NoiseReductionType' - turn_detection: - type: object - description: | - 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. - properties: - type: - type: string - description: | - Type of turn detection, only `server_vad` is currently supported. - threshold: - type: number - description: | - 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. - prefix_padding_ms: - type: integer - description: | - Amount of audio to include before the VAD detected speech (in - milliseconds). Defaults to 300ms. - silence_duration_ms: - type: integer - description: | - 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. - required: - - type - - id - - object - x-oaiMeta: - name: The transcription session object - group: realtime - example: | - { - "id": "sess_BBwZc7cFV3XizEyKGDCGL", - "type": "transcription", - "object": "realtime.transcription_session", - "expires_at": 1742188264, - "include": ["item.input_audio_transcription.logprobs"], - "audio": { - "input": { - "format": "pcm16", - "transcription": { - "model": "gpt-4o-transcribe", - "language": null, - "prompt": "" - }, - "noise_reduction": null, - "turn_detection": { - "type": "server_vad", - "threshold": 0.5, - "prefix_padding_ms": 300, - "silence_duration_ms": 200 - } - } - } - } - RealtimeTruncation: - title: Realtime Truncation Controls - description: > - When the number of tokens in a conversation exceeds the model's input token limit, the conversation be - truncated, meaning messages (starting from the oldest) will not be included in the model's context. A - 32k context model with 4,096 max output tokens can only include 28,224 tokens in the context before - truncation occurs. - - Clients can configure truncation behavior to truncate with a lower max token limit, which is an - effective way to control token usage and cost. - - Truncation will reduce the number of cached tokens on the next turn (busting the cache), since - messages are dropped from the beginning of the context. However, clients can also configure truncation - to retain messages up to a fraction of the maximum context size, which will reduce the need for future - truncations and thus improve the cache rate. - - Truncation can be disabled entirely, which means the server will never truncate but would instead - return an error if the conversation exceeds the model's input token limit. - anyOf: - - type: string - description: >- - The truncation strategy to use for the session. `auto` is the default truncation strategy. - `disabled` will disable truncation and emit errors when the conversation exceeds the input token - limit. - enum: - - auto - - disabled - title: RealtimeTruncationStrategy - - type: object - title: Retention ratio truncation - description: >- - Retain a fraction of the conversation tokens when the conversation exceeds the input token limit. - This allows you to amortize truncations across multiple turns, which can help improve cached token - usage. - properties: - type: - type: string - enum: - - retention_ratio - description: Use retention ratio truncation. - x-stainless-const: true - retention_ratio: - type: number - description: > - Fraction of post-instruction conversation tokens to retain (`0.0` - `1.0`) when the - conversation exceeds the input token limit. Setting this to `0.8` means that messages will be - dropped until 80% of the maximum allowed tokens are used. This helps reduce the frequency of - truncations and improve cache rates. - minimum: 0 - maximum: 1 - token_limits: - type: object - description: >- - Optional custom token limits for this truncation strategy. If not provided, the model's - default token limits will be used. - properties: - post_instructions: - type: integer - description: >- - Maximum tokens allowed in the conversation after instructions (which including tool - definitions). For example, setting this to 5,000 would mean that truncation would occur - when the conversation exceeds 5,000 tokens after instructions. This cannot be higher than - the model's context window size minus the maximum output tokens. - minimum: 0 - required: - - type - - retention_ratio - RealtimeTurnDetection: - anyOf: - - title: Realtime Turn Detection - description: > - 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. - discriminator: - propertyName: type - anyOf: - - type: object - title: Server VAD - description: >- - Server-side voice activity detection (VAD) which flips on when user speech is detected and off - after a period of silence. - required: - - type - properties: - type: - type: string - default: server_vad - const: server_vad - description: | - Type of turn detection, `server_vad` to turn on simple Server VAD. - threshold: - type: number - description: > - 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. - prefix_padding_ms: - type: integer - description: > - Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech - (in - - milliseconds). Defaults to 300ms. - silence_duration_ms: - type: integer - description: > - 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. - create_response: - type: boolean - default: true - description: | - Whether or not to automatically generate a response when a VAD stop event occurs. - interrupt_response: - type: boolean - default: true - description: | - 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. - idle_timeout_ms: - anyOf: - - type: integer - minimum: 5000 - maximum: 30000 - description: > - Optional timeout after which a model response will be triggered automatically. This is - - useful for situations in which a long pause from the user is unexpected, such as a - phone - - call. The model will effectively prompt the user to continue the conversation based - - on the current context. - - - The timeout value will be applied after the last model response's audio has finished - playing, - - i.e. it's set to the `response.done` time plus audio playback duration. - - - An `input_audio_buffer.timeout_triggered` event (plus events - - associated with the Response) will be emitted when the timeout is reached. - - Idle timeout is currently only supported for `server_vad` mode. - - type: 'null' - - type: object - title: Semantic VAD - description: >- - Server-side semantic turn detection which uses a model to determine when the user has finished - speaking. - required: - - type - properties: - type: - type: string - const: semantic_vad - description: | - Type of turn detection, `semantic_vad` to turn on Semantic VAD. - eagerness: - type: string - default: auto - enum: - - low - - medium - - high - - auto - description: > - 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`. `low`, `medium`, and `high` have max timeouts of - 8s, 4s, and 2s respectively. - create_response: - type: boolean - default: true - description: | - Whether or not to automatically generate a response when a VAD stop event occurs. - interrupt_response: - type: boolean - default: true - description: | - 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. - - type: 'null' - Reasoning: - type: object - description: | - **gpt-5 and o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - title: Reasoning - properties: - effort: - $ref: '#/components/schemas/ReasoningEffort' - summary: - anyOf: - - type: string - description: | - 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`. - - `concise` is only supported for `computer-use-preview` models. - enum: - - auto - - concise - - detailed - - type: 'null' - generate_summary: - anyOf: - - type: string - deprecated: true - description: | - **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`. - enum: - - auto - - concise - - detailed - - type: 'null' - ReasoningEffort: - anyOf: - - type: string - enum: - - none - - minimal - - low - - medium - - high - default: medium - description: > - Constrains effort on reasoning for - - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing - - reasoning effort can result in faster responses and fewer tokens used - - on reasoning in a response. - - - - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values - for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning - values in gpt-5.1. - - - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`. - - - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort. - - type: 'null' - ReasoningItem: - type: object - description: | - A description of the chain of thought used by a reasoning model while generating - a response. Be sure to include these items in your `input` to the Responses API - for subsequent turns of a conversation if you are manually - [managing context](https://platform.openai.com/docs/guides/conversation-state). - title: Reasoning - properties: - type: - type: string - description: | - The type of the object. Always `reasoning`. - enum: - - reasoning - x-stainless-const: true - id: - type: string - description: | - The unique identifier of the reasoning content. - encrypted_content: - anyOf: - - type: string - description: | - The encrypted content of the reasoning item - populated when a response is - generated with `reasoning.encrypted_content` in the `include` parameter. - - type: 'null' - summary: - type: array - description: | - Reasoning summary content. - items: - $ref: '#/components/schemas/Summary' - content: - type: array - description: | - Reasoning text content. - items: - $ref: '#/components/schemas/ReasoningTextContent' - status: - type: string - description: | - The status of the item. One of `in_progress`, `completed`, or - `incomplete`. Populated when items are returned via API. - enum: - - in_progress - - completed - - incomplete - required: - - id - - summary - - type - Response: - title: The response object - allOf: - - $ref: '#/components/schemas/ModelResponseProperties' - - $ref: '#/components/schemas/ResponseProperties' - - type: object - properties: - id: - type: string - description: | - Unique identifier for this Response. - object: - type: string - description: | - The object type of this resource - always set to `response`. - enum: - - response - x-stainless-const: true - status: - type: string - description: | - The status of the response generation. One of `completed`, `failed`, - `in_progress`, `cancelled`, `queued`, or `incomplete`. - enum: - - completed - - failed - - in_progress - - cancelled - - queued - - incomplete - created_at: - type: number - description: | - Unix timestamp (in seconds) of when this Response was created. - error: - $ref: '#/components/schemas/ResponseError' - incomplete_details: - anyOf: - - type: object - description: | - Details about why the response is incomplete. - properties: - reason: - type: string - description: The reason why the response is incomplete. - enum: - - max_output_tokens - - content_filter - - type: 'null' - output: - type: array - description: | - An array of content items generated by the model. - - - The length and order of items in the `output` array is dependent - on the model's response. - - Rather than accessing the first item in the `output` array and - assuming it's an `assistant` message with the content generated by - the model, you might consider using the `output_text` property where - supported in SDKs. - items: - $ref: '#/components/schemas/OutputItem' - instructions: - anyOf: - - description: | - A system (or developer) message inserted into the model's context. - - When using along with `previous_response_id`, the instructions from a previous - response will not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - anyOf: - - type: string - description: | - A text input to the model, equivalent to a text input with the - `developer` role. - - type: array - title: Input item list - description: | - A list of one or many input items to the model, containing - different content types. - items: - $ref: '#/components/schemas/InputItem' - - type: 'null' - output_text: - anyOf: - - type: string - description: | - SDK-only convenience property that contains the aggregated text output - from all `output_text` items in the `output` array, if any are present. - Supported in the Python and JavaScript SDKs. - x-oaiSupportedSDKs: - - python - - javascript - - type: 'null' - x-stainless-skip: true - usage: - $ref: '#/components/schemas/ResponseUsage' - parallel_tool_calls: - type: boolean - description: | - Whether to allow the model to run tool calls in parallel. - default: true - conversation: - anyOf: - - $ref: '#/components/schemas/Conversation-2' - - type: 'null' - required: - - id - - object - - created_at - - error - - incomplete_details - - instructions - - model - - tools - - output - - parallel_tool_calls - - metadata - - tool_choice - - temperature - - top_p - ResponseAudioDeltaEvent: - type: object - description: Emitted when there is a partial audio response. - properties: - type: - type: string - description: | - The type of the event. Always `response.audio.delta`. - enum: - - response.audio.delta - x-stainless-const: true - sequence_number: - type: integer - description: | - A sequence number for this chunk of the stream response. - delta: - type: string - description: | - A chunk of Base64 encoded response audio bytes. - required: - - type - - delta - - sequence_number - x-oaiMeta: - name: response.audio.delta - group: responses - example: | - { - "type": "response.audio.delta", - "response_id": "resp_123", - "delta": "base64encoded...", - "sequence_number": 1 - } - ResponseAudioDoneEvent: - type: object - description: Emitted when the audio response is complete. - properties: - type: - type: string - description: | - The type of the event. Always `response.audio.done`. - enum: - - response.audio.done - x-stainless-const: true - sequence_number: - type: integer - description: | - The sequence number of the delta. - required: - - type - - sequence_number - - response_id - x-oaiMeta: - name: response.audio.done - group: responses - example: | - { - "type": "response.audio.done", - "response_id": "resp-123", - "sequence_number": 1 - } - ResponseAudioTranscriptDeltaEvent: - type: object - description: Emitted when there is a partial transcript of audio. - properties: - type: - type: string - description: | - The type of the event. Always `response.audio.transcript.delta`. - enum: - - response.audio.transcript.delta - x-stainless-const: true - delta: - type: string - description: | - The partial transcript of the audio response. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - response_id - - delta - - sequence_number - x-oaiMeta: - name: response.audio.transcript.delta - group: responses - example: | - { - "type": "response.audio.transcript.delta", - "response_id": "resp_123", - "delta": " ... partial transcript ... ", - "sequence_number": 1 - } - ResponseAudioTranscriptDoneEvent: - type: object - description: Emitted when the full audio transcript is completed. - properties: - type: - type: string - description: | - The type of the event. Always `response.audio.transcript.done`. - enum: - - response.audio.transcript.done - x-stainless-const: true - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - response_id - - sequence_number - x-oaiMeta: - name: response.audio.transcript.done - group: responses - example: | - { - "type": "response.audio.transcript.done", - "response_id": "resp_123", - "sequence_number": 1 - } - ResponseCodeInterpreterCallCodeDeltaEvent: - type: object - description: Emitted when a partial code snippet is streamed by the code interpreter. - properties: - type: - type: string - description: The type of the event. Always `response.code_interpreter_call_code.delta`. - enum: - - response.code_interpreter_call_code.delta - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response for which the code is being streamed. - item_id: - type: string - description: The unique identifier of the code interpreter tool call item. - delta: - type: string - description: The partial code snippet being streamed by the code interpreter. - sequence_number: - type: integer - description: The sequence number of this event, used to order streaming events. - required: - - type - - output_index - - item_id - - delta - - sequence_number - x-oaiMeta: - name: response.code_interpreter_call_code.delta - group: responses - example: | - { - "type": "response.code_interpreter_call_code.delta", - "output_index": 0, - "item_id": "ci_12345", - "delta": "print('Hello, world')", - "sequence_number": 1 - } - ResponseCodeInterpreterCallCodeDoneEvent: - type: object - description: Emitted when the code snippet is finalized by the code interpreter. - properties: - type: - type: string - description: The type of the event. Always `response.code_interpreter_call_code.done`. - enum: - - response.code_interpreter_call_code.done - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response for which the code is finalized. - item_id: - type: string - description: The unique identifier of the code interpreter tool call item. - code: - type: string - description: The final code snippet output by the code interpreter. - sequence_number: - type: integer - description: The sequence number of this event, used to order streaming events. - required: - - type - - output_index - - item_id - - code - - sequence_number - x-oaiMeta: - name: response.code_interpreter_call_code.done - group: responses - example: | - { - "type": "response.code_interpreter_call_code.done", - "output_index": 3, - "item_id": "ci_12345", - "code": "print('done')", - "sequence_number": 1 - } - ResponseCodeInterpreterCallCompletedEvent: - type: object - description: Emitted when the code interpreter call is completed. - properties: - type: - type: string - description: The type of the event. Always `response.code_interpreter_call.completed`. - enum: - - response.code_interpreter_call.completed - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response for which the code interpreter call is completed. - item_id: - type: string - description: The unique identifier of the code interpreter tool call item. - sequence_number: - type: integer - description: The sequence number of this event, used to order streaming events. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.code_interpreter_call.completed - group: responses - example: | - { - "type": "response.code_interpreter_call.completed", - "output_index": 5, - "item_id": "ci_12345", - "sequence_number": 1 - } - ResponseCodeInterpreterCallInProgressEvent: - type: object - description: Emitted when a code interpreter call is in progress. - properties: - type: - type: string - description: The type of the event. Always `response.code_interpreter_call.in_progress`. - enum: - - response.code_interpreter_call.in_progress - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response for which the code interpreter call is in progress. - item_id: - type: string - description: The unique identifier of the code interpreter tool call item. - sequence_number: - type: integer - description: The sequence number of this event, used to order streaming events. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.code_interpreter_call.in_progress - group: responses - example: | - { - "type": "response.code_interpreter_call.in_progress", - "output_index": 0, - "item_id": "ci_12345", - "sequence_number": 1 - } - ResponseCodeInterpreterCallInterpretingEvent: - type: object - description: Emitted when the code interpreter is actively interpreting the code snippet. - properties: - type: - type: string - description: The type of the event. Always `response.code_interpreter_call.interpreting`. - enum: - - response.code_interpreter_call.interpreting - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response for which the code interpreter is interpreting code. - item_id: - type: string - description: The unique identifier of the code interpreter tool call item. - sequence_number: - type: integer - description: The sequence number of this event, used to order streaming events. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.code_interpreter_call.interpreting - group: responses - example: | - { - "type": "response.code_interpreter_call.interpreting", - "output_index": 4, - "item_id": "ci_12345", - "sequence_number": 1 - } - ResponseCompletedEvent: - type: object - description: Emitted when the model response is complete. - properties: - type: - type: string - description: | - The type of the event. Always `response.completed`. - enum: - - response.completed - x-stainless-const: true - response: - $ref: '#/components/schemas/Response' - description: | - Properties of the completed response. - sequence_number: - type: integer - description: The sequence number for this event. - required: - - type - - response - - sequence_number - x-oaiMeta: - name: response.completed - group: responses - example: | - { - "type": "response.completed", - "response": { - "id": "resp_123", - "object": "response", - "created_at": 1740855869, - "status": "completed", - "error": null, - "incomplete_details": null, - "input": [], - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-mini-2024-07-18", - "output": [ - { - "id": "msg_123", - "type": "message", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", - "annotations": [] - } - ] - } - ], - "previous_response_id": null, - "reasoning_effort": null, - "store": false, - "temperature": 1, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1, - "truncation": "disabled", - "usage": { - "input_tokens": 0, - "output_tokens": 0, - "output_tokens_details": { - "reasoning_tokens": 0 - }, - "total_tokens": 0 - }, - "user": null, - "metadata": {} - }, - "sequence_number": 1 - } - ResponseContentPartAddedEvent: - type: object - description: Emitted when a new content part is added. - properties: - type: - type: string - description: | - The type of the event. Always `response.content_part.added`. - enum: - - response.content_part.added - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the content part was added to. - output_index: - type: integer - description: | - The index of the output item that the content part was added to. - content_index: - type: integer - description: | - The index of the content part that was added. - part: - $ref: '#/components/schemas/OutputContent' - description: | - The content part that was added. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - item_id - - output_index - - content_index - - part - - sequence_number - x-oaiMeta: - name: response.content_part.added - group: responses - example: | - { - "type": "response.content_part.added", - "item_id": "msg_123", - "output_index": 0, - "content_index": 0, - "part": { - "type": "output_text", - "text": "", - "annotations": [] - }, - "sequence_number": 1 - } - ResponseContentPartDoneEvent: - type: object - description: Emitted when a content part is done. - properties: - type: - type: string - description: | - The type of the event. Always `response.content_part.done`. - enum: - - response.content_part.done - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the content part was added to. - output_index: - type: integer - description: | - The index of the output item that the content part was added to. - content_index: - type: integer - description: | - The index of the content part that is done. - sequence_number: - type: integer - description: The sequence number of this event. - part: - $ref: '#/components/schemas/OutputContent' - description: | - The content part that is done. - required: - - type - - item_id - - output_index - - content_index - - part - - sequence_number - x-oaiMeta: - name: response.content_part.done - group: responses - example: | - { - "type": "response.content_part.done", - "item_id": "msg_123", - "output_index": 0, - "content_index": 0, - "sequence_number": 1, - "part": { - "type": "output_text", - "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", - "annotations": [] - } - } - ResponseCreatedEvent: - type: object - description: | - An event that is emitted when a response is created. - properties: - type: - type: string - description: | - The type of the event. Always `response.created`. - enum: - - response.created - x-stainless-const: true - response: - $ref: '#/components/schemas/Response' - description: | - The response that was created. - sequence_number: - type: integer - description: The sequence number for this event. - required: - - type - - response - - sequence_number - x-oaiMeta: - name: response.created - group: responses - example: | - { - "type": "response.created", - "response": { - "id": "resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c", - "object": "response", - "created_at": 1741487325, - "status": "in_progress", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-2024-08-06", - "output": [], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1, - "truncation": "disabled", - "usage": null, - "user": null, - "metadata": {} - }, - "sequence_number": 1 - } - ResponseCustomToolCallInputDeltaEvent: - title: ResponseCustomToolCallInputDelta - type: object - description: | - Event representing a delta (partial update) to the input of a custom tool call. - properties: - type: - type: string - enum: - - response.custom_tool_call_input.delta - description: The event type identifier. - x-stainless-const: true - sequence_number: - type: integer - description: The sequence number of this event. - output_index: - type: integer - description: The index of the output this delta applies to. - item_id: - type: string - description: Unique identifier for the API item associated with this event. - delta: - type: string - description: The incremental input data (delta) for the custom tool call. - required: - - type - - output_index - - item_id - - delta - - sequence_number - x-oaiMeta: - name: response.custom_tool_call_input.delta - group: responses - example: | - { - "type": "response.custom_tool_call_input.delta", - "output_index": 0, - "item_id": "ctc_1234567890abcdef", - "delta": "partial input text" - } - ResponseCustomToolCallInputDoneEvent: - title: ResponseCustomToolCallInputDone - type: object - description: | - Event indicating that input for a custom tool call is complete. - properties: - type: - type: string - enum: - - response.custom_tool_call_input.done - description: The event type identifier. - x-stainless-const: true - sequence_number: - type: integer - description: The sequence number of this event. - output_index: - type: integer - description: The index of the output this event applies to. - item_id: - type: string - description: Unique identifier for the API item associated with this event. - input: - type: string - description: The complete input data for the custom tool call. - required: - - type - - output_index - - item_id - - input - - sequence_number - x-oaiMeta: - name: response.custom_tool_call_input.done - group: responses - example: | - { - "type": "response.custom_tool_call_input.done", - "output_index": 0, - "item_id": "ctc_1234567890abcdef", - "input": "final complete input text" - } - ResponseError: - anyOf: - - type: object - description: | - An error object returned when the model fails to generate a Response. - properties: - code: - $ref: '#/components/schemas/ResponseErrorCode' - message: - type: string - description: | - A human-readable description of the error. - required: - - code - - message - - type: 'null' - ResponseErrorCode: - type: string - description: | - The error code for the response. - enum: - - server_error - - rate_limit_exceeded - - invalid_prompt - - vector_store_timeout - - invalid_image - - invalid_image_format - - invalid_base64_image - - invalid_image_url - - image_too_large - - image_too_small - - image_parse_error - - image_content_policy_violation - - invalid_image_mode - - image_file_too_large - - unsupported_image_media_type - - empty_image_file - - failed_to_download_image - - image_file_not_found - ResponseErrorEvent: - type: object - description: Emitted when an error occurs. - properties: - type: - type: string - description: | - The type of the event. Always `error`. - enum: - - error - x-stainless-const: true - code: - anyOf: - - type: string - description: | - The error code. - - type: 'null' - message: - type: string - description: | - The error message. - param: - anyOf: - - type: string - description: | - The error parameter. - - type: 'null' - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - code - - message - - param - - sequence_number - x-oaiMeta: - name: error - group: responses - example: | - { - "type": "error", - "code": "ERR_SOMETHING", - "message": "Something went wrong", - "param": null, - "sequence_number": 1 - } - ResponseFailedEvent: - type: object - description: | - An event that is emitted when a response fails. - properties: - type: - type: string - description: | - The type of the event. Always `response.failed`. - enum: - - response.failed - x-stainless-const: true - sequence_number: - type: integer - description: The sequence number of this event. - response: - $ref: '#/components/schemas/Response' - description: | - The response that failed. - required: - - type - - response - - sequence_number - x-oaiMeta: - name: response.failed - group: responses - example: | - { - "type": "response.failed", - "response": { - "id": "resp_123", - "object": "response", - "created_at": 1740855869, - "status": "failed", - "error": { - "code": "server_error", - "message": "The model failed to generate a response." - }, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-mini-2024-07-18", - "output": [], - "previous_response_id": null, - "reasoning_effort": null, - "store": false, - "temperature": 1, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1, - "truncation": "disabled", - "usage": null, - "user": null, - "metadata": {} - } - } - ResponseFileSearchCallCompletedEvent: - type: object - description: Emitted when a file search call is completed (results found). - properties: - type: - type: string - description: | - The type of the event. Always `response.file_search_call.completed`. - enum: - - response.file_search_call.completed - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that the file search call is initiated. - item_id: - type: string - description: | - The ID of the output item that the file search call is initiated. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.file_search_call.completed - group: responses - example: | - { - "type": "response.file_search_call.completed", - "output_index": 0, - "item_id": "fs_123", - "sequence_number": 1 - } - ResponseFileSearchCallInProgressEvent: - type: object - description: Emitted when a file search call is initiated. - properties: - type: - type: string - description: | - The type of the event. Always `response.file_search_call.in_progress`. - enum: - - response.file_search_call.in_progress - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that the file search call is initiated. - item_id: - type: string - description: | - The ID of the output item that the file search call is initiated. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.file_search_call.in_progress - group: responses - example: | - { - "type": "response.file_search_call.in_progress", - "output_index": 0, - "item_id": "fs_123", - "sequence_number": 1 - } - ResponseFileSearchCallSearchingEvent: - type: object - description: Emitted when a file search is currently searching. - properties: - type: - type: string - description: | - The type of the event. Always `response.file_search_call.searching`. - enum: - - response.file_search_call.searching - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that the file search call is searching. - item_id: - type: string - description: | - The ID of the output item that the file search call is initiated. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.file_search_call.searching - group: responses - example: | - { - "type": "response.file_search_call.searching", - "output_index": 0, - "item_id": "fs_123", - "sequence_number": 1 - } - ResponseFormatJsonObject: - type: object - title: JSON object - description: | - 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. - properties: - type: - type: string - description: The type of response format being defined. Always `json_object`. - enum: - - json_object - x-stainless-const: true - required: - - type - ResponseFormatJsonSchema: - type: object - title: JSON schema - description: | - JSON Schema response format. Used to generate structured JSON responses. - Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). - properties: - type: - type: string - description: The type of response format being defined. Always `json_schema`. - enum: - - json_schema - x-stainless-const: true - json_schema: - type: object - title: JSON schema - description: | - Structured Outputs configuration options, including a JSON Schema. - properties: - description: - type: string - description: | - A description of what the response format is for, used by the model to - determine how to respond in the format. - name: - type: string - description: | - The name of the response format. Must be a-z, A-Z, 0-9, or contain - underscores and dashes, with a maximum length of 64. - schema: - $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' - strict: - anyOf: - - type: boolean - default: false - description: | - Whether to enable strict schema adherence when generating the output. - If set to true, the model will always follow the exact schema defined - in the `schema` field. Only a subset of JSON Schema is supported when - `strict` is `true`. To learn more, read the [Structured Outputs - guide](https://platform.openai.com/docs/guides/structured-outputs). - - type: 'null' - required: - - name - required: - - type - - json_schema - ResponseFormatJsonSchemaSchema: - type: object - title: JSON schema - description: | - The schema for the response format, described as a JSON Schema object. - Learn how to build JSON schemas [here](https://json-schema.org/). - additionalProperties: true - ResponseFormatText: - type: object - title: Text - description: | - Default response format. Used to generate text responses. - properties: - type: - type: string - description: The type of response format being defined. Always `text`. - enum: - - text - x-stainless-const: true - required: - - type - ResponseFormatTextGrammar: - type: object - title: Text grammar - description: | - A custom grammar for the model to follow when generating text. - Learn more in the [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars). - properties: - type: - type: string - description: The type of response format being defined. Always `grammar`. - enum: - - grammar - x-stainless-const: true - grammar: - type: string - description: The custom grammar for the model to follow. - required: - - type - - grammar - ResponseFormatTextPython: - type: object - title: Python grammar - description: | - Configure the model to generate valid Python code. See the - [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars) for more details. - properties: - type: - type: string - description: The type of response format being defined. Always `python`. - enum: - - python - x-stainless-const: true - required: - - type - ResponseFunctionCallArgumentsDeltaEvent: - type: object - description: Emitted when there is a partial function-call arguments delta. - properties: - type: - type: string - description: | - The type of the event. Always `response.function_call_arguments.delta`. - enum: - - response.function_call_arguments.delta - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the function-call arguments delta is added to. - output_index: - type: integer - description: | - The index of the output item that the function-call arguments delta is added to. - sequence_number: - type: integer - description: The sequence number of this event. - delta: - type: string - description: | - The function-call arguments delta that is added. - required: - - type - - item_id - - output_index - - delta - - sequence_number - x-oaiMeta: - name: response.function_call_arguments.delta - group: responses - example: | - { - "type": "response.function_call_arguments.delta", - "item_id": "item-abc", - "output_index": 0, - "delta": "{ \"arg\":" - "sequence_number": 1 - } - ResponseFunctionCallArgumentsDoneEvent: - type: object - description: Emitted when function-call arguments are finalized. - properties: - type: - type: string - enum: - - response.function_call_arguments.done - x-stainless-const: true - item_id: - type: string - description: The ID of the item. - name: - type: string - description: The name of the function that was called. - output_index: - type: integer - description: The index of the output item. - sequence_number: - type: integer - description: The sequence number of this event. - arguments: - type: string - description: The function-call arguments. - required: - - type - - item_id - - name - - output_index - - arguments - - sequence_number - x-oaiMeta: - name: response.function_call_arguments.done - group: responses - example: | - { - "type": "response.function_call_arguments.done", - "item_id": "item-abc", - "name": "get_weather", - "output_index": 1, - "arguments": "{ \"arg\": 123 }", - "sequence_number": 1 - } - ResponseImageGenCallCompletedEvent: - type: object - title: ResponseImageGenCallCompletedEvent - description: | - Emitted when an image generation tool call has completed and the final image is available. - properties: - type: - type: string - enum: - - response.image_generation_call.completed - description: The type of the event. Always 'response.image_generation_call.completed'. - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response's output array. - sequence_number: - type: integer - description: The sequence number of this event. - item_id: - type: string - description: The unique identifier of the image generation item being processed. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.image_generation_call.completed - group: responses - example: | - { - "type": "response.image_generation_call.completed", - "output_index": 0, - "item_id": "item-123", - "sequence_number": 1 - } - ResponseImageGenCallGeneratingEvent: - type: object - title: ResponseImageGenCallGeneratingEvent - description: | - Emitted when an image generation tool call is actively generating an image (intermediate state). - properties: - type: - type: string - enum: - - response.image_generation_call.generating - description: The type of the event. Always 'response.image_generation_call.generating'. - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response's output array. - item_id: - type: string - description: The unique identifier of the image generation item being processed. - sequence_number: - type: integer - description: The sequence number of the image generation item being processed. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.image_generation_call.generating - group: responses - example: | - { - "type": "response.image_generation_call.generating", - "output_index": 0, - "item_id": "item-123", - "sequence_number": 0 - } - ResponseImageGenCallInProgressEvent: - type: object - title: ResponseImageGenCallInProgressEvent - description: | - Emitted when an image generation tool call is in progress. - properties: - type: - type: string - enum: - - response.image_generation_call.in_progress - description: The type of the event. Always 'response.image_generation_call.in_progress'. - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response's output array. - item_id: - type: string - description: The unique identifier of the image generation item being processed. - sequence_number: - type: integer - description: The sequence number of the image generation item being processed. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.image_generation_call.in_progress - group: responses - example: | - { - "type": "response.image_generation_call.in_progress", - "output_index": 0, - "item_id": "item-123", - "sequence_number": 0 - } - ResponseImageGenCallPartialImageEvent: - type: object - title: ResponseImageGenCallPartialImageEvent - description: | - Emitted when a partial image is available during image generation streaming. - properties: - type: - type: string - enum: - - response.image_generation_call.partial_image - description: The type of the event. Always 'response.image_generation_call.partial_image'. - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response's output array. - item_id: - type: string - description: The unique identifier of the image generation item being processed. - sequence_number: - type: integer - description: The sequence number of the image generation item being processed. - partial_image_index: - type: integer - description: 0-based index for the partial image (backend is 1-based, but this is 0-based for the user). - partial_image_b64: - type: string - description: Base64-encoded partial image data, suitable for rendering as an image. - required: - - type - - output_index - - item_id - - sequence_number - - partial_image_index - - partial_image_b64 - x-oaiMeta: - name: response.image_generation_call.partial_image - group: responses - example: | - { - "type": "response.image_generation_call.partial_image", - "output_index": 0, - "item_id": "item-123", - "sequence_number": 0, - "partial_image_index": 0, - "partial_image_b64": "..." - } - ResponseInProgressEvent: - type: object - description: Emitted when the response is in progress. - properties: - type: - type: string - description: | - The type of the event. Always `response.in_progress`. - enum: - - response.in_progress - x-stainless-const: true - response: - $ref: '#/components/schemas/Response' - description: | - The response that is in progress. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - response - - sequence_number - x-oaiMeta: - name: response.in_progress - group: responses - example: | - { - "type": "response.in_progress", - "response": { - "id": "resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c", - "object": "response", - "created_at": 1741487325, - "status": "in_progress", - "error": null, - "incomplete_details": null, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-2024-08-06", - "output": [], - "parallel_tool_calls": true, - "previous_response_id": null, - "reasoning": { - "effort": null, - "summary": null - }, - "store": true, - "temperature": 1, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1, - "truncation": "disabled", - "usage": null, - "user": null, - "metadata": {} - }, - "sequence_number": 1 - } - ResponseIncompleteEvent: - type: object - description: | - An event that is emitted when a response finishes as incomplete. - properties: - type: - type: string - description: | - The type of the event. Always `response.incomplete`. - enum: - - response.incomplete - x-stainless-const: true - response: - $ref: '#/components/schemas/Response' - description: | - The response that was incomplete. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - response - - sequence_number - x-oaiMeta: - name: response.incomplete - group: responses - example: | - { - "type": "response.incomplete", - "response": { - "id": "resp_123", - "object": "response", - "created_at": 1740855869, - "status": "incomplete", - "error": null, - "incomplete_details": { - "reason": "max_tokens" - }, - "instructions": null, - "max_output_tokens": null, - "model": "gpt-4o-mini-2024-07-18", - "output": [], - "previous_response_id": null, - "reasoning_effort": null, - "store": false, - "temperature": 1, - "text": { - "format": { - "type": "text" - } - }, - "tool_choice": "auto", - "tools": [], - "top_p": 1, - "truncation": "disabled", - "usage": null, - "user": null, - "metadata": {} - }, - "sequence_number": 1 - } - ResponseItemList: - type: object - description: A list of Response items. - properties: - object: - description: The type of object returned, must be `list`. - x-stainless-const: true - const: list - data: - type: array - description: A list of items used to generate this response. - items: - $ref: '#/components/schemas/ItemResource' - has_more: - type: boolean - description: Whether there are more items available. - first_id: - type: string - description: The ID of the first item in the list. - last_id: - type: string - description: The ID of the last item in the list. - required: - - object - - data - - has_more - - first_id - - last_id - x-oaiMeta: - name: The input item list - group: responses - example: | - { - "object": "list", - "data": [ - { - "id": "msg_abc123", - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "Tell me a three sentence bedtime story about a unicorn." - } - ] - } - ], - "first_id": "msg_abc123", - "last_id": "msg_abc123", - "has_more": false - } - ResponseLogProb: - type: object - description: | - A logprob is the logarithmic probability that the model assigns to producing - a particular token at a given position in the sequence. Less-negative (higher) - logprob values indicate greater model confidence in that token choice. - properties: - token: - description: A possible text token. - type: string - logprob: - description: | - The log probability of this token. - type: number - top_logprobs: - description: | - The log probability of the top 20 most likely tokens. - type: array - items: - type: object - properties: - token: - description: A possible text token. - type: string - logprob: - description: The log probability of this token. - type: number - required: - - token - - logprob - ResponseMCPCallArgumentsDeltaEvent: - type: object - title: ResponseMCPCallArgumentsDeltaEvent - description: | - Emitted when there is a delta (partial update) to the arguments of an MCP tool call. - properties: - type: - type: string - enum: - - response.mcp_call_arguments.delta - description: The type of the event. Always 'response.mcp_call_arguments.delta'. - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response's output array. - item_id: - type: string - description: The unique identifier of the MCP tool call item being processed. - delta: - type: string - description: | - A JSON string containing the partial update to the arguments for the MCP tool call. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - output_index - - item_id - - delta - - sequence_number - x-oaiMeta: - name: response.mcp_call_arguments.delta - group: responses - example: | - { - "type": "response.mcp_call_arguments.delta", - "output_index": 0, - "item_id": "item-abc", - "delta": "{", - "sequence_number": 1 - } - ResponseMCPCallArgumentsDoneEvent: - type: object - title: ResponseMCPCallArgumentsDoneEvent - description: | - Emitted when the arguments for an MCP tool call are finalized. - properties: - type: - type: string - enum: - - response.mcp_call_arguments.done - description: The type of the event. Always 'response.mcp_call_arguments.done'. - x-stainless-const: true - output_index: - type: integer - description: The index of the output item in the response's output array. - item_id: - type: string - description: The unique identifier of the MCP tool call item being processed. - arguments: - type: string - description: | - A JSON string containing the finalized arguments for the MCP tool call. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - output_index - - item_id - - arguments - - sequence_number - x-oaiMeta: - name: response.mcp_call_arguments.done - group: responses - example: | - { - "type": "response.mcp_call_arguments.done", - "output_index": 0, - "item_id": "item-abc", - "arguments": "{\"arg1\": \"value1\", \"arg2\": \"value2\"}", - "sequence_number": 1 - } - ResponseMCPCallCompletedEvent: - type: object - title: ResponseMCPCallCompletedEvent - description: | - Emitted when an MCP tool call has completed successfully. - properties: - type: - type: string - enum: - - response.mcp_call.completed - description: The type of the event. Always 'response.mcp_call.completed'. - x-stainless-const: true - item_id: - type: string - description: The ID of the MCP tool call item that completed. - output_index: - type: integer - description: The index of the output item that completed. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - item_id - - output_index - - sequence_number - x-oaiMeta: - name: response.mcp_call.completed - group: responses - example: | - { - "type": "response.mcp_call.completed", - "sequence_number": 1, - "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90", - "output_index": 0 - } - ResponseMCPCallFailedEvent: - type: object - title: ResponseMCPCallFailedEvent - description: | - Emitted when an MCP tool call has failed. - properties: - type: - type: string - enum: - - response.mcp_call.failed - description: The type of the event. Always 'response.mcp_call.failed'. - x-stainless-const: true - item_id: - type: string - description: The ID of the MCP tool call item that failed. - output_index: - type: integer - description: The index of the output item that failed. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - item_id - - output_index - - sequence_number - x-oaiMeta: - name: response.mcp_call.failed - group: responses - example: | - { - "type": "response.mcp_call.failed", - "sequence_number": 1, - "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90", - "output_index": 0 - } - ResponseMCPCallInProgressEvent: - type: object - title: ResponseMCPCallInProgressEvent - description: | - Emitted when an MCP tool call is in progress. - properties: - type: - type: string - enum: - - response.mcp_call.in_progress - description: The type of the event. Always 'response.mcp_call.in_progress'. - x-stainless-const: true - sequence_number: - type: integer - description: The sequence number of this event. - output_index: - type: integer - description: The index of the output item in the response's output array. - item_id: - type: string - description: The unique identifier of the MCP tool call item being processed. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.mcp_call.in_progress - group: responses - example: | - { - "type": "response.mcp_call.in_progress", - "sequence_number": 1, - "output_index": 0, - "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90" - } - ResponseMCPListToolsCompletedEvent: - type: object - title: ResponseMCPListToolsCompletedEvent - description: | - Emitted when the list of available MCP tools has been successfully retrieved. - properties: - type: - type: string - enum: - - response.mcp_list_tools.completed - description: The type of the event. Always 'response.mcp_list_tools.completed'. - x-stainless-const: true - item_id: - type: string - description: The ID of the MCP tool call item that produced this output. - output_index: - type: integer - description: The index of the output item that was processed. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - item_id - - output_index - - sequence_number - x-oaiMeta: - name: response.mcp_list_tools.completed - group: responses - example: | - { - "type": "response.mcp_list_tools.completed", - "sequence_number": 1, - "output_index": 0, - "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" - } - ResponseMCPListToolsFailedEvent: - type: object - title: ResponseMCPListToolsFailedEvent - description: | - Emitted when the attempt to list available MCP tools has failed. - properties: - type: - type: string - enum: - - response.mcp_list_tools.failed - description: The type of the event. Always 'response.mcp_list_tools.failed'. - x-stainless-const: true - item_id: - type: string - description: The ID of the MCP tool call item that failed. - output_index: - type: integer - description: The index of the output item that failed. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - item_id - - output_index - - sequence_number - x-oaiMeta: - name: response.mcp_list_tools.failed - group: responses - example: | - { - "type": "response.mcp_list_tools.failed", - "sequence_number": 1, - "output_index": 0, - "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" - } - ResponseMCPListToolsInProgressEvent: - type: object - title: ResponseMCPListToolsInProgressEvent - description: | - Emitted when the system is in the process of retrieving the list of available MCP tools. - properties: - type: - type: string - enum: - - response.mcp_list_tools.in_progress - description: The type of the event. Always 'response.mcp_list_tools.in_progress'. - x-stainless-const: true - item_id: - type: string - description: The ID of the MCP tool call item that is being processed. - output_index: - type: integer - description: The index of the output item that is being processed. - sequence_number: - type: integer - description: The sequence number of this event. - required: - - type - - item_id - - output_index - - sequence_number - x-oaiMeta: - name: response.mcp_list_tools.in_progress - group: responses - example: | - { - "type": "response.mcp_list_tools.in_progress", - "sequence_number": 1, - "output_index": 0, - "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" - } - ResponseModalities: - anyOf: - - type: array - description: > - Output types that you would like the model to generate. - - Most models are capable of generating text, which is the default: - - - `["text"]` - - - The `gpt-4o-audio-preview` model can also be used to - - [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model - generate - - both text and audio responses, you can use: - - - `["text", "audio"]` - items: - type: string - enum: - - text - - audio - - type: 'null' - ResponseOutputItemAddedEvent: - type: object - description: Emitted when a new output item is added. - properties: - type: - type: string - description: | - The type of the event. Always `response.output_item.added`. - enum: - - response.output_item.added - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that was added. - sequence_number: - type: integer - description: | - The sequence number of this event. - item: - $ref: '#/components/schemas/OutputItem' - description: | - The output item that was added. - required: - - type - - output_index - - item - - sequence_number - x-oaiMeta: - name: response.output_item.added - group: responses - example: | - { - "type": "response.output_item.added", - "output_index": 0, - "item": { - "id": "msg_123", - "status": "in_progress", - "type": "message", - "role": "assistant", - "content": [] - }, - "sequence_number": 1 - } - ResponseOutputItemDoneEvent: - type: object - description: Emitted when an output item is marked done. - properties: - type: - type: string - description: | - The type of the event. Always `response.output_item.done`. - enum: - - response.output_item.done - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that was marked done. - sequence_number: - type: integer - description: | - The sequence number of this event. - item: - $ref: '#/components/schemas/OutputItem' - description: | - The output item that was marked done. - required: - - type - - output_index - - item - - sequence_number - x-oaiMeta: - name: response.output_item.done - group: responses - example: | - { - "type": "response.output_item.done", - "output_index": 0, - "item": { - "id": "msg_123", - "status": "completed", - "type": "message", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", - "annotations": [] - } - ] - }, - "sequence_number": 1 - } - ResponseOutputTextAnnotationAddedEvent: - type: object - title: ResponseOutputTextAnnotationAddedEvent - description: | - Emitted when an annotation is added to output text content. - properties: - type: - type: string - enum: - - response.output_text.annotation.added - description: The type of the event. Always 'response.output_text.annotation.added'. - x-stainless-const: true - item_id: - type: string - description: The unique identifier of the item to which the annotation is being added. - output_index: - type: integer - description: The index of the output item in the response's output array. - content_index: - type: integer - description: The index of the content part within the output item. - annotation_index: - type: integer - description: The index of the annotation within the content part. - sequence_number: - type: integer - description: The sequence number of this event. - annotation: - type: object - description: The annotation object being added. (See annotation schema for details.) - required: - - type - - item_id - - output_index - - content_index - - annotation_index - - annotation - - sequence_number - x-oaiMeta: - name: response.output_text.annotation.added - group: responses - example: | - { - "type": "response.output_text.annotation.added", - "item_id": "item-abc", - "output_index": 0, - "content_index": 0, - "annotation_index": 0, - "annotation": { - "type": "text_annotation", - "text": "This is a test annotation", - "start": 0, - "end": 10 - }, - "sequence_number": 1 - } - ResponsePromptVariables: - anyOf: - - type: object - title: Prompt Variables - description: | - Optional map of values to substitute in for variables in your - prompt. The substitution values can either be strings, or other - Response input types like images or files. - x-oaiExpandable: true - x-oaiTypeLabel: map - additionalProperties: - x-oaiExpandable: true - x-oaiTypeLabel: map - anyOf: - - type: string - - $ref: '#/components/schemas/InputTextContent' - - $ref: '#/components/schemas/InputImageContent' - - $ref: '#/components/schemas/InputFileContent' - - type: 'null' - ResponseProperties: - type: object - properties: - previous_response_id: - anyOf: - - type: string - description: > - 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`. - - type: 'null' - model: - description: > - Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI - - offers a wide range of models with different capabilities, performance - - characteristics, and price points. Refer to the [model - guide](https://platform.openai.com/docs/models) - - to browse and compare available models. - $ref: '#/components/schemas/ModelIdsResponses' - reasoning: - anyOf: - - $ref: '#/components/schemas/Reasoning' - - type: 'null' - background: - anyOf: - - type: boolean - description: | - Whether to run the model response in the background. - [Learn more](https://platform.openai.com/docs/guides/background). - default: false - - type: 'null' - max_output_tokens: - anyOf: - - description: > - 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). - type: integer - - type: 'null' - max_tool_calls: - anyOf: - - description: > - The maximum number of total calls to built-in tools that can be processed in a response. This - maximum number applies across all built-in tool calls, not per individual tool. Any further - attempts to call a tool by the model will be ignored. - type: integer - - type: 'null' - text: - $ref: '#/components/schemas/ResponseTextParam' - tools: - $ref: '#/components/schemas/ToolsArray' - tool_choice: - $ref: '#/components/schemas/ToolChoiceParam' - prompt: - $ref: '#/components/schemas/Prompt' - truncation: - anyOf: - - type: string - description: | - The truncation strategy to use for the model response. - - `auto`: If the input to this Response exceeds - the model's context window size, the model will truncate the - response to fit the context window by dropping items from the beginning of the conversation. - - `disabled` (default): If the input size will exceed the context window - size for a model, the request will fail with a 400 error. - enum: - - auto - - disabled - default: disabled - - type: 'null' - ResponseQueuedEvent: - type: object - title: ResponseQueuedEvent - description: | - Emitted when a response is queued and waiting to be processed. - properties: - type: - type: string - enum: - - response.queued - description: The type of the event. Always 'response.queued'. - x-stainless-const: true - response: - $ref: '#/components/schemas/Response' - description: The full response object that is queued. - sequence_number: - type: integer - description: The sequence number for this event. - required: - - type - - response - - sequence_number - x-oaiMeta: - name: response.queued - group: responses - example: | - { - "type": "response.queued", - "response": { - "id": "res_123", - "status": "queued", - "created_at": "2021-01-01T00:00:00Z", - "updated_at": "2021-01-01T00:00:00Z" - }, - "sequence_number": 1 - } - ResponseReasoningSummaryPartAddedEvent: - type: object - description: Emitted when a new reasoning summary part is added. - properties: - type: - type: string - description: | - The type of the event. Always `response.reasoning_summary_part.added`. - enum: - - response.reasoning_summary_part.added - x-stainless-const: true - item_id: - type: string - description: | - The ID of the item this summary part is associated with. - output_index: - type: integer - description: | - The index of the output item this summary part is associated with. - summary_index: - type: integer - description: | - The index of the summary part within the reasoning summary. - sequence_number: - type: integer - description: | - The sequence number of this event. - part: - type: object - description: | - The summary part that was added. - properties: - type: - type: string - description: The type of the summary part. Always `summary_text`. - enum: - - summary_text - x-stainless-const: true - text: - type: string - description: The text of the summary part. - required: - - type - - text - required: - - type - - item_id - - output_index - - summary_index - - part - - sequence_number - x-oaiMeta: - name: response.reasoning_summary_part.added - group: responses - example: | - { - "type": "response.reasoning_summary_part.added", - "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", - "output_index": 0, - "summary_index": 0, - "part": { - "type": "summary_text", - "text": "" - }, - "sequence_number": 1 - } - ResponseReasoningSummaryPartDoneEvent: - type: object - description: Emitted when a reasoning summary part is completed. - properties: - type: - type: string - description: | - The type of the event. Always `response.reasoning_summary_part.done`. - enum: - - response.reasoning_summary_part.done - x-stainless-const: true - item_id: - type: string - description: | - The ID of the item this summary part is associated with. - output_index: - type: integer - description: | - The index of the output item this summary part is associated with. - summary_index: - type: integer - description: | - The index of the summary part within the reasoning summary. - sequence_number: - type: integer - description: | - The sequence number of this event. - part: - type: object - description: | - The completed summary part. - properties: - type: - type: string - description: The type of the summary part. Always `summary_text`. - enum: - - summary_text - x-stainless-const: true - text: - type: string - description: The text of the summary part. - required: - - type - - text - required: - - type - - item_id - - output_index - - summary_index - - part - - sequence_number - x-oaiMeta: - name: response.reasoning_summary_part.done - group: responses - example: | - { - "type": "response.reasoning_summary_part.done", - "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", - "output_index": 0, - "summary_index": 0, - "part": { - "type": "summary_text", - "text": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!" - }, - "sequence_number": 1 - } - ResponseReasoningSummaryTextDeltaEvent: - type: object - description: Emitted when a delta is added to a reasoning summary text. - properties: - type: - type: string - description: | - The type of the event. Always `response.reasoning_summary_text.delta`. - enum: - - response.reasoning_summary_text.delta - x-stainless-const: true - item_id: - type: string - description: | - The ID of the item this summary text delta is associated with. - output_index: - type: integer - description: | - The index of the output item this summary text delta is associated with. - summary_index: - type: integer - description: | - The index of the summary part within the reasoning summary. - delta: - type: string - description: | - The text delta that was added to the summary. - sequence_number: - type: integer - description: | - The sequence number of this event. - required: - - type - - item_id - - output_index - - summary_index - - delta - - sequence_number - x-oaiMeta: - name: response.reasoning_summary_text.delta - group: responses - example: | - { - "type": "response.reasoning_summary_text.delta", - "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", - "output_index": 0, - "summary_index": 0, - "delta": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!", - "sequence_number": 1 - } - ResponseReasoningSummaryTextDoneEvent: - type: object - description: Emitted when a reasoning summary text is completed. - properties: - type: - type: string - description: | - The type of the event. Always `response.reasoning_summary_text.done`. - enum: - - response.reasoning_summary_text.done - x-stainless-const: true - item_id: - type: string - description: | - The ID of the item this summary text is associated with. - output_index: - type: integer - description: | - The index of the output item this summary text is associated with. - summary_index: - type: integer - description: | - The index of the summary part within the reasoning summary. - text: - type: string - description: | - The full text of the completed reasoning summary. - sequence_number: - type: integer - description: | - The sequence number of this event. - required: - - type - - item_id - - output_index - - summary_index - - text - - sequence_number - x-oaiMeta: - name: response.reasoning_summary_text.done - group: responses - example: | - { - "type": "response.reasoning_summary_text.done", - "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", - "output_index": 0, - "summary_index": 0, - "text": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!", - "sequence_number": 1 - } - ResponseReasoningTextDeltaEvent: - type: object - description: Emitted when a delta is added to a reasoning text. - properties: - type: - type: string - description: | - The type of the event. Always `response.reasoning_text.delta`. - enum: - - response.reasoning_text.delta - x-stainless-const: true - item_id: - type: string - description: | - The ID of the item this reasoning text delta is associated with. - output_index: - type: integer - description: | - The index of the output item this reasoning text delta is associated with. - content_index: - type: integer - description: | - The index of the reasoning content part this delta is associated with. - delta: - type: string - description: | - The text delta that was added to the reasoning content. - sequence_number: - type: integer - description: | - The sequence number of this event. - required: - - type - - item_id - - output_index - - content_index - - delta - - sequence_number - x-oaiMeta: - name: response.reasoning_text.delta - group: responses - example: | - { - "type": "response.reasoning_text.delta", - "item_id": "rs_123", - "output_index": 0, - "content_index": 0, - "delta": "The", - "sequence_number": 1 - } - ResponseReasoningTextDoneEvent: - type: object - description: Emitted when a reasoning text is completed. - properties: - type: - type: string - description: | - The type of the event. Always `response.reasoning_text.done`. - enum: - - response.reasoning_text.done - x-stainless-const: true - item_id: - type: string - description: | - The ID of the item this reasoning text is associated with. - output_index: - type: integer - description: | - The index of the output item this reasoning text is associated with. - content_index: - type: integer - description: | - The index of the reasoning content part. - text: - type: string - description: | - The full text of the completed reasoning content. - sequence_number: - type: integer - description: | - The sequence number of this event. - required: - - type - - item_id - - output_index - - content_index - - text - - sequence_number - x-oaiMeta: - name: response.reasoning_text.done - group: responses - example: | - { - "type": "response.reasoning_text.done", - "item_id": "rs_123", - "output_index": 0, - "content_index": 0, - "text": "The user is asking...", - "sequence_number": 4 - } - ResponseRefusalDeltaEvent: - type: object - description: Emitted when there is a partial refusal text. - properties: - type: - type: string - description: | - The type of the event. Always `response.refusal.delta`. - enum: - - response.refusal.delta - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the refusal text is added to. - output_index: - type: integer - description: | - The index of the output item that the refusal text is added to. - content_index: - type: integer - description: | - The index of the content part that the refusal text is added to. - delta: - type: string - description: | - The refusal text that is added. - sequence_number: - type: integer - description: | - The sequence number of this event. - required: - - type - - item_id - - output_index - - content_index - - delta - - sequence_number - x-oaiMeta: - name: response.refusal.delta - group: responses - example: | - { - "type": "response.refusal.delta", - "item_id": "msg_123", - "output_index": 0, - "content_index": 0, - "delta": "refusal text so far", - "sequence_number": 1 - } - ResponseRefusalDoneEvent: - type: object - description: Emitted when refusal text is finalized. - properties: - type: - type: string - description: | - The type of the event. Always `response.refusal.done`. - enum: - - response.refusal.done - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the refusal text is finalized. - output_index: - type: integer - description: | - The index of the output item that the refusal text is finalized. - content_index: - type: integer - description: | - The index of the content part that the refusal text is finalized. - refusal: - type: string - description: | - The refusal text that is finalized. - sequence_number: - type: integer - description: | - The sequence number of this event. - required: - - type - - item_id - - output_index - - content_index - - refusal - - sequence_number - x-oaiMeta: - name: response.refusal.done - group: responses - example: | - { - "type": "response.refusal.done", - "item_id": "item-abc", - "output_index": 1, - "content_index": 2, - "refusal": "final refusal text", - "sequence_number": 1 - } - ResponseStreamEvent: - anyOf: - - $ref: '#/components/schemas/ResponseAudioDeltaEvent' - - $ref: '#/components/schemas/ResponseAudioDoneEvent' - - $ref: '#/components/schemas/ResponseAudioTranscriptDeltaEvent' - - $ref: '#/components/schemas/ResponseAudioTranscriptDoneEvent' - - $ref: '#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent' - - $ref: '#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent' - - $ref: '#/components/schemas/ResponseCodeInterpreterCallCompletedEvent' - - $ref: '#/components/schemas/ResponseCodeInterpreterCallInProgressEvent' - - $ref: '#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent' - - $ref: '#/components/schemas/ResponseCompletedEvent' - - $ref: '#/components/schemas/ResponseContentPartAddedEvent' - - $ref: '#/components/schemas/ResponseContentPartDoneEvent' - - $ref: '#/components/schemas/ResponseCreatedEvent' - - $ref: '#/components/schemas/ResponseErrorEvent' - - $ref: '#/components/schemas/ResponseFileSearchCallCompletedEvent' - - $ref: '#/components/schemas/ResponseFileSearchCallInProgressEvent' - - $ref: '#/components/schemas/ResponseFileSearchCallSearchingEvent' - - $ref: '#/components/schemas/ResponseFunctionCallArgumentsDeltaEvent' - - $ref: '#/components/schemas/ResponseFunctionCallArgumentsDoneEvent' - - $ref: '#/components/schemas/ResponseInProgressEvent' - - $ref: '#/components/schemas/ResponseFailedEvent' - - $ref: '#/components/schemas/ResponseIncompleteEvent' - - $ref: '#/components/schemas/ResponseOutputItemAddedEvent' - - $ref: '#/components/schemas/ResponseOutputItemDoneEvent' - - $ref: '#/components/schemas/ResponseReasoningSummaryPartAddedEvent' - - $ref: '#/components/schemas/ResponseReasoningSummaryPartDoneEvent' - - $ref: '#/components/schemas/ResponseReasoningSummaryTextDeltaEvent' - - $ref: '#/components/schemas/ResponseReasoningSummaryTextDoneEvent' - - $ref: '#/components/schemas/ResponseReasoningTextDeltaEvent' - - $ref: '#/components/schemas/ResponseReasoningTextDoneEvent' - - $ref: '#/components/schemas/ResponseRefusalDeltaEvent' - - $ref: '#/components/schemas/ResponseRefusalDoneEvent' - - $ref: '#/components/schemas/ResponseTextDeltaEvent' - - $ref: '#/components/schemas/ResponseTextDoneEvent' - - $ref: '#/components/schemas/ResponseWebSearchCallCompletedEvent' - - $ref: '#/components/schemas/ResponseWebSearchCallInProgressEvent' - - $ref: '#/components/schemas/ResponseWebSearchCallSearchingEvent' - - $ref: '#/components/schemas/ResponseImageGenCallCompletedEvent' - - $ref: '#/components/schemas/ResponseImageGenCallGeneratingEvent' - - $ref: '#/components/schemas/ResponseImageGenCallInProgressEvent' - - $ref: '#/components/schemas/ResponseImageGenCallPartialImageEvent' - - $ref: '#/components/schemas/ResponseMCPCallArgumentsDeltaEvent' - - $ref: '#/components/schemas/ResponseMCPCallArgumentsDoneEvent' - - $ref: '#/components/schemas/ResponseMCPCallCompletedEvent' - - $ref: '#/components/schemas/ResponseMCPCallFailedEvent' - - $ref: '#/components/schemas/ResponseMCPCallInProgressEvent' - - $ref: '#/components/schemas/ResponseMCPListToolsCompletedEvent' - - $ref: '#/components/schemas/ResponseMCPListToolsFailedEvent' - - $ref: '#/components/schemas/ResponseMCPListToolsInProgressEvent' - - $ref: '#/components/schemas/ResponseOutputTextAnnotationAddedEvent' - - $ref: '#/components/schemas/ResponseQueuedEvent' - - $ref: '#/components/schemas/ResponseCustomToolCallInputDeltaEvent' - - $ref: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' - discriminator: - propertyName: type - ResponseStreamOptions: - anyOf: - - description: | - Options for streaming responses. Only set this when you set `stream: true`. - type: object - properties: - include_obfuscation: - type: boolean - description: | - When true, stream obfuscation will be enabled. Stream obfuscation adds - random characters to an `obfuscation` field on streaming delta events to - normalize payload sizes as a mitigation to certain side-channel attacks. - These obfuscation fields are included by default, but add a small amount - of overhead to the data stream. You can set `include_obfuscation` to - false to optimize for bandwidth if you trust the network links between - your application and the OpenAI API. - - type: 'null' - ResponseTextDeltaEvent: - type: object - description: Emitted when there is an additional text delta. - properties: - type: - type: string - description: | - The type of the event. Always `response.output_text.delta`. - enum: - - response.output_text.delta - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the text delta was added to. - output_index: - type: integer - description: | - The index of the output item that the text delta was added to. - content_index: - type: integer - description: | - The index of the content part that the text delta was added to. - delta: - type: string - description: | - The text delta that was added. - sequence_number: - type: integer - description: The sequence number for this event. - logprobs: - type: array - description: | - The log probabilities of the tokens in the delta. - items: - $ref: '#/components/schemas/ResponseLogProb' - required: - - type - - item_id - - output_index - - content_index - - delta - - sequence_number - - logprobs - x-oaiMeta: - name: response.output_text.delta - group: responses - example: | - { - "type": "response.output_text.delta", - "item_id": "msg_123", - "output_index": 0, - "content_index": 0, - "delta": "In", - "sequence_number": 1 - } - ResponseTextDoneEvent: + response: + content: | + { + "object": "organization.project.api_key.deleted", + "id": "key_abc", + "deleted": true + } + error_response: + content: | + { + "code": 400, + "message": "API keys cannot be deleted for service accounts, please delete the service account" + } + +components: + securitySchemes: + ApiKeyAuth: + type: http + scheme: "bearer" + + schemas: + Error: type: object - description: Emitted when text content is finalized. properties: - type: - type: string - description: | - The type of the event. Always `response.output_text.done`. - enum: - - response.output_text.done - x-stainless-const: true - item_id: - type: string - description: | - The ID of the output item that the text content is finalized. - output_index: - type: integer - description: | - The index of the output item that the text content is finalized. - content_index: - type: integer - description: | - The index of the content part that the text content is finalized. - text: + code: type: string - description: | - The text content that is finalized. - sequence_number: - type: integer - description: The sequence number for this event. - logprobs: - type: array - description: | - The log probabilities of the tokens in the delta. - items: - $ref: '#/components/schemas/ResponseLogProb' - required: - - type - - item_id - - output_index - - content_index - - text - - sequence_number - - logprobs - x-oaiMeta: - name: response.output_text.done - group: responses - example: | - { - "type": "response.output_text.done", - "item_id": "msg_123", - "output_index": 0, - "content_index": 0, - "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", - "sequence_number": 1 - } - ResponseTextParam: - type: object - description: | - Configuration options for a text response from the model. Can be plain - text or structured JSON data. Learn more: - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - properties: - format: - $ref: '#/components/schemas/TextResponseFormatConfiguration' - verbosity: - $ref: '#/components/schemas/Verbosity' - ResponseUsage: - type: object - description: | - Represents token usage details including input tokens, output tokens, - a breakdown of output tokens, and the total tokens used. - properties: - input_tokens: - type: integer - description: The number of input tokens. - input_tokens_details: - type: object - description: A detailed breakdown of the input tokens. - properties: - cached_tokens: - type: integer - description: | - The number of tokens that were retrieved from the cache. - [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching). - required: - - cached_tokens - output_tokens: - type: integer - description: The number of output tokens. - output_tokens_details: - type: object - description: A detailed breakdown of the output tokens. - properties: - reasoning_tokens: - type: integer - description: The number of reasoning tokens. - required: - - reasoning_tokens - total_tokens: - type: integer - description: The total number of tokens used. - required: - - input_tokens - - input_tokens_details - - output_tokens - - output_tokens_details - - total_tokens - ResponseWebSearchCallCompletedEvent: - type: object - description: Emitted when a web search call is completed. - properties: - type: + nullable: true + message: type: string - description: | - The type of the event. Always `response.web_search_call.completed`. - enum: - - response.web_search_call.completed - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that the web search call is associated with. - item_id: + nullable: false + param: type: string - description: | - Unique ID for the output item associated with the web search call. - sequence_number: - type: integer - description: The sequence number of the web search call being processed. - required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.web_search_call.completed - group: responses - example: | - { - "type": "response.web_search_call.completed", - "output_index": 0, - "item_id": "ws_123", - "sequence_number": 0 - } - ResponseWebSearchCallInProgressEvent: - type: object - description: Emitted when a web search call is initiated. - properties: + nullable: true type: type: string - description: | - The type of the event. Always `response.web_search_call.in_progress`. - enum: - - response.web_search_call.in_progress - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that the web search call is associated with. - item_id: - type: string - description: | - Unique ID for the output item associated with the web search call. - sequence_number: - type: integer - description: The sequence number of the web search call being processed. + nullable: false required: - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.web_search_call.in_progress - group: responses - example: | - { - "type": "response.web_search_call.in_progress", - "output_index": 0, - "item_id": "ws_123", - "sequence_number": 0 - } - ResponseWebSearchCallSearchingEvent: + - message + - param + - code + ErrorResponse: type: object - description: Emitted when a web search call is executing. properties: - type: - type: string - description: | - The type of the event. Always `response.web_search_call.searching`. - enum: - - response.web_search_call.searching - x-stainless-const: true - output_index: - type: integer - description: | - The index of the output item that the web search call is associated with. - item_id: - type: string - description: | - Unique ID for the output item associated with the web search call. - sequence_number: - type: integer - description: The sequence number of the web search call being processed. + error: + $ref: "#/components/schemas/Error" required: - - type - - output_index - - item_id - - sequence_number - x-oaiMeta: - name: response.web_search_call.searching - group: responses - example: | - { - "type": "response.web_search_call.searching", - "output_index": 0, - "item_id": "ws_123", - "sequence_number": 0 - } - Role: + - error + + ListModelsResponse: type: object - description: Details about a role that can be assigned through the public Roles API. properties: object: type: string - enum: - - role - description: Always `role`. - x-stainless-const: true - id: - type: string - description: Identifier for the role. - name: - type: string - description: Unique name for the role. - description: - description: Optional description of the role. - anyOf: - - type: string - - type: 'null' - permissions: + enum: [list] + data: type: array - description: Permissions granted by the role. items: - type: string - resource_type: - type: string - description: Resource type the role is bound to (for example `api.organization` or `api.project`). - predefined_role: - type: boolean - description: Whether the role is predefined and managed by OpenAI. + $ref: "#/components/schemas/Model" required: - object - - id - - name - - description - - permissions - - resource_type - - predefined_role - x-oaiMeta: - name: The role object - example: | - { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - RoleDeletedResource: + - data + DeleteModelResponse: type: object - description: Confirmation payload returned after deleting a role. properties: - object: - type: string - enum: - - role.deleted - description: Always `role.deleted`. - x-stainless-const: true id: type: string - description: Identifier of the deleted role. deleted: type: boolean - description: Whether the role was deleted. - required: - - object - - id - - deleted - x-oaiMeta: - name: Role deletion confirmation - example: | - { - "object": "role.deleted", - "id": "role_01J1F8ROLE01", - "deleted": true - } - RoleListResource: - type: object - description: Paginated list of roles assigned to a principal. - properties: object: type: string - enum: - - list - description: Always `list`. - x-stainless-const: true - data: - type: array - description: Role assignments returned in the current page. - items: - $ref: '#/components/schemas/AssignedRoleDetails' - has_more: - type: boolean - description: Whether additional assignments are available when paginating. - next: - description: Cursor to fetch the next page of results, or `null` when there are no more assignments. - anyOf: - - type: string - - type: 'null' required: + - id - object - - data - - has_more - - next - x-oaiMeta: - name: Assigned role list - example: | - { - "object": "list", - "data": [ - { - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false, - "description": "Allows managing organization groups", - "created_at": 1711471533, - "updated_at": 1711472599, - "created_by": "user_abc123", - "created_by_user_obj": { - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com" - }, - "metadata": {} - } - ], - "has_more": false, - "next": null - } - RunCompletionUsage: - anyOf: - - type: object - description: >- - Usage statistics related to the run. This value will be `null` if the run is not in a terminal - state (i.e. `in_progress`, `queued`, etc.). - properties: - completion_tokens: - type: integer - description: Number of completion tokens used over the course of the run. - prompt_tokens: - type: integer - description: Number of prompt tokens used over the course of the run. - total_tokens: - type: integer - description: Total number of tokens used (prompt + completion). - required: - - prompt_tokens - - completion_tokens - - total_tokens - - type: 'null' - RunGraderRequest: + - deleted + + CreateCompletionRequest: type: object - title: RunGraderRequest properties: - grader: - type: object - description: The grader used for the fine-tuning job. + model: + description: &model_description | + ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. anyOf: - - $ref: '#/components/schemas/GraderStringCheck' - - $ref: '#/components/schemas/GraderTextSimilarity' - - $ref: '#/components/schemas/GraderPython' - - $ref: '#/components/schemas/GraderScoreModel' - - $ref: '#/components/schemas/GraderMulti' - discriminator: - propertyName: type - item: - type: object - description: > - The dataset item provided to the grader. This will be used to populate - - the `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more - details. - model_sample: - type: string - description: > - The model sample to be evaluated. This value will be used to populate - - the `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more - details. - - The `output_json` variable will be populated if the model sample is a + - type: string + - type: string + enum: ["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"] + x-oaiTypeLabel: string + prompt: + description: &completions_prompt_description | + The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. - valid JSON string. - - required: - - grader - - model_sample - RunGraderResponse: - type: object - properties: - reward: - type: number - metadata: - type: object - properties: - name: - type: string - type: - type: string - errors: - type: object - properties: - formula_parse_error: - type: boolean - sample_parse_error: - type: boolean - truncated_observation_error: - type: boolean - unresponsive_reward_error: - type: boolean - invalid_variable_error: - type: boolean - other_error: - type: boolean - python_grader_server_error: - type: boolean - python_grader_server_error_type: - anyOf: - - type: string - - type: 'null' - python_grader_runtime_error: - type: boolean - python_grader_runtime_error_details: - anyOf: - - type: string - - type: 'null' - model_grader_server_error: - type: boolean - model_grader_refusal_error: - type: boolean - model_grader_parse_error: - type: boolean - model_grader_server_error_details: - anyOf: - - type: string - - type: 'null' - required: - - formula_parse_error - - sample_parse_error - - truncated_observation_error - - unresponsive_reward_error - - invalid_variable_error - - other_error - - python_grader_server_error - - python_grader_server_error_type - - python_grader_runtime_error - - python_grader_runtime_error_details - - model_grader_server_error - - model_grader_refusal_error - - model_grader_parse_error - - model_grader_server_error_details - execution_time: - type: number - scores: - type: object - additionalProperties: {} - token_usage: - anyOf: - - type: integer - - type: 'null' - sampled_model_name: - anyOf: - - type: string - - type: 'null' - required: - - name - - type - - errors - - execution_time - - scores - - token_usage - - sampled_model_name - sub_rewards: - type: object - additionalProperties: {} - model_grader_token_usage_per_model: - type: object - additionalProperties: {} - required: - - reward - - metadata - - sub_rewards - - model_grader_token_usage_per_model - RunObject: - type: object - title: A run on a thread - description: Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads). - properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `thread.run`. - type: string - enum: - - thread.run - x-stainless-const: true - created_at: - description: The Unix timestamp (in seconds) for when the run was created. + Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document. + default: "<|endoftext|>" + nullable: true + oneOf: + - type: string + default: "" + example: "This is a test." + - type: array + items: + type: string + default: "" + example: "This is a test." + - type: array + minItems: 1 + items: + type: integer + example: "[1212, 318, 257, 1332, 13]" + - type: array + minItems: 1 + items: + type: array + minItems: 1 + items: + type: integer + example: "[[1212, 318, 257, 1332, 13]]" + best_of: type: integer - thread_id: - description: >- - The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed - on as a part of this run. - type: string - assistant_id: - description: >- - The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - execution of this run. - type: string - status: - $ref: '#/components/schemas/RunStatus' - required_action: - type: object - description: Details on the action required to continue the run. Will be `null` if no action is required. + default: 1 + minimum: 0 + maximum: 20 nullable: true - properties: - type: - description: For now, this is always `submit_tool_outputs`. - type: string - enum: - - submit_tool_outputs - x-stainless-const: true - submit_tool_outputs: - type: object - description: Details on the tool outputs needed for this run to continue. - properties: - tool_calls: - type: array - description: A list of the relevant tool calls. - items: - $ref: '#/components/schemas/RunToolCallObject' - required: - - tool_calls - required: - - type - - submit_tool_outputs - last_error: + description: &completions_best_of_description | + Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. + echo: + type: boolean + default: false + nullable: true + description: &completions_echo_description > + Echo back the prompt in addition to the completion + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: &completions_frequency_penalty_description | + Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. + + [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + logit_bias: &completions_logit_bias type: object - description: The last error associated with this run. Will be `null` if there are no errors. + x-oaiTypeLabel: map + default: null nullable: true - properties: - code: - type: string - description: One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. - enum: - - server_error - - rate_limit_exceeded - - invalid_prompt - message: - type: string - description: A human-readable description of the error. - required: - - code - - message - expires_at: - description: The Unix timestamp (in seconds) for when the run will expire. + additionalProperties: + type: integer + description: &completions_logit_bias_description | + Modify the likelihood of specified tokens appearing in the completion. + + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. + logprobs: &completions_logprobs_configuration type: integer + minimum: 0 + maximum: 5 + default: null nullable: true - started_at: - description: The Unix timestamp (in seconds) for when the run was started. + description: &completions_logprobs_description | + Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + max_tokens: type: integer + minimum: 0 + default: 16 + example: 16 nullable: true - cancelled_at: - description: The Unix timestamp (in seconds) for when the run was cancelled. + description: &completions_max_tokens_description | + The maximum number of [tokens](/tokenizer) that can be generated in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + n: type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 nullable: true - failed_at: - description: The Unix timestamp (in seconds) for when the run failed. - type: integer + description: &completions_completions_description | + How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 nullable: true - completed_at: - description: The Unix timestamp (in seconds) for when the run was completed. + description: &completions_presence_penalty_description | + Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. + + [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + seed: &completions_seed_param type: integer + minimum: -9223372036854775808 + maximum: 9223372036854775807 nullable: true - incomplete_details: - description: Details on why the run is incomplete. Will be `null` if the run is not incomplete. - type: object + description: | + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + stop: + description: &completions_stop_description > + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. + default: null + nullable: true + oneOf: + - type: string + default: <|endoftext|> + example: "\n" + nullable: true + - type: array + minItems: 1 + maxItems: 4 + items: + type: string + example: '["\n"]' + stream: + description: > + Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + type: boolean + nullable: true + default: false + stream_options: + $ref: "#/components/schemas/ChatCompletionStreamOptions" + suffix: + description: | + The suffix that comes after a completion of inserted text. + + This parameter is only supported for `gpt-3.5-turbo-instruct`. + default: null nullable: true - properties: - reason: - description: >- - The reason why the run is incomplete. This will point to which specific token limit was - reached over the course of the run. - type: string - enum: - - max_completion_tokens - - max_prompt_tokens - model: - description: >- - The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - this run. - type: string - instructions: - description: >- - The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) - used for this run. type: string - tools: - description: >- - The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) - used for this run. - default: [] - type: array - maxItems: 20 - items: - $ref: '#/components/schemas/AssistantTool' - metadata: - $ref: '#/components/schemas/Metadata' - usage: - $ref: '#/components/schemas/RunCompletionUsage' + example: "test." temperature: - description: The sampling temperature used for this run. If not set, defaults to 1. type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 nullable: true + description: &completions_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. top_p: - description: The nucleus sampling value used for this run. If not set, defaults to 1. type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 nullable: true - max_prompt_tokens: - type: integer - nullable: true - description: | - The maximum number of prompt tokens specified to have been used over the course of the run. - minimum: 256 - max_completion_tokens: - type: integer - nullable: true + description: &completions_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + user: &end_user_param_configuration + type: string + example: user-1234 description: | - The maximum number of completion tokens specified to have been used over the course of the run. - minimum: 256 - truncation_strategy: - allOf: - - $ref: '#/components/schemas/TruncationObject' - - nullable: true - tool_choice: - allOf: - - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - - nullable: true - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - response_format: - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - nullable: true + A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). required: - - id - - object - - created_at - - thread_id - - assistant_id - - status - - required_action - - last_error - - expires_at - - started_at - - cancelled_at - - failed_at - - completed_at - model - - instructions - - tools - - metadata - - usage - - incomplete_details - - max_prompt_tokens - - max_completion_tokens - - truncation_strategy - - tool_choice - - parallel_tool_calls - - response_format - x-oaiMeta: - name: The run object - beta: true - example: | - { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1698107661, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "status": "completed", - "started_at": 1699073476, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699073498, - "last_error": null, - "model": "gpt-4o", - "instructions": null, - "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], - "metadata": {}, - "incomplete_details": null, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - }, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true - } - RunStepCompletionUsage: - anyOf: - - type: object - description: >- - Usage statistics related to the run step. This value will be `null` while the run step's status is - `in_progress`. - properties: - completion_tokens: - type: integer - description: Number of completion tokens used over the course of the run step. - prompt_tokens: - type: integer - description: Number of prompt tokens used over the course of the run step. - total_tokens: - type: integer - description: Total number of tokens used (prompt + completion). - required: - - prompt_tokens - - completion_tokens - - total_tokens - - type: 'null' - RunStepDeltaObject: + - prompt + + CreateCompletionResponse: type: object - title: Run step delta object description: | - Represents a run step delta i.e. any changed fields on a run step during streaming. + Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint). properties: id: - description: The identifier of the run step, which can be referenced in API endpoints. type: string + description: A unique identifier for the completion. + choices: + type: array + description: The list of completion choices the model generated for the input prompt. + items: + type: object + required: + - finish_reason + - index + - logprobs + - text + properties: + finish_reason: + type: string + description: &completion_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + or `content_filter` if content was omitted due to a flag from our content filters. + enum: ["stop", "length", "content_filter"] + nullable: true + index: + type: integer + logprobs: + type: object + nullable: true + properties: + text_offset: + type: array + items: + type: integer + token_logprobs: + type: array + items: + type: number + tokens: + type: array + items: + type: string + top_logprobs: + type: array + items: + type: object + additionalProperties: + type: number + text: + type: string + created: + type: integer + description: The Unix timestamp (in seconds) of when the completion was created. + model: + type: string + description: The model used for completion. + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. object: - description: The object type, which is always `thread.run.step.delta`. type: string - enum: - - thread.run.step.delta - x-stainless-const: true - delta: - $ref: '#/components/schemas/RunStepDeltaObjectDelta' + description: The object type, which is always "text_completion" + enum: [text_completion] + usage: + $ref: "#/components/schemas/CompletionUsage" required: - id - object - - delta + - created + - model + - choices x-oaiMeta: - name: The run step delta object - beta: true + name: The completion object + legacy: true example: | { - "id": "step_123", - "object": "thread.run.step.delta", - "delta": { - "step_details": { - "type": "tool_calls", - "tool_calls": [ - { - "index": 0, - "id": "call_123", - "type": "code_interpreter", - "code_interpreter": { "input": "", "outputs": [] } - } - ] + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "gpt-4-turbo", + "choices": [ + { + "text": "\n\nThis is indeed a test", + "index": 0, + "logprobs": null, + "finish_reason": "length" } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 7, + "total_tokens": 12 } } - RunStepDeltaStepDetailsMessageCreationObject: - title: Message creation + + ChatCompletionRequestMessageContentPartText: type: object - description: Details of the message creation by the run step. + title: Text content part properties: type: - description: Always `message_creation`. type: string - enum: - - message_creation - x-stainless-const: true - message_creation: - type: object - properties: - message_id: - type: string - description: The ID of the message that was created by this run step. + enum: ["text"] + description: The type of the content part. + text: + type: string + description: The text content. required: - type - RunStepDeltaStepDetailsToolCallsCodeObject: - title: Code interpreter tool call + - text + + ChatCompletionRequestMessageContentPartImage: type: object - description: Details of the Code Interpreter tool call the run step was involved in. + title: Image content part properties: - index: - type: integer - description: The index of the tool call in the tool calls array. - id: - type: string - description: The ID of the tool call. type: type: string - description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. - enum: - - code_interpreter - x-stainless-const: true - code_interpreter: + enum: ["image_url"] + description: The type of the content part. + image_url: type: object - description: The Code Interpreter tool call definition. properties: - input: + url: type: string - description: The input to the Code Interpreter tool call. - outputs: - type: array - description: >- - The outputs from the Code Interpreter tool call. Code Interpreter can output one or more - items, including text (`logs`) or images (`image`). Each of these are represented by a - different object type. - items: - type: object - anyOf: - - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject' - - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject' - discriminator: - propertyName: type + description: Either a URL of the image or the base64 encoded image data. + format: uri + detail: + type: string + description: Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). + enum: ["auto", "low", "high"] + default: "auto" + required: + - url required: - - index - type - RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: - title: Code interpreter image output + - image_url + + ChatCompletionRequestMessageContentPartRefusal: type: object + title: Refusal content part properties: - index: - type: integer - description: The index of the output in the outputs array. type: - description: Always `image`. type: string - enum: - - image - x-stainless-const: true - image: + enum: ["refusal"] + description: The type of the content part. + refusal: + type: string + description: The refusal message generated by the model. + required: + - type + - refusal + + ChatCompletionRequestMessage: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" + - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" + - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" + - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" + - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" + x-oaiExpandable: true + discriminator: + propertyName: role + mapping: + system: "#/components/schemas/ChatCompletionRequestSystemMessage" + user: "#/components/schemas/ChatCompletionRequestUserMessage" + assistant: "#/components/schemas/ChatCompletionRequestAssistantMessage" + tool: "#/components/schemas/ChatCompletionRequestToolMessage" + function: "#/components/schemas/ChatCompletionRequestFunctionMessage" + + ChatCompletionRequestSystemMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + x-oaiExpandable: true + + ChatCompletionRequestUserMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartImage" + x-oaiExpandable: true + + ChatCompletionRequestAssistantMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartRefusal" + x-oaiExpandable: true + + ChatCompletionRequestToolMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + x-oaiExpandable: true + + ChatCompletionRequestSystemMessage: + type: object + title: System message + properties: + content: + description: The contents of the system message. + oneOf: + - type: string + description: The contents of the system message. + title: Text content + - type: array + description: An array of content parts with a defined type. For system messages, only type `text` is supported. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestSystemMessageContentPart" + minItems: 1 + role: + type: string + enum: ["system"] + description: The role of the messages author, in this case `system`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + required: + - content + - role + + ChatCompletionRequestUserMessage: + type: object + title: User message + properties: + content: + description: | + The contents of the user message. + oneOf: + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4o` model. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestUserMessageContentPart" + minItems: 1 + x-oaiExpandable: true + role: + type: string + enum: ["user"] + description: The role of the messages author, in this case `user`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + required: + - content + - role + + ChatCompletionRequestAssistantMessage: + type: object + title: Assistant message + properties: + content: + nullable: true + oneOf: + - type: string + description: The contents of the assistant message. + title: Text content + - type: array + description: An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestAssistantMessageContentPart" + minItems: 1 + description: | + The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. + refusal: + nullable: true + type: string + description: The refusal message by the assistant. + role: + type: string + enum: ["assistant"] + description: The role of the messages author, in this case `assistant`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + tool_calls: + $ref: "#/components/schemas/ChatCompletionMessageToolCalls" + function_call: type: object + deprecated: true + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + nullable: true + properties: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + required: + - arguments + - name + required: + - role + + FineTuneChatCompletionRequestAssistantMessage: + allOf: + - type: object + title: Assistant message + deprecated: false properties: - file_id: - description: The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. - type: string + weight: + type: integer + enum: [0, 1] + description: "Controls whether the assistant message is trained against (0 or 1)" + - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" required: - - index - - type - RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: - title: Code interpreter log output + - role + + ChatCompletionRequestToolMessage: type: object - description: Text output from the Code Interpreter tool call as part of a run step. + title: Tool message properties: - index: - type: integer - description: The index of the output in the outputs array. - type: - description: Always `logs`. + role: type: string - enum: - - logs - x-stainless-const: true - logs: + enum: ["tool"] + description: The role of the messages author, in this case `tool`. + content: + oneOf: + - type: string + description: The contents of the tool message. + title: Text content + - type: array + description: An array of content parts with a defined type. For tool messages, only type `text` is supported. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestToolMessageContentPart" + minItems: 1 + description: The contents of the tool message. + tool_call_id: type: string - description: The text output from the Code Interpreter tool call. + description: Tool call that this message is responding to. required: - - index - - type - RunStepDeltaStepDetailsToolCallsFileSearchObject: - title: File search tool call + - role + - content + - tool_call_id + + ChatCompletionRequestFunctionMessage: type: object + title: Function message + deprecated: true properties: - index: - type: integer - description: The index of the tool call in the tool calls array. - id: + role: type: string - description: The ID of the tool call object. - type: + enum: ["function"] + description: The role of the messages author, in this case `function`. + content: + nullable: true type: string - description: The type of tool call. This is always going to be `file_search` for this type of tool call. - enum: - - file_search - x-stainless-const: true - file_search: - type: object - description: For now, this is always going to be an empty object. - x-oaiTypeLabel: map + description: The contents of the function message. + name: + type: string + description: The name of the function to call. required: - - index - - type - - file_search - RunStepDeltaStepDetailsToolCallsFunctionObject: + - role + - content + - name + + FunctionParameters: type: object - title: Function tool call + description: "The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. \n\nOmitting `parameters` defines a function with an empty parameter list." + additionalProperties: true + + ChatCompletionFunctions: + type: object + deprecated: true properties: - index: - type: integer - description: The index of the tool call in the tool calls array. - id: + description: type: string - description: The ID of the tool call object. - type: + description: A description of what the function does, used by the model to choose when and how to call the function. + name: type: string - description: The type of tool call. This is always going to be `function` for this type of tool call. - enum: - - function - x-stainless-const: true - function: - type: object - description: The definition of the function that was called. - properties: - name: - type: string - description: The name of the function. - arguments: - type: string - description: The arguments passed to the function. - output: - anyOf: - - type: string - description: >- - The output of the function. This will be `null` if the outputs have not been - [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet. - - type: 'null' + description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: "#/components/schemas/FunctionParameters" required: - - index - - type - RunStepDeltaStepDetailsToolCallsObject: - title: Tool calls + - name + + ChatCompletionFunctionCallOption: type: object - description: Details of the tool call. + description: > + Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. properties: - type: - description: Always `tool_calls`. + name: type: string - enum: - - tool_calls - x-stainless-const: true - tool_calls: - type: array - description: > - An array of tool calls the run step was involved in. These can be associated with one of three - types of tools: `code_interpreter`, `file_search`, or `function`. - items: - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCall' + description: The name of the function to call. required: - - type - RunStepDetailsMessageCreationObject: - title: Message creation + - name + + ChatCompletionTool: type: object - description: Details of the message creation by the run step. properties: type: - description: Always `message_creation`. type: string - enum: - - message_creation - x-stainless-const: true - message_creation: - type: object - properties: - message_id: - type: string - description: The ID of the message that was created by this run step. - required: - - message_id + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + $ref: "#/components/schemas/FunctionObject" required: - type - - message_creation - RunStepDetailsToolCallsCodeObject: - title: Code Interpreter tool call + - function + + FunctionObject: type: object - description: Details of the Code Interpreter tool call the run step was involved in. properties: - id: + description: type: string - description: The ID of the tool call. - type: + description: A description of what the function does, used by the model to choose when and how to call the function. + name: type: string - description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. - enum: - - code_interpreter - x-stainless-const: true - code_interpreter: - type: object - description: The Code Interpreter tool call definition. - required: - - input - - outputs - properties: - input: - type: string - description: The input to the Code Interpreter tool call. - outputs: - type: array - description: >- - The outputs from the Code Interpreter tool call. Code Interpreter can output one or more - items, including text (`logs`) or images (`image`). Each of these are represented by a - different object type. - items: - type: object - anyOf: - - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject' - - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject' - discriminator: - propertyName: type + description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: "#/components/schemas/FunctionParameters" + strict: + type: boolean + nullable: true + # default: false (TODO: dmchoi) revert once vllm updates their spec + description: Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). required: - - id - - type - - code_interpreter - RunStepDetailsToolCallsCodeOutputImageObject: - title: Code Interpreter image output + - name + + ResponseFormatText: type: object properties: type: - description: Always `image`. type: string - enum: - - image - x-stainless-const: true - image: - type: object - properties: - file_id: - description: The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. - type: string - required: - - file_id + description: "The type of response format being defined: `text`" + enum: ["text"] required: - type - - image - x-stainless-naming: - java: - type_name: ImageOutput - kotlin: - type_name: ImageOutput - RunStepDetailsToolCallsCodeOutputLogsObject: - title: Code Interpreter log output + + ResponseFormatJsonObject: type: object - description: Text output from the Code Interpreter tool call as part of a run step. properties: type: - description: Always `logs`. - type: string - enum: - - logs - x-stainless-const: true - logs: type: string - description: The text output from the Code Interpreter tool call. + description: "The type of response format being defined: `json_object`" + enum: ["json_object"] required: - type - - logs - x-stainless-naming: - java: - type_name: LogsOutput - kotlin: - type_name: LogsOutput - RunStepDetailsToolCallsFileSearchObject: - title: File search tool call + + ResponseFormatJsonSchemaSchema: + type: object + description: "The schema for the response format, described as a JSON Schema object." + additionalProperties: true + + ResponseFormatJsonSchema: type: object properties: - id: - type: string - description: The ID of the tool call object. type: type: string - description: The type of tool call. This is always going to be `file_search` for this type of tool call. - enum: - - file_search - x-stainless-const: true - file_search: + description: "The type of response format being defined: `json_schema`" + enum: ["json_schema"] + json_schema: type: object - description: For now, this is always going to be an empty object. - x-oaiTypeLabel: map properties: - ranking_options: - $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchRankingOptionsObject' - results: - type: array - description: The results of the file search. - items: - $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchResultObject' - required: - - id - - type - - file_search - RunStepDetailsToolCallsFileSearchRankingOptionsObject: - title: File search tool call ranking options - type: object - description: The ranking options for the file search. - properties: - ranker: - $ref: '#/components/schemas/FileSearchRanker' - score_threshold: - type: number - description: >- - The score threshold for the file search. All values must be a floating point number between 0 and - 1. - minimum: 0 - maximum: 1 - required: - - ranker - - score_threshold - RunStepDetailsToolCallsFileSearchResultObject: - title: File search tool call result - type: object - description: A result instance of the file search. - x-oaiTypeLabel: map - properties: - file_id: - type: string - description: The ID of the file that result was found in. - file_name: - type: string - description: The name of the file that result was found in. - score: - type: number - description: The score of the result. All values must be a floating point number between 0 and 1. - minimum: 0 - maximum: 1 - content: - type: array - description: >- - The content of the result that was found. The content is only included if requested via the - include query parameter. - items: - type: object - properties: - type: - type: string - description: The type of the content. - enum: - - text - x-stainless-const: true - text: - type: string - description: The text content of the file. + description: + type: string + description: A description of what the response format is for, used by the model to determine how to respond in the format. + name: + type: string + description: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + schema: + $ref: "#/components/schemas/ResponseFormatJsonSchemaSchema" + strict: + type: boolean + nullable: true + default: false + description: Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + required: + - type + - name required: - - file_id - - file_name - - score - RunStepDetailsToolCallsFunctionObject: + - type + - json_schema + + ChatCompletionToolChoiceOption: + description: | + Controls which (if any) tool is called by the model. + `none` means the model will not call any tool and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools. + Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + + `none` is the default when no tools are present. `auto` is the default if tools are present. + oneOf: + - type: string + description: > + `none` means the model will not call any tool and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools. + enum: [none, auto, required] + - $ref: "#/components/schemas/ChatCompletionNamedToolChoice" + x-oaiExpandable: true + + ChatCompletionNamedToolChoice: type: object - title: Function tool call + description: Specifies a tool the model should use. Use to force the model to call a specific function. properties: - id: - type: string - description: The ID of the tool call object. type: type: string - description: The type of tool call. This is always going to be `function` for this type of tool call. - enum: - - function - x-stainless-const: true + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. function: type: object - description: The definition of the function that was called. properties: name: type: string - description: The name of the function. - arguments: - type: string - description: The arguments passed to the function. - output: - anyOf: - - type: string - description: >- - The output of the function. This will be `null` if the outputs have not been - [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet. - - type: 'null' + description: The name of the function to call. required: - name - - arguments - - output required: - - id - type - function - RunStepDetailsToolCallsObject: - title: Tool calls - type: object - description: Details of the tool call. - properties: - type: - description: Always `tool_calls`. - type: string - enum: - - tool_calls - x-stainless-const: true - tool_calls: - type: array - description: > - An array of tool calls the run step was involved in. These can be associated with one of three - types of tools: `code_interpreter`, `file_search`, or `function`. - items: - $ref: '#/components/schemas/RunStepDetailsToolCall' - required: - - type - - tool_calls - RunStepObject: + + ParallelToolCalls: + description: Whether to enable [parallel function calling](/docs/guides/function-calling/parallel-function-calling) during tool use. + type: boolean + default: true + + ChatCompletionMessageToolCalls: + type: array + description: The tool calls generated by the model, such as function calls. + items: + $ref: "#/components/schemas/ChatCompletionMessageToolCall" + + ChatCompletionMessageToolCall: type: object - title: Run steps - description: | - Represents a step in execution of a run. properties: + # TODO: index included when streaming id: - description: The identifier of the run step, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `thread.run.step`. - type: string - enum: - - thread.run.step - x-stainless-const: true - created_at: - description: The Unix timestamp (in seconds) for when the run step was created. - type: integer - assistant_id: - description: >- - The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated - with the run step. - type: string - thread_id: - description: The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run. - type: string - run_id: - description: >- - The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a - part of. type: string + description: The ID of the tool call. type: - description: The type of run step, which can be either `message_creation` or `tool_calls`. type: string - enum: - - message_creation - - tool_calls - status: - description: >- - The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, - or `expired`. - type: string - enum: - - in_progress - - cancelled - - failed - - completed - - expired - step_details: - type: object - description: The details of the run step. - anyOf: - - $ref: '#/components/schemas/RunStepDetailsMessageCreationObject' - - $ref: '#/components/schemas/RunStepDetailsToolCallsObject' - discriminator: - propertyName: type - last_error: - anyOf: - - type: object - description: The last error associated with this run step. Will be `null` if there are no errors. - properties: - code: - type: string - description: One of `server_error` or `rate_limit_exceeded`. - enum: - - server_error - - rate_limit_exceeded - message: - type: string - description: A human-readable description of the error. - required: - - code - - message - - type: 'null' - expired_at: - anyOf: - - description: >- - The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if - the parent run is expired. - type: integer - - type: 'null' - cancelled_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the run step was cancelled. - type: integer - - type: 'null' - failed_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the run step failed. - type: integer - - type: 'null' - completed_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the run step completed. - type: integer - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - usage: - $ref: '#/components/schemas/RunStepCompletionUsage' - required: - - id - - object - - created_at - - assistant_id - - thread_id - - run_id - - type - - status - - step_details - - last_error - - expired_at - - cancelled_at - - failed_at - - completed_at - - metadata - - usage - x-oaiMeta: - name: The run step object - beta: true - example: | - { - "id": "step_abc123", - "object": "thread.run.step", - "created_at": 1699063291, - "run_id": "run_abc123", - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", - "type": "message_creation", - "status": "completed", - "cancelled_at": null, - "completed_at": 1699063291, - "expired_at": null, - "failed_at": null, - "last_error": null, - "step_details": { - "type": "message_creation", - "message_creation": { - "message_id": "msg_abc123" - } - }, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - } - } - RunStepStreamEvent: - anyOf: - - type: object - properties: - event: - type: string - enum: - - thread.run.step.created - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepObject' - required: - - event - - data - description: >- - Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is - created. - x-oaiMeta: - dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.step.in_progress - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepObject' - required: - - event - - data - description: >- - Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) - moves to an `in_progress` state. - x-oaiMeta: - dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.step.delta - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepDeltaObject' - required: - - event - - data - description: >- - Occurs when parts of a [run - step](https://platform.openai.com/docs/api-reference/run-steps/step-object) are being streamed. - x-oaiMeta: - dataDescription: '`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.step.completed - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepObject' - required: - - event - - data - description: >- - Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is - completed. - x-oaiMeta: - dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.step.failed - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepObject' - required: - - event - - data - description: >- - Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) - fails. - x-oaiMeta: - dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.step.cancelled - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepObject' - required: - - event - - data - description: >- - Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is - cancelled. - x-oaiMeta: - dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.step.expired - x-stainless-const: true - data: - $ref: '#/components/schemas/RunStepObject' - required: - - event - - data - description: >- - Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) - expires. - x-oaiMeta: - dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' - discriminator: - propertyName: event - RunStreamEvent: - anyOf: - - type: object - properties: - event: - type: string - enum: - - thread.run.created - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: Occurs when a new [run](https://platform.openai.com/docs/api-reference/runs/object) is created. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object - properties: - event: - type: string - enum: - - thread.run.queued - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: >- - Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a - `queued` status. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + description: The function that the model called. properties: - event: + name: type: string - enum: - - thread.run.in_progress - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: >- - Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to an - `in_progress` status. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object - properties: - event: + description: The name of the function to call. + arguments: type: string - enum: - - thread.run.requires_action - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. required: - - event - - data - description: >- - Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a - `requires_action` status. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object + - name + - arguments + required: + - id + - type + - function + + ChatCompletionMessageToolCallChunk: + type: object + properties: + index: + type: integer + id: + type: string + description: The ID of the tool call. + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object properties: - event: + name: type: string - enum: - - thread.run.completed - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) is completed. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object - properties: - event: + description: The name of the function to call. + arguments: type: string - enum: - - thread.run.incomplete - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: >- - Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) ends with status - `incomplete`. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + required: + - index + + # Note, this isn't referenced anywhere, but is kept as a convenience to record all possible roles in one place. + ChatCompletionRole: + type: string + description: The role of the author of a message + enum: + - system + - user + - assistant + - tool + - function + + ChatCompletionStreamOptions: + description: | + Options for streaming response. Only set this when you set `stream: true`. + type: object + nullable: true + default: null + properties: + include_usage: + type: boolean + description: | + If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + + ChatCompletionResponseMessage: + type: object + description: A chat completion message generated by the model. + properties: + content: + type: string + description: The contents of the message. + nullable: true + refusal: + type: string + description: The refusal message generated by the model. + nullable: true + tool_calls: + $ref: "#/components/schemas/ChatCompletionMessageToolCalls" + role: + type: string + enum: ["assistant"] + description: The role of the author of this message. + function_call: + type: object + deprecated: true + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." properties: - event: + arguments: type: string - enum: - - thread.run.failed - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) fails. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object - properties: - event: + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: type: string - enum: - - thread.run.cancelling - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' + description: The name of the function to call. required: - - event - - data - description: >- - Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a - `cancelling` status. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object + - name + - arguments + required: + - role + - content + # - refusal + + ChatCompletionStreamResponseDelta: + type: object + description: A chat completion delta generated by streamed model responses. + properties: + content: + type: string + description: The contents of the chunk message. + nullable: true + function_call: + deprecated: true + type: object + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." properties: - event: + arguments: type: string - enum: - - thread.run.cancelled - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) is cancelled. - x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - - type: object - properties: - event: + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: type: string + description: The name of the function to call. + tool_calls: + type: array + items: + $ref: "#/components/schemas/ChatCompletionMessageToolCallChunk" + role: + type: string + enum: ["system", "user", "assistant", "tool"] + description: The role of the author of this message. + refusal: + type: string + description: The refusal message generated by the model. + nullable: true + + CreateChatCompletionRequest: + type: object + properties: + messages: + description: A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + type: array + minItems: 1 + items: + $ref: "#/components/schemas/ChatCompletionRequestMessage" + model: + description: ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + example: "gpt-4o" + anyOf: + - type: string + - type: string enum: - - thread.run.expired - x-stainless-const: true - data: - $ref: '#/components/schemas/RunObject' - required: - - event - - data - description: Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) expires. + [ + "gpt-4o", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "chatgpt-4o-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: *completions_frequency_penalty_description + logit_bias: + type: object + x-oaiTypeLabel: map + default: null + nullable: true + additionalProperties: + type: integer + description: | + Modify the likelihood of specified tokens appearing in the completion. + + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + logprobs: + description: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. + type: boolean + default: false + nullable: true + top_logprobs: + description: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + type: integer + minimum: 0 + maximum: 20 + nullable: true + max_tokens: + description: | + The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + type: integer + nullable: true + n: + type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 + nullable: true + description: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: *completions_presence_penalty_description + response_format: + description: | + An object specifying the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4o mini](/docs/models/gpt-4o-mini), [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + oneOf: + - $ref: "#/components/schemas/ResponseFormatText" + - $ref: "#/components/schemas/ResponseFormatJsonObject" + - $ref: "#/components/schemas/ResponseFormatJsonSchema" + x-oaiExpandable: true + seed: + type: integer + minimum: -9223372036854775808 + maximum: 9223372036854775807 + nullable: true + description: | + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. x-oaiMeta: - dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' - discriminator: - propertyName: event - RunToolCallObject: + beta: true + service_tier: + description: | + Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: + - If set to 'auto', the system will utilize scale tier credits until they are exhausted. + - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` utilized. + type: string + enum: ["auto", "default"] + nullable: true + default: null + stop: + description: | + Up to 4 sequences where the API will stop generating further tokens. + default: null + oneOf: + - type: string + nullable: true + - type: array + minItems: 1 + maxItems: 4 + items: + type: string + stream: + description: > + If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + type: boolean + nullable: true + default: false + stream_options: + $ref: "#/components/schemas/ChatCompletionStreamOptions" + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *completions_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *completions_top_p_description + tools: + type: array + description: > + A list of tools the model may call. Currently, only functions are supported as a tool. + Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. + items: + $ref: "#/components/schemas/ChatCompletionTool" + tool_choice: + $ref: "#/components/schemas/ChatCompletionToolChoiceOption" + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + user: *end_user_param_configuration + function_call: + deprecated: true + description: | + Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. + `none` means the model will not call a function and instead generates a message. + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + + `none` is the default when no functions are present. `auto` is the default if functions are present. + oneOf: + - type: string + description: > + `none` means the model will not call a function and instead generates a message. + `auto` means the model can pick between generating a message or calling a function. + enum: [none, auto] + - $ref: "#/components/schemas/ChatCompletionFunctionCallOption" + x-oaiExpandable: true + functions: + deprecated: true + description: | + Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. + type: array + minItems: 1 + maxItems: 128 + items: + $ref: "#/components/schemas/ChatCompletionFunctions" + + required: + - model + - messages + + CreateChatCompletionResponse: type: object - description: Tool call objects + description: Represents a chat completion response returned by model, based on the provided input. properties: id: type: string - description: >- - The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the - [Submit tool outputs to - run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint. - type: + description: A unique identifier for the chat completion. + choices: + type: array + description: A list of chat completion choices. Can be more than one if `n` is greater than 1. + items: + type: object + required: + - finish_reason + - index + - message + # - logprobs + properties: + finish_reason: + type: string + description: &chat_completion_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + `content_filter` if content was omitted due to a flag from our content filters, + `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + enum: + [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call", + ] + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: "#/components/schemas/ChatCompletionResponseMessage" + logprobs: &chat_completion_response_logprobs + description: Log probability information for the choice. + type: object + nullable: true + properties: + content: + description: A list of message content tokens with log probability information. + type: array + items: + $ref: "#/components/schemas/ChatCompletionTokenLogprob" + nullable: true + refusal: + description: A list of message refusal tokens with log probability information. + type: array + items: + $ref: "#/components/schemas/ChatCompletionTokenLogprob" + nullable: true + required: + - content + # - refusal + + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. + model: type: string - description: The type of tool call the output is required for. For now, this is always `function`. - enum: - - function - x-stainless-const: true - function: - type: object - description: The function definition. - properties: - name: - type: string - description: The name of the function. - arguments: - type: string - description: The arguments that the model expects you to pass to the function. - required: - - name - - arguments + description: The model used for the chat completion. + service_tier: + description: The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. + type: string + enum: ["scale", "default"] + example: "scale" + nullable: true + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion`. + enum: [chat.completion] + usage: + $ref: "#/components/schemas/CompletionUsage" required: + - choices + - created - id - - type - - function - Screenshot: + - model + - object + x-oaiMeta: + name: The chat completion object + group: chat + example: *chat_completion_example + + CreateChatCompletionFunctionResponse: type: object - title: Screenshot - description: | - A screenshot action. + description: Represents a chat completion response returned by model, based on the provided input. properties: - type: + id: + type: string + description: A unique identifier for the chat completion. + choices: + type: array + description: A list of chat completion choices. Can be more than one if `n` is greater than 1. + items: + type: object + required: + - finish_reason + - index + - message + - logprobs + properties: + finish_reason: + type: string + description: + &chat_completion_function_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, or `function_call` if the model called a function. + enum: ["stop", "length", "function_call", "content_filter"] + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: "#/components/schemas/ChatCompletionResponseMessage" + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. + model: + type: string + description: The model used for the chat completion. + system_fingerprint: type: string - enum: - - screenshot - default: screenshot description: | - Specifies the event type. For a screenshot action, this property is - always set to `screenshot`. - x-stainless-const: true + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion`. + enum: [chat.completion] + usage: + $ref: "#/components/schemas/CompletionUsage" required: - - type - Scroll: + - choices + - created + - id + - model + - object + x-oaiMeta: + name: The chat completion object + group: chat + example: *chat_completion_function_example + + ChatCompletionTokenLogprob: type: object - title: Scroll - description: | - A scroll action. properties: - type: + token: &chat_completion_response_logprobs_token + description: The token. type: string - enum: - - scroll - default: scroll - description: | - Specifies the event type. For a scroll action, this property is - always set to `scroll`. - x-stainless-const: true - x: - type: integer - description: | - The x-coordinate where the scroll occurred. - 'y': - type: integer - description: | - The y-coordinate where the scroll occurred. - scroll_x: - type: integer - description: | - The horizontal scroll distance. - scroll_y: - type: integer - description: | - The vertical scroll distance. + logprob: &chat_completion_response_logprobs_token_logprob + description: The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. + type: number + bytes: &chat_completion_response_logprobs_bytes + description: A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. + type: array + items: + type: integer + nullable: true + top_logprobs: + description: List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. + type: array + items: + type: object + properties: + token: *chat_completion_response_logprobs_token + logprob: *chat_completion_response_logprobs_token_logprob + bytes: *chat_completion_response_logprobs_bytes + required: + - token + - logprob + - bytes required: - - type - - x - - 'y' - - scroll_x - - scroll_y - ServiceTier: - anyOf: - - type: string - description: | - Specifies the processing type used for serving the request. - - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'. - - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model. - - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier. - - When not set, the default behavior is 'auto'. + - token + - logprob + - bytes + - top_logprobs - When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter. - enum: - - auto - - default - - flex - - scale - - priority - default: auto - - type: 'null' - SpeechAudioDeltaEvent: + ListPaginatedFineTuningJobsResponse: type: object - description: Emitted for each chunk of audio data generated during speech synthesis. properties: - type: - type: string - description: | - The type of the event. Always `speech.audio.delta`. - enum: - - speech.audio.delta - x-stainless-const: true - audio: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJob" + has_more: + type: boolean + object: type: string - description: | - A chunk of Base64-encoded audio data. + enum: [list] required: - - type - - audio - x-oaiMeta: - name: Stream Event (speech.audio.delta) - group: speech - example: | - { - "type": "speech.audio.delta", - "audio": "base64-encoded-audio-data" - } - SpeechAudioDoneEvent: + - object + - data + - has_more + + CreateChatCompletionStreamResponse: type: object - description: Emitted when the speech synthesis is complete and all audio has been streamed. + description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. properties: - type: + id: + type: string + description: A unique identifier for the chat completion. Each chunk has the same ID. + choices: + type: array + description: | + A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the + last chunk if you set `stream_options: {"include_usage": true}`. + items: + type: object + required: + - delta + - finish_reason + - index + properties: + delta: + $ref: "#/components/schemas/ChatCompletionStreamResponseDelta" + logprobs: *chat_completion_response_logprobs + finish_reason: + type: string + description: *chat_completion_finish_reason_description + enum: + [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call", + ] + nullable: true + index: + type: integer + description: The index of the choice in the list of choices. + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp. + model: + type: string + description: The model to generate the completion. + service_tier: + description: The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. + type: string + enum: ["scale", "default"] + example: "scale" + nullable: true + system_fingerprint: type: string description: | - The type of the event. Always `speech.audio.done`. - enum: - - speech.audio.done - x-stainless-const: true + This fingerprint represents the backend configuration that the model runs with. + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion.chunk`. + enum: [chat.completion.chunk] usage: type: object description: | - Token usage statistics for the request. + An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request. + When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request. properties: - input_tokens: + completion_tokens: type: integer - description: Number of input tokens in the prompt. - output_tokens: + description: Number of tokens in the generated completion. + prompt_tokens: type: integer - description: Number of output tokens generated. + description: Number of tokens in the prompt. total_tokens: type: integer - description: Total number of tokens used (input + output). + description: Total number of tokens used in the request (prompt + completion). required: - - input_tokens - - output_tokens + - prompt_tokens + - completion_tokens - total_tokens required: - - type - - usage + - choices + - created + - id + - model + - object x-oaiMeta: - name: Stream Event (speech.audio.done) - group: speech - example: | - { - "type": "speech.audio.done", - "usage": { - "input_tokens": 14, - "output_tokens": 101, - "total_tokens": 115 - } - } - StaticChunkingStrategy: + name: The chat completion chunk object + group: chat + example: *chat_completion_chunk_example + + CreateChatCompletionImageResponse: type: object - additionalProperties: false - properties: - max_chunk_size_tokens: - type: integer - minimum: 100 - maximum: 4096 - description: >- - The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` - and the maximum value is `4096`. - chunk_overlap_tokens: - type: integer - description: | - The number of tokens that overlap between chunks. The default value is `400`. + description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. + x-oaiMeta: + name: The chat completion chunk object + group: chat + example: *chat_completion_image_example - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - required: - - max_chunk_size_tokens - - chunk_overlap_tokens - StaticChunkingStrategyRequestParam: + CreateImageRequest: type: object - title: Static Chunking Strategy - description: Customize your own chunking strategy by setting chunk size and chunk overlap. - additionalProperties: false properties: - type: + prompt: + description: A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. type: string - description: Always `static`. - enum: - - static - x-stainless-const: true - static: - $ref: '#/components/schemas/StaticChunkingStrategy' - required: - - type - - static - StaticChunkingStrategyResponseParam: - type: object - title: Static Chunking Strategy - additionalProperties: false - properties: - type: + example: "A cute baby sea otter" + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2", "dall-e-3"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-3" + nullable: true + description: The model to use for image generation. + n: &images_n + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. + quality: type: string - description: Always `static`. - enum: - - static - x-stainless-const: true - static: - $ref: '#/components/schemas/StaticChunkingStrategy' + enum: ["standard", "hd"] + default: "standard" + example: "standard" + description: The quality of the image that will be generated. `hd` creates images with finer details and greater consistency across the image. This param is only supported for `dall-e-3`. + response_format: &images_response_format + type: string + enum: ["url", "b64_json"] + default: "url" + example: "url" + nullable: true + description: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. + size: &images_size + type: string + enum: ["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"] + default: "1024x1024" + example: "1024x1024" + nullable: true + description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models. + style: + type: string + enum: ["vivid", "natural"] + default: "vivid" + example: "vivid" + nullable: true + description: The style of the generated images. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for `dall-e-3`. + user: *end_user_param_configuration required: - - type - - static - StopConfiguration: - description: | - Not supported with latest reasoning models `o3` and `o4-mini`. - - Up to 4 sequences where the API will stop generating further tokens. The - returned text will not contain the stop sequence. - nullable: true - anyOf: - - type: string - default: <|endoftext|> - example: |+ + - prompt - nullable: true - - type: array - minItems: 1 - maxItems: 4 - items: - type: string - example: '["\n"]' - SubmitToolOutputsRunRequest: - type: object - additionalProperties: false + ImagesResponse: properties: - tool_outputs: - description: A list of tools for which the outputs are being submitted. + created: + type: integer + data: type: array items: - type: object - properties: - tool_call_id: - type: string - description: >- - The ID of the tool call in the `required_action` object within the run object the output is - being submitted for. - output: - type: string - description: The output of the tool call to be submitted to continue the run. - stream: - anyOf: - - type: boolean - description: > - If `true`, returns a stream of events that happen during the Run as server-sent events, - terminating when the Run enters a terminal state with a `data: [DONE]` message. - - type: 'null' + $ref: "#/components/schemas/Image" required: - - tool_outputs - TextResponseFormatConfiguration: - description: | - An object specifying the format that the model must output. - - Configuring `{ "type": "json_schema" }` enables Structured Outputs, - which ensures the model will match your supplied JSON schema. Learn more in the - [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - - The default format is `{ "type": "text" }` with no additional options. - - **Not recommended for gpt-4o and newer models:** + - created + - data - Setting to `{ "type": "json_object" }` enables the older JSON mode, which - ensures the message the model generates is valid JSON. Using `json_schema` - is preferred for models that support it. - anyOf: - - $ref: '#/components/schemas/ResponseFormatText' - - $ref: '#/components/schemas/TextResponseFormatJsonSchema' - - $ref: '#/components/schemas/ResponseFormatJsonObject' - discriminator: - propertyName: type - TextResponseFormatJsonSchema: + Image: type: object - title: JSON schema - description: | - JSON Schema response format. Used to generate structured JSON responses. - Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). + description: Represents the url or the content of an image generated by the OpenAI API. properties: - type: - type: string - description: The type of response format being defined. Always `json_schema`. - enum: - - json_schema - x-stainless-const: true - description: - type: string - description: | - A description of what the response format is for, used by the model to - determine how to respond in the format. - name: + b64_json: type: string - description: | - The name of the response format. Must be a-z, A-Z, 0-9, or contain - underscores and dashes, with a maximum length of 64. - schema: - $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' - strict: - anyOf: - - type: boolean - default: false - description: | - Whether to enable strict schema adherence when generating the output. - If set to true, the model will always follow the exact schema defined - in the `schema` field. Only a subset of JSON Schema is supported when - `strict` is `true`. To learn more, read the [Structured Outputs - guide](https://platform.openai.com/docs/guides/structured-outputs). - - type: 'null' - required: - - type - - schema - - name - ThreadObject: - type: object - title: Thread - description: Represents a thread that contains [messages](https://platform.openai.com/docs/api-reference/messages). - properties: - id: - description: The identifier, which can be referenced in API endpoints. + description: The base64-encoded JSON of the generated image, if `response_format` is `b64_json`. + url: type: string - object: - description: The object type, which is always `thread`. + description: The URL of the generated image, if `response_format` is `url` (default). + revised_prompt: type: string - enum: - - thread - x-stainless-const: true - created_at: - description: The Unix timestamp (in seconds) for when the thread was created. - type: integer - tool_resources: - anyOf: - - type: object - description: > - A set of resources that are made available to the assistant's tools in this thread. The - resources are specific to the type of tool. For example, the `code_interpreter` tool requires - a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - available to the `code_interpreter` tool. There can be a maximum of 20 files - associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached - to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: string - - type: 'null' - metadata: - $ref: '#/components/schemas/Metadata' - required: - - id - - object - - created_at - - tool_resources - - metadata + description: The prompt that was used to generate the image, if there was any revision to the prompt. x-oaiMeta: - name: The thread object - beta: true + name: The image object example: | { - "id": "thread_abc123", - "object": "thread", - "created_at": 1698107661, - "metadata": {} + "url": "...", + "revised_prompt": "..." } - ThreadStreamEvent: - anyOf: - - type: object - properties: - enabled: - type: boolean - description: Whether to enable input audio transcription. - event: - type: string - enum: - - thread.created - x-stainless-const: true - data: - $ref: '#/components/schemas/ThreadObject' - required: - - event - - data - description: >- - Occurs when a new [thread](https://platform.openai.com/docs/api-reference/threads/object) is - created. - x-oaiMeta: - dataDescription: '`data` is a [thread](/docs/api-reference/threads/object)' - discriminator: - propertyName: event - ToggleCertificatesRequest: - type: object - properties: - certificate_ids: - type: array - items: - type: string - example: cert_abc - minItems: 1 - maxItems: 10 - required: - - certificate_ids - Tool: - description: | - A tool that can be used to generate a response. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/FunctionTool' - - $ref: '#/components/schemas/FileSearchTool' - - $ref: '#/components/schemas/ComputerUsePreviewTool' - - $ref: '#/components/schemas/WebSearchTool' - - $ref: '#/components/schemas/MCPTool' - - $ref: '#/components/schemas/CodeInterpreterTool' - - $ref: '#/components/schemas/ImageGenTool' - - $ref: '#/components/schemas/LocalShellToolParam' - - $ref: '#/components/schemas/FunctionShellToolParam' - - $ref: '#/components/schemas/CustomToolParam' - - $ref: '#/components/schemas/WebSearchPreviewTool' - - $ref: '#/components/schemas/ApplyPatchToolParam' - ToolChoiceAllowed: - type: object - title: Allowed tools - description: | - Constrains the tools available to the model to a pre-defined set. - properties: - type: - type: string - enum: - - allowed_tools - description: Allowed tool configuration type. Always `allowed_tools`. - x-stainless-const: true - mode: - type: string - enum: - - auto - - required - description: | - Constrains the tools available to the model to a pre-defined set. - - `auto` allows the model to pick from among the allowed tools and generate a - message. - - `required` requires the model to call one or more of the allowed tools. - tools: - type: array - description: | - A list of tool definitions that the model should be allowed to call. - For the Responses API, the list of tool definitions might look like: - ```json - [ - { "type": "function", "name": "get_weather" }, - { "type": "mcp", "server_label": "deepwiki" }, - { "type": "image_generation" } - ] - ``` - items: - type: object - description: | - A tool definition that the model should be allowed to call. - additionalProperties: true - x-oaiExpandable: false - required: - - type - - mode - - tools - ToolChoiceCustom: + CreateImageEditRequest: type: object - title: Custom tool - description: | - Use this option to force the model to call a specific custom tool. properties: - type: + image: + description: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. type: string - enum: - - custom - description: For custom tool calling, the type is always `custom`. - x-stainless-const: true - name: + format: binary + prompt: + description: A text description of the desired image(s). The maximum length is 1000 characters. type: string - description: The name of the custom tool to call. - required: - - type - - name - ToolChoiceFunction: - type: object - title: Function tool - description: | - Use this option to force the model to call a specific function. - properties: - type: + example: "A cute baby sea otter wearing a beret" + mask: + description: An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. type: string - enum: - - function - description: For function calling, the type is always `function`. - x-stainless-const: true - name: + format: binary + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-2" + nullable: true + description: The model to use for image generation. Only `dall-e-2` is supported at this time. + n: + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. + size: &dalle2_images_size type: string - description: The name of the function to call. + enum: ["256x256", "512x512", "1024x1024"] + default: "1024x1024" + example: "1024x1024" + nullable: true + description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. + response_format: *images_response_format + user: *end_user_param_configuration required: - - type - - name - ToolChoiceMCP: + - prompt + - image + + CreateImageVariationRequest: type: object - title: MCP tool - description: | - Use this option to force the model to call a specific tool on a remote MCP server. properties: - type: - type: string - enum: - - mcp - description: For MCP tools, the type is always `mcp`. - x-stainless-const: true - server_label: + image: + description: The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. type: string - description: | - The label of the MCP server to use. - name: + format: binary + model: anyOf: - type: string - description: | - The name of the tool to call on the server. - - type: 'null' + - type: string + enum: ["dall-e-2"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-2" + nullable: true + description: The model to use for image generation. Only `dall-e-2` is supported at this time. + n: *images_n + response_format: *images_response_format + size: *dalle2_images_size + user: *end_user_param_configuration required: - - type - - server_label - ToolChoiceOptions: - type: string - title: Tool choice mode - description: | - Controls which (if any) tool is called by the model. - - `none` means the model will not call any tool and instead generates a message. - - `auto` means the model can pick between generating a message or calling one or - more tools. + - image - `required` means the model must call one or more tools. - enum: - - none - - auto - - required - ToolChoiceParam: - description: | - How the model should select which tool (or tools) to use when generating - a response. See the `tools` parameter to see how to specify which tools - the model can call. - anyOf: - - $ref: '#/components/schemas/ToolChoiceOptions' - - $ref: '#/components/schemas/ToolChoiceAllowed' - - $ref: '#/components/schemas/ToolChoiceTypes' - - $ref: '#/components/schemas/ToolChoiceFunction' - - $ref: '#/components/schemas/ToolChoiceMCP' - - $ref: '#/components/schemas/ToolChoiceCustom' - - $ref: '#/components/schemas/SpecificApplyPatchParam' - - $ref: '#/components/schemas/SpecificFunctionShellParam' - discriminator: - propertyName: type - ToolChoiceTypes: - type: object - title: Hosted tool - description: | - Indicates that the model should use a built-in tool to generate a response. - [Learn more about built-in tools](https://platform.openai.com/docs/guides/tools). - properties: - type: - type: string - description: | - The type of hosted tool the model should to use. Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - Allowed values are: - - `file_search` - - `web_search_preview` - - `computer_use_preview` - - `code_interpreter` - - `image_generation` - enum: - - file_search - - web_search_preview - - computer_use_preview - - web_search_preview_2025_03_11 - - image_generation - - code_interpreter - required: - - type - ToolsArray: - type: array - description: | - 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. - - We support the following categories of tools: - - **Built-in tools**: Tools that are provided by OpenAI that extend the - model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) - or [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 SharePoint. 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 - [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use - custom tools to call your own code. - items: - $ref: '#/components/schemas/Tool' - TranscriptTextDeltaEvent: + CreateModerationRequest: type: object - description: >- - Emitted when there is an additional text delta. This is also the first event emitted when the - transcription starts. Only emitted when you [create a - transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the - `Stream` parameter set to `true`. properties: - type: - type: string - description: | - The type of the event. Always `transcript.text.delta`. - enum: - - transcript.text.delta - x-stainless-const: true - delta: - type: string - description: | - The text delta that was additionally transcribed. - logprobs: - type: array - description: > - The log probabilities of the delta. Only included if you [create a - transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the - `include[]` parameter set to `logprobs`. - items: - type: object - properties: - token: + input: + description: The input text to classify + oneOf: + - type: string + default: "" + example: "I want to kill them." + - type: array + items: type: string - description: | - The token that was used to generate the log probability. - logprob: - type: number - description: | - The log probability of the token. - bytes: - type: array - items: - type: integer - description: | - The bytes that were used to generate the log probability. - segment_id: - type: string - description: > - Identifier of the diarized segment that this delta belongs to. Only present when using - `gpt-4o-transcribe-diarize`. + default: "" + example: "I want to kill them." + model: + description: | + Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`. + + The default is `text-moderation-latest` which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. + nullable: false + default: "text-moderation-latest" + example: "text-moderation-stable" + anyOf: + - type: string + - type: string + enum: ["text-moderation-latest", "text-moderation-stable"] + x-oaiTypeLabel: string required: - - type - - delta - x-oaiMeta: - name: Stream Event (transcript.text.delta) - group: transcript - example: | - { - "type": "transcript.text.delta", - "delta": " wonderful" - } - TranscriptTextDoneEvent: + - input + + CreateModerationResponse: type: object - description: >- - Emitted when the transcription is complete. Contains the complete transcription text. Only emitted - when you [create a - transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the - `Stream` parameter set to `true`. + description: Represents if a given text input is potentially harmful. properties: - type: + id: type: string - description: | - The type of the event. Always `transcript.text.done`. - enum: - - transcript.text.done - x-stainless-const: true - text: + description: The unique identifier for the moderation request. + model: type: string - description: | - The text that was transcribed. - logprobs: + description: The model used to generate the moderation results. + results: type: array - description: > - The log probabilities of the individual tokens in the transcription. Only included if you [create - a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with - the `include[]` parameter set to `logprobs`. + description: A list of moderation objects. items: type: object properties: - token: - type: string - description: | - The token that was used to generate the log probability. - logprob: - type: number - description: | - The log probability of the token. - bytes: - type: array - items: - type: integer - description: | - The bytes that were used to generate the log probability. - usage: - $ref: '#/components/schemas/TranscriptTextUsageTokens' - required: - - type - - text - x-oaiMeta: - name: Stream Event (transcript.text.done) - group: transcript - example: | - { - "type": "transcript.text.done", - "text": "I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.", - "usage": { - "type": "tokens", - "input_tokens": 14, - "input_token_details": { - "text_tokens": 10, - "audio_tokens": 4 - }, - "output_tokens": 31, - "total_tokens": 45 - } - } - TranscriptTextSegmentEvent: - type: object - description: > - Emitted when a diarized transcription returns a completed segment with speaker information. Only - emitted when you [create a - transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with - `stream` set to `true` and `response_format` set to `diarized_json`. - properties: - type: - type: string - description: The type of the event. Always `transcript.text.segment`. - enum: - - transcript.text.segment - x-stainless-const: true - id: - type: string - description: Unique identifier for the segment. - start: - type: number - format: float - description: Start timestamp of the segment in seconds. - end: - type: number - format: float - description: End timestamp of the segment in seconds. - text: - type: string - description: Transcript text for this segment. - speaker: - type: string - description: Speaker label for this segment. + flagged: + type: boolean + description: Whether any of the below categories are flagged. + categories: + type: object + description: A list of the categories, and whether they are flagged or not. + properties: + hate: + type: boolean + description: Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment. + hate/threatening: + type: boolean + description: Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. + harassment: + type: boolean + description: Content that expresses, incites, or promotes harassing language towards any target. + harassment/threatening: + type: boolean + description: Harassment content that also includes violence or serious harm towards any target. + self-harm: + type: boolean + description: Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. + self-harm/intent: + type: boolean + description: Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. + self-harm/instructions: + type: boolean + description: Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. + sexual: + type: boolean + description: Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness). + sexual/minors: + type: boolean + description: Sexual content that includes an individual who is under 18 years old. + violence: + type: boolean + description: Content that depicts death, violence, or physical injury. + violence/graphic: + type: boolean + description: Content that depicts death, violence, or physical injury in graphic detail. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + category_scores: + type: object + description: A list of the categories along with their scores as predicted by model. + properties: + hate: + type: number + description: The score for the category 'hate'. + hate/threatening: + type: number + description: The score for the category 'hate/threatening'. + harassment: + type: number + description: The score for the category 'harassment'. + harassment/threatening: + type: number + description: The score for the category 'harassment/threatening'. + self-harm: + type: number + description: The score for the category 'self-harm'. + self-harm/intent: + type: number + description: The score for the category 'self-harm/intent'. + self-harm/instructions: + type: number + description: The score for the category 'self-harm/instructions'. + sexual: + type: number + description: The score for the category 'sexual'. + sexual/minors: + type: number + description: The score for the category 'sexual/minors'. + violence: + type: number + description: The score for the category 'violence'. + violence/graphic: + type: number + description: The score for the category 'violence/graphic'. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + required: + - flagged + - categories + - category_scores required: - - type - id - - start - - end - - text - - speaker - x-oaiMeta: - name: Stream Event (transcript.text.segment) - group: transcript - example: | - { - "type": "transcript.text.segment", - "id": "seg_002", - "start": 5.2, - "end": 12.8, - "text": "Hi, I need help with diarization.", - "speaker": "A" - } - TranscriptTextUsageDuration: - type: object - title: TranscriptTextUsageDuration - description: Usage statistics for models billed by audio input duration. - properties: - type: - type: string - enum: - - duration - description: The type of the usage object. Always `duration` for this variant. - x-stainless-const: true - seconds: - type: number - description: Duration of the input audio in seconds. - required: - - type - - seconds - TranscriptTextUsageTokens: + - model + - results + x-oaiMeta: + name: The moderation object + example: *moderation_example + + ListFilesResponse: type: object - title: TranscriptTextUsageTokens - description: Usage statistics for models billed by token usage. properties: - type: + data: + type: array + items: + $ref: "#/components/schemas/OpenAIFile" + object: type: string - enum: - - tokens - description: The type of the usage object. Always `tokens` for this variant. - x-stainless-const: true - input_tokens: - type: integer - description: Number of input tokens billed for this request. - input_token_details: - type: object - description: Details about the input tokens billed for this request. - properties: - text_tokens: - type: integer - description: Number of text tokens billed for this request. - audio_tokens: - type: integer - description: Number of audio tokens billed for this request. - output_tokens: - type: integer - description: Number of output tokens generated. - total_tokens: - type: integer - description: Total number of tokens used (input + output). + enum: [list] required: - - type - - input_tokens - - output_tokens - - total_tokens - TranscriptionChunkingStrategy: - anyOf: - - description: >- - Controls how the audio is cut into chunks. When set to `"auto"`, the server first normalizes - loudness and then uses voice activity detection (VAD) to choose boundaries. `server_vad` object - can be provided to tweak VAD detection parameters manually. If unset, the audio is transcribed as - a single block. Required when using `gpt-4o-transcribe-diarize` for inputs longer than 30 - seconds. - anyOf: - - type: string - enum: - - auto - default: auto - description: | - Automatically set chunking parameters based on the audio. Must be set to `"auto"`. - x-stainless-const: true - - $ref: '#/components/schemas/VadConfig' - x-oaiTypeLabel: string - - type: 'null' - TranscriptionDiarizedSegment: + - object + - data + + CreateFileRequest: type: object - description: A segment of diarized transcript text with speaker metadata. + additionalProperties: false properties: - type: - type: string + file: description: | - The type of the segment. Always `transcript.text.segment`. - enum: - - transcript.text.segment - x-stainless-const: true - id: - type: string - description: Unique identifier for the segment. - start: - type: number - format: float - description: Start timestamp of the segment in seconds. - end: - type: number - format: float - description: End timestamp of the segment in seconds. - text: + The File object (not file name) to be uploaded. type: string - description: Transcript text for this segment. - speaker: + format: binary + purpose: + description: | + The intended purpose of the uploaded file. + + Use "assistants" for [Assistants](/docs/api-reference/assistants) and [Message](/docs/api-reference/messages) files, "vision" for Assistants image file inputs, "batch" for [Batch API](/docs/guides/batch), and "fine-tune" for [Fine-tuning](/docs/api-reference/fine-tuning). type: string - description: > - Speaker label for this segment. When known speakers are provided, the label matches - `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, - `B`, ...). + enum: ["assistants", "batch", "fine-tune", "vision"] required: - - type - - id - - start - - end - - text - - speaker - TranscriptionInclude: - type: string - enum: - - logprobs - TranscriptionSegment: + - file + - purpose + + DeleteFileResponse: type: object properties: id: - type: integer - description: Unique identifier of the segment. - seek: - type: integer - description: Seek offset of the segment. - start: - type: number - format: float - description: Start time of the segment in seconds. - end: - type: number - format: float - description: End time of the segment in seconds. - text: - type: string - description: Text content of the segment. - tokens: - type: array - items: - type: integer - description: Array of token IDs for the text content. - temperature: - type: number - format: float - description: Temperature parameter used for generating the segment. - avg_logprob: - type: number - format: float - description: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. - compression_ratio: - type: number - format: float - description: >- - Compression ratio of the segment. If the value is greater than 2.4, consider the compression - failed. - no_speech_prob: - type: number - format: float - description: >- - Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is - below -1, consider this segment silent. - required: - - id - - seek - - start - - end - - text - - tokens - - temperature - - avg_logprob - - compression_ratio - - no_speech_prob - TranscriptionWord: - type: object - properties: - word: type: string - description: The text content of the word. - start: - type: number - format: float - description: Start time of the word in seconds. - end: - type: number - format: float - description: End time of the word in seconds. - required: - - word - - start - - end - TruncationObject: - type: object - title: Thread Truncation Controls - description: >- - Controls for how a thread will be truncated prior to the run. Use this to control the initial context - window of the run. - properties: - type: + object: type: string - description: >- - The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, - the thread will be truncated to the n most recent messages in the thread. When set to `auto`, - messages in the middle of the thread will be dropped to fit the context length of the model, - `max_prompt_tokens`. - enum: - - auto - - last_messages - last_messages: - anyOf: - - type: integer - description: The number of most recent messages from the thread when constructing the context for the run. - minimum: 1 - - type: 'null' + enum: [file] + deleted: + type: boolean required: - - type - Type: + - id + - object + - deleted + + CreateUploadRequest: type: object - title: Type - description: | - An action to type in text. + additionalProperties: false properties: - type: + filename: + description: | + The name of the file to upload. type: string - enum: - - type - default: type + purpose: description: | - Specifies the event type. For a type action, this property is - always set to `type`. - x-stainless-const: true - text: + The intended purpose of the uploaded file. + + See the [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose). type: string + enum: ["assistants", "batch", "fine-tune", "vision"] + bytes: + description: | + The number of bytes in the file you are uploading. + type: integer + mime_type: description: | - The text to type. + The MIME type of the file. + + This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + type: string required: - - type - - text - UpdateGroupBody: + - filename + - purpose + - bytes + - mime_type + + AddUploadPartRequest: type: object - description: Request payload for updating the details of an existing group. + additionalProperties: false properties: - name: + data: + description: | + The chunk of bytes for this Part. type: string - description: New display name for the group. - minLength: 1 - maxLength: 255 + format: binary required: - - name - x-oaiMeta: - example: | - { - "name": "Escalations" - } - UpdateVectorStoreFileAttributesRequest: + - data + + CompleteUploadRequest: type: object additionalProperties: false properties: - attributes: - $ref: '#/components/schemas/VectorStoreFileAttributes' + part_ids: + type: array + description: | + The ordered list of Part IDs. + items: + type: string + md5: + description: | + The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. + type: string required: - - attributes - x-oaiMeta: - name: Update vector store file attributes request - UpdateVectorStoreRequest: + - part_ids + + CancelUploadRequest: type: object additionalProperties: false - properties: - name: - description: The name of the vector store. - type: string - nullable: true - expires_after: - allOf: - - $ref: '#/components/schemas/VectorStoreExpirationAfter' - - nullable: true - metadata: - $ref: '#/components/schemas/Metadata' - Upload: + + CreateFineTuningJobRequest: type: object - title: Upload - description: | - The Upload object can accept byte chunks in the form of Parts. properties: - id: - type: string - description: The Upload unique identifier, which can be referenced in API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the Upload was created. - filename: + model: + description: | + The name of the model to fine-tune. You can select one of the + [supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned). + example: "gpt-4o-mini" + anyOf: + - type: string + - type: string + enum: + ["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"] + x-oaiTypeLabel: string + training_file: + description: | + The ID of an uploaded file that contains training data. + + See [upload file](/docs/api-reference/files/create) for how to upload a file. + + Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. + + The contents of the file should differ depending on if the model uses the [chat](/docs/api-reference/fine-tuning/chat-input) or [completions](/docs/api-reference/fine-tuning/completions-input) format. + + See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. type: string - description: The name of the file to be uploaded. - bytes: - type: integer - description: The intended number of bytes to be uploaded. - purpose: + example: "file-abc123" + hyperparameters: + type: object + description: The hyperparameters used for the fine-tuning job. + properties: + batch_size: + description: | + Number of examples in each batch. A larger batch size means that model parameters + are updated less frequently, but with lower variance. + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: | + Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + overfitting. + oneOf: + - type: string + enum: [auto] + - type: number + minimum: 0 + exclusiveMinimum: true + default: auto + n_epochs: + description: | + The number of epochs to train the model for. An epoch refers to one full cycle + through the training dataset. + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 50 + default: auto + suffix: + description: | + A string of up to 18 characters that will be added to your fine-tuned model name. + + For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. type: string - description: >- - The intended purpose of the file. [Please refer - here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for - acceptable values. - status: + minLength: 1 + maxLength: 40 + default: null + nullable: true + validation_file: + description: | + The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation + metrics periodically during fine-tuning. These metrics can be viewed in + the fine-tuning results file. + The same data should not be present in both train and validation files. + + Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`. + + See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. type: string - description: The status of the Upload. - enum: - - pending - - completed - - cancelled - - expired - expires_at: + nullable: true + example: "file-abc123" + integrations: + type: array + description: A list of integrations to enable for your fine-tuning job. + nullable: true + items: + type: object + required: + - type + - wandb + properties: + type: + description: | + The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported. + oneOf: + - type: string + enum: [wandb] + wandb: + type: object + description: | + The settings for your integration with Weights and Biases. This payload specifies the project that + metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags + to your run, and set a default entity (team, username, etc) to be associated with your run. + required: + - project + properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: "my-wandb-project" + name: + description: | + A display name to set for the run. If not set, we will use the Job ID as the name. + nullable: true + type: string + entity: + description: | + The entity to use for the run. This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered WandB API key is used. + nullable: true + type: string + tags: + description: | + A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some + default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: "custom-tag" + + seed: + description: | + The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. + If a seed is not specified, one will be generated for you. type: integer - description: The Unix timestamp (in seconds) for when the Upload will expire. - object: - type: string - description: The object type, which is always "upload". - enum: - - upload - x-stainless-const: true - file: - allOf: - - $ref: '#/components/schemas/OpenAIFile' - - nullable: true - description: The ready File object after the Upload is completed. + nullable: true + minimum: 0 + maximum: 2147483647 + example: 42 required: - - bytes - - created_at - - expires_at - - filename - - id - - purpose - - status - - object - x-oaiMeta: - name: The upload object - example: | - { - "id": "upload_abc123", - "object": "upload", - "bytes": 2147483648, - "created_at": 1719184911, - "filename": "training_examples.jsonl", - "purpose": "fine-tune", - "status": "completed", - "expires_at": 1719127296, - "file": { - "id": "file-xyz321", - "object": "file", - "bytes": 2147483648, - "created_at": 1719186911, - "filename": "training_examples.jsonl", - "purpose": "fine-tune", - } - } - UploadCertificateRequest: + - model + - training_file + + ListFineTuningJobEventsResponse: type: object properties: - name: - type: string - description: An optional name for the certificate - content: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJobEvent" + object: type: string - description: The certificate content in PEM format + enum: [list] required: - - content - UploadPart: + - object + - data + + ListFineTuningJobCheckpointsResponse: type: object - title: UploadPart - description: | - The upload Part represents a chunk of bytes we can add to an Upload object. properties: - id: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJobCheckpoint" + object: type: string - description: The upload Part unique identifier, which can be referenced in API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the Part was created. - upload_id: + enum: [list] + first_id: type: string - description: The ID of the Upload object that this Part was added to. - object: + nullable: true + last_id: type: string - description: The object type, which is always `upload.part`. - enum: - - upload.part - x-stainless-const: true + nullable: true + has_more: + type: boolean required: - - created_at - - id - object - - upload_id - x-oaiMeta: - name: The upload part object - example: | - { - "id": "part_def456", - "object": "upload.part", - "created_at": 1719186911, - "upload_id": "upload_abc123" - } - UsageAudioSpeechesResult: + - data + - has_more + + CreateEmbeddingRequest: type: object - description: The aggregated audio speeches usage details of the specific time bucket. + additionalProperties: false properties: - object: - type: string - enum: - - organization.usage.audio_speeches.result - x-stainless-const: true - characters: - type: integer - description: The number of characters processed. - num_model_requests: - type: integer - description: The count of requests made to the model. - project_id: - anyOf: + input: + description: | + Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + example: "The quick brown fox jumped over the lazy dog" + oneOf: - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' - user_id: + title: string + description: The string that will be turned into an embedding. + default: "" + example: "This is a test." + - type: array + title: array + description: The array of strings that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: string + default: "" + example: "['This is a test.']" + - type: array + title: array + description: The array of integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: integer + example: "[1212, 318, 257, 1332, 13]" + - type: array + title: array + description: The array of arrays containing integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: array + minItems: 1 + items: + type: integer + example: "[[1212, 318, 257, 1332, 13]]" + x-oaiExpandable: true + model: + description: *model_description + example: "text-embedding-3-small" anyOf: - type: string - description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. - - type: 'null' - api_key_id: - anyOf: - type: string - description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. - - type: 'null' + enum: + [ + "text-embedding-ada-002", + "text-embedding-3-small", + "text-embedding-3-large", + ] + x-oaiTypeLabel: string + encoding_format: + description: "The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/)." + example: "float" + default: "float" + type: string + enum: ["float", "base64"] + dimensions: + description: | + The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + type: integer + minimum: 1 + user: *end_user_param_configuration + required: + - model + - input + + CreateEmbeddingResponse: + type: object + properties: + data: + type: array + description: The list of embeddings generated by the model. + items: + $ref: "#/components/schemas/Embedding" model: - anyOf: - - type: string - description: When `group_by=model`, this field provides the model name of the grouped usage result. - - type: 'null' + type: string + description: The name of the model used to generate the embedding. + object: + type: string + description: The object type, which is always "list". + enum: [list] + usage: + type: object + description: The usage information for the request. + properties: + prompt_tokens: + type: integer + description: The number of tokens used by the prompt. + total_tokens: + type: integer + description: The total number of tokens used by the request. + required: + - prompt_tokens + - total_tokens required: - object - - characters - - num_model_requests - x-oaiMeta: - name: Audio speeches usage object - example: | - { - "object": "organization.usage.audio_speeches.result", - "characters": 45, - "num_model_requests": 1, - "project_id": "proj_abc", - "user_id": "user-abc", - "api_key_id": "key_abc", - "model": "tts-1" - } - UsageAudioTranscriptionsResult: + - model + - data + - usage + + CreateTranscriptionRequest: type: object - description: The aggregated audio transcriptions usage details of the specific time bucket. + additionalProperties: false properties: - object: + file: + description: | + The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. type: string - enum: - - organization.usage.audio_transcriptions.result - x-stainless-const: true - seconds: - type: integer - description: The number of seconds processed. - num_model_requests: - type: integer - description: The count of requests made to the model. - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' - user_id: - anyOf: - - type: string - description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. - - type: 'null' - api_key_id: - anyOf: - - type: string - description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. - - type: 'null' + x-oaiTypeLabel: file + format: binary model: + description: | + ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. + example: whisper-1 anyOf: - type: string - description: When `group_by=model`, this field provides the model name of the grouped usage result. - - type: 'null' + - type: string + enum: ["whisper-1"] + x-oaiTypeLabel: string + language: + description: | + 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) format will improve accuracy and latency. + type: string + prompt: + description: | + An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. + type: string + response_format: + description: | + The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. + type: string + enum: + - json + - text + - srt + - verbose_json + - vtt + default: json + temperature: + description: | + The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + type: number + default: 0 + timestamp_granularities[]: + description: | + The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + type: array + items: + type: string + enum: + - word + - segment + default: [segment] required: - - object - - seconds - - num_model_requests - x-oaiMeta: - name: Audio transcriptions usage object - example: | - { - "object": "organization.usage.audio_transcriptions.result", - "seconds": 10, - "num_model_requests": 1, - "project_id": "proj_abc", - "user_id": "user-abc", - "api_key_id": "key_abc", - "model": "tts-1" - } - UsageCodeInterpreterSessionsResult: + - file + - model + + # Note: This does not currently support the non-default response format types. + CreateTranscriptionResponseJson: type: object - description: The aggregated code interpreter sessions usage details of the specific time bucket. + description: Represents a transcription response returned by model, based on the provided input. properties: - object: + text: type: string - enum: - - organization.usage.code_interpreter_sessions.result - x-stainless-const: true - num_sessions: - type: integer - description: The number of code interpreter sessions. - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' + description: The transcribed text. required: - - object - - sessions + - text x-oaiMeta: - name: Code interpreter sessions usage object - example: | - { - "object": "organization.usage.code_interpreter_sessions.result", - "num_sessions": 1, - "project_id": "proj_abc" - } - UsageCompletionsResult: + name: The transcription object (JSON) + group: audio + example: *basic_transcription_response_example + + TranscriptionSegment: type: object - description: The aggregated completions usage details of the specific time bucket. properties: - object: - type: string - enum: - - organization.usage.completions.result - x-stainless-const: true - input_tokens: - type: integer - description: >- - The aggregated number of text input tokens used, including cached tokens. For customers subscribe - to scale tier, this includes scale tier tokens. - input_cached_tokens: - type: integer - description: >- - The aggregated number of text input tokens that has been cached from previous requests. For - customers subscribe to scale tier, this includes scale tier tokens. - output_tokens: - type: integer - description: >- - The aggregated number of text output tokens used. For customers subscribe to scale tier, this - includes scale tier tokens. - input_audio_tokens: - type: integer - description: The aggregated number of audio input tokens used, including cached tokens. - output_audio_tokens: + id: type: integer - description: The aggregated number of audio output tokens used. - num_model_requests: + description: Unique identifier of the segment. + seek: type: integer - description: The count of requests made to the model. - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' - user_id: - anyOf: - - type: string - description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. - - type: 'null' - api_key_id: - anyOf: - - type: string - description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. - - type: 'null' - model: - anyOf: - - type: string - description: When `group_by=model`, this field provides the model name of the grouped usage result. - - type: 'null' - batch: - anyOf: - - type: boolean - description: When `group_by=batch`, this field tells whether the grouped usage result is batch or not. - - type: 'null' - service_tier: - anyOf: - - type: string - description: >- - When `group_by=service_tier`, this field provides the service tier of the grouped usage - result. - - type: 'null' + description: Seek offset of the segment. + start: + type: number + format: float + description: Start time of the segment in seconds. + end: + type: number + format: float + description: End time of the segment in seconds. + text: + type: string + description: Text content of the segment. + tokens: + type: array + items: + type: integer + description: Array of token IDs for the text content. + temperature: + type: number + format: float + description: Temperature parameter used for generating the segment. + avg_logprob: + type: number + format: float + description: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. + compression_ratio: + type: number + format: float + description: Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. + no_speech_prob: + type: number + format: float + description: Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. required: - - object - - input_tokens - - output_tokens - - num_model_requests + - id + - seek + - start + - end + - text + - tokens + - temperature + - avg_logprob + - compression_ratio + - no_speech_prob + + TranscriptionWord: + type: object + properties: + word: + type: string + description: The text content of the word. + start: + type: number + format: float + description: Start time of the word in seconds. + end: + type: number + format: float + description: End time of the word in seconds. + required: [word, start, end] + + CreateTranscriptionResponseVerboseJson: + type: object + description: Represents a verbose json transcription response returned by model, based on the provided input. + properties: + language: + type: string + description: The language of the input audio. + duration: + type: string + description: The duration of the input audio. + text: + type: string + description: The transcribed text. + words: + type: array + description: Extracted words and their corresponding timestamps. + items: + $ref: "#/components/schemas/TranscriptionWord" + segments: + type: array + description: Segments of the transcribed text and their corresponding details. + items: + $ref: "#/components/schemas/TranscriptionSegment" + required: [language, duration, text] x-oaiMeta: - name: Completions usage object - example: | - { - "object": "organization.usage.completions.result", - "input_tokens": 5000, - "output_tokens": 1000, - "input_cached_tokens": 4000, - "input_audio_tokens": 300, - "output_audio_tokens": 200, - "num_model_requests": 5, - "project_id": "proj_abc", - "user_id": "user-abc", - "api_key_id": "key_abc", - "model": "gpt-4o-mini-2024-07-18", - "batch": false, - "service_tier": "default" - } - UsageEmbeddingsResult: + name: The transcription object (Verbose JSON) + group: audio + example: *verbose_transcription_response_example + + CreateTranslationRequest: type: object - description: The aggregated embeddings usage details of the specific time bucket. + additionalProperties: false properties: - object: + file: + description: | + The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. type: string - enum: - - organization.usage.embeddings.result - x-stainless-const: true - input_tokens: - type: integer - description: The aggregated number of input tokens used. - num_model_requests: - type: integer - description: The count of requests made to the model. - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' - user_id: - anyOf: - - type: string - description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. - - type: 'null' - api_key_id: - anyOf: - - type: string - description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. - - type: 'null' + x-oaiTypeLabel: file + format: binary model: + description: | + ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. + example: whisper-1 anyOf: - type: string - description: When `group_by=model`, this field provides the model name of the grouped usage result. - - type: 'null' + - type: string + enum: ["whisper-1"] + x-oaiTypeLabel: string + prompt: + description: | + An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. + type: string + response_format: + description: | + The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. + type: string + default: json + temperature: + description: | + The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + type: number + default: 0 required: - - object - - input_tokens - - num_model_requests - x-oaiMeta: - name: Embeddings usage object - example: | - { - "object": "organization.usage.embeddings.result", - "input_tokens": 20, - "num_model_requests": 2, - "project_id": "proj_abc", - "user_id": "user-abc", - "api_key_id": "key_abc", - "model": "text-embedding-ada-002-v2" - } - UsageImagesResult: + - file + - model + + # Note: This does not currently support the non-default response format types. + CreateTranslationResponseJson: type: object - description: The aggregated images usage details of the specific time bucket. properties: - object: + text: type: string - enum: - - organization.usage.images.result - x-stainless-const: true - images: - type: integer - description: The number of images processed. - num_model_requests: - type: integer - description: The count of requests made to the model. - source: - anyOf: - - type: string - description: >- - When `group_by=source`, this field provides the source of the grouped usage result, possible - values are `image.generation`, `image.edit`, `image.variation`. - - type: 'null' - size: - anyOf: - - type: string - description: When `group_by=size`, this field provides the image size of the grouped usage result. - - type: 'null' - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' - user_id: - anyOf: - - type: string - description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. - - type: 'null' - api_key_id: - anyOf: - - type: string - description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. - - type: 'null' - model: - anyOf: - - type: string - description: When `group_by=model`, this field provides the model name of the grouped usage result. - - type: 'null' required: - - object - - images - - num_model_requests - x-oaiMeta: - name: Images usage object - example: | - { - "object": "organization.usage.images.result", - "images": 2, - "num_model_requests": 2, - "size": "1024x1024", - "source": "image.generation", - "project_id": "proj_abc", - "user_id": "user-abc", - "api_key_id": "key_abc", - "model": "dall-e-3" - } - UsageModerationsResult: + - text + + CreateTranslationResponseVerboseJson: type: object - description: The aggregated moderations usage details of the specific time bucket. properties: - object: + language: type: string - enum: - - organization.usage.moderations.result - x-stainless-const: true - input_tokens: - type: integer - description: The aggregated number of input tokens used. - num_model_requests: - type: integer - description: The count of requests made to the model. - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' - user_id: - anyOf: - - type: string - description: When `group_by=user_id`, this field provides the user ID of the grouped usage result. - - type: 'null' - api_key_id: - anyOf: - - type: string - description: When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result. - - type: 'null' + description: The language of the output translation (always `english`). + duration: + type: string + description: The duration of the input audio. + text: + type: string + description: The translated text. + segments: + type: array + description: Segments of the translated text and their corresponding details. + items: + $ref: "#/components/schemas/TranscriptionSegment" + required: [language, duration, text] + + CreateSpeechRequest: + type: object + additionalProperties: false + properties: model: + description: | + One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd` anyOf: - type: string - description: When `group_by=model`, this field provides the model name of the grouped usage result. - - type: 'null' + - type: string + enum: ["tts-1", "tts-1-hd"] + x-oaiTypeLabel: string + input: + type: string + description: The text to generate audio for. The maximum length is 4096 characters. + maxLength: 4096 + voice: + description: The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech/voice-options). + type: string + enum: ["alloy", "echo", "fable", "onyx", "nova", "shimmer"] + response_format: + description: "The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." + default: "mp3" + type: string + enum: ["mp3", "opus", "aac", "flac", "wav", "pcm"] + speed: + description: "The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default." + type: number + default: 1.0 + minimum: 0.25 + maximum: 4.0 required: - - object - - input_tokens - - num_model_requests - x-oaiMeta: - name: Moderations usage object - example: | - { - "object": "organization.usage.moderations.result", - "input_tokens": 20, - "num_model_requests": 2, - "project_id": "proj_abc", - "user_id": "user-abc", - "api_key_id": "key_abc", - "model": "text-moderation" - } - UsageResponse: - type: object + - model + - input + - voice + + Model: + title: Model + description: Describes an OpenAI model offering that can be used with the API. properties: + id: + type: string + description: The model identifier, which can be referenced in the API endpoints. + created: + type: integer + description: The Unix timestamp (in seconds) when the model was created. object: type: string - enum: - - page - x-stainless-const: true - data: - type: array - items: - $ref: '#/components/schemas/UsageTimeBucket' - has_more: - type: boolean - next_page: + description: The object type, which is always "model". + enum: [model] + owned_by: type: string + description: The organization that owns the model. required: + - id - object - - data - - has_more - - next_page - UsageTimeBucket: - type: object + - created + - owned_by + x-oaiMeta: + name: The model object + example: *retrieve_model_response + + OpenAIFile: + title: OpenAIFile + description: The `File` object represents a document that has been uploaded to OpenAI. properties: - object: + id: type: string - enum: - - bucket - x-stainless-const: true - start_time: + description: The file identifier, which can be referenced in the API endpoints. + bytes: type: integer - end_time: + description: The size of the file, in bytes. + created_at: type: integer - result: - type: array - items: - anyOf: - - $ref: '#/components/schemas/UsageCompletionsResult' - - $ref: '#/components/schemas/UsageEmbeddingsResult' - - $ref: '#/components/schemas/UsageModerationsResult' - - $ref: '#/components/schemas/UsageImagesResult' - - $ref: '#/components/schemas/UsageAudioSpeechesResult' - - $ref: '#/components/schemas/UsageAudioTranscriptionsResult' - - $ref: '#/components/schemas/UsageVectorStoresResult' - - $ref: '#/components/schemas/UsageCodeInterpreterSessionsResult' - - $ref: '#/components/schemas/CostsResult' - discriminator: - propertyName: object - required: - - object - - start_time - - end_time - - result - UsageVectorStoresResult: - type: object - description: The aggregated vector stores usage details of the specific time bucket. - properties: + description: The Unix timestamp (in seconds) for when the file was created. + filename: + type: string + description: The name of the file. object: type: string + description: The object type, which is always `file`. + enum: ["file"] + purpose: + type: string + description: The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. enum: - - organization.usage.vector_stores.result - x-stainless-const: true - usage_bytes: - type: integer - description: The vector stores usage in bytes. - project_id: - anyOf: - - type: string - description: When `group_by=project_id`, this field provides the project ID of the grouped usage result. - - type: 'null' + [ + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", + ] + status: + type: string + deprecated: true + description: Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. + enum: ["uploaded", "processed", "error"] + status_details: + type: string + deprecated: true + description: Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. required: + - id - object - - usage_bytes + - bytes + - created_at + - filename + - purpose + - status x-oaiMeta: - name: Vector stores usage object + name: The file object example: | { - "object": "organization.usage.vector_stores.result", - "usage_bytes": 1024, - "project_id": "proj_abc" + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "salesOverview.pdf", + "purpose": "assistants", } - User: + Upload: type: object - description: Represents an individual `user` within an organization. + title: Upload + description: | + The Upload object can accept byte chunks in the form of Parts. properties: - object: - type: string - enum: - - organization.user - description: The object type, which is always `organization.user` - x-stainless-const: true id: type: string - description: The identifier, which can be referenced in API endpoints - name: + description: The Upload unique identifier, which can be referenced in API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the Upload was created. + filename: type: string - description: The name of the user - email: + description: The name of the file to be uploaded. + bytes: + type: integer + description: The intended number of bytes to be uploaded. + purpose: type: string - description: The email address of the user - role: + description: The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values. + status: type: string - enum: - - owner - - reader - description: '`owner` or `reader`' - added_at: + description: The status of the Upload. + enum: ["pending", "completed", "cancelled", "expired"] + expires_at: type: integer - description: The Unix timestamp (in seconds) of when the user was added. + description: The Unix timestamp (in seconds) for when the Upload was created. + object: + type: string + description: The object type, which is always "upload". + enum: [upload] + file: + $ref: "#/components/schemas/OpenAIFile" + nullable: true + description: The ready File object after the Upload is completed. required: - - object + - bytes + - created_at + - expires_at + - filename - id - - name - - email - - role - - added_at + - purpose + - status + - step_number x-oaiMeta: - name: The user object + name: The upload object example: | { - "object": "organization.user", - "id": "user_abc", - "name": "First Last", - "email": "user@example.com", - "role": "owner", - "added_at": 1711471533 + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "completed", + "expires_at": 1719127296, + "file": { + "id": "file-xyz321", + "object": "file", + "bytes": 2147483648, + "created_at": 1719186911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + } } - UserDeleteResponse: + UploadPart: type: object + title: UploadPart + description: | + The upload Part represents a chunk of bytes we can add to an Upload object. properties: - object: - type: string - enum: - - organization.user.deleted - x-stainless-const: true id: type: string - deleted: - type: boolean + description: The upload Part unique identifier, which can be referenced in API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the Part was created. + upload_id: + type: string + description: The ID of the Upload object that this Part was added to. + object: + type: string + description: The object type, which is always `upload.part`. + enum: ["upload.part"] required: - - object + - created_at - id - - deleted - UserListResource: + - object + - upload_id + x-oaiMeta: + name: The upload part object + example: | + { + "id": "part_def456", + "object": "upload.part", + "created_at": 1719186911, + "upload_id": "upload_abc123" + } + Embedding: type: object - description: Paginated list of user objects returned when inspecting group membership. + description: | + Represents an embedding vector returned by embedding endpoint. properties: - object: - type: string - enum: - - list - description: Always `list`. - x-stainless-const: true - data: + index: + type: integer + description: The index of the embedding in the list of embeddings. + embedding: type: array - description: Users in the current page. + description: | + The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings). items: - $ref: '#/components/schemas/User' - has_more: - type: boolean - description: Whether more users are available when paginating. - next: - description: Cursor to fetch the next page of results, or `null` when no further users are available. - anyOf: - - type: string - - type: 'null' + type: number + object: + type: string + description: The object type, which is always "embedding". + enum: [embedding] required: + - index - object - - data - - has_more - - next + - embedding x-oaiMeta: - name: Group user list + name: The embedding object example: | { - "object": "list", - "data": [ - { - "object": "organization.user", - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com", - "role": "owner", - "added_at": 1711471533 - } - ], - "has_more": false, - "next": null + "object": "embedding", + "embedding": [ + 0.0023064255, + -0.009327292, + .... (1536 floats total for ada-002) + -0.0028842222, + ], + "index": 0 } - UserListResponse: + + FineTuningJob: type: object + title: FineTuningJob + description: | + The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. properties: + id: + type: string + description: The object identifier, which can be referenced in the API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the fine-tuning job was created. + error: + type: object + nullable: true + description: For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + param: + type: string + description: The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. + nullable: true + required: + - code + - message + - param + fine_tuned_model: + type: string + nullable: true + description: The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. + finished_at: + type: integer + nullable: true + description: The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. + hyperparameters: + type: object + description: The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + properties: + n_epochs: + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 50 + default: auto + description: + The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. + + "auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs. + required: + - n_epochs + model: + type: string + description: The base model that is being fine-tuned. object: type: string - enum: - - list - x-stainless-const: true - data: + description: The object type, which is always "fine_tuning.job". + enum: [fine_tuning.job] + organization_id: + type: string + description: The organization that owns the fine-tuning job. + result_files: type: array + description: The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents). items: - $ref: '#/components/schemas/User' - first_id: + type: string + example: file-abc123 + status: type: string - last_id: + description: The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + enum: + [ + "validating_files", + "queued", + "running", + "succeeded", + "failed", + "cancelled", + ] + trained_tokens: + type: integer + nullable: true + description: The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. + training_file: type: string - has_more: - type: boolean - required: - - object - - data - - first_id - - last_id - - has_more - UserRoleAssignment: - type: object - description: Role assignment linking a user to a role. - properties: - object: + description: The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents). + validation_file: type: string - enum: - - user.role - description: Always `user.role`. - x-stainless-const: true - user: - $ref: '#/components/schemas/User' - role: - $ref: '#/components/schemas/Role' + nullable: true + description: The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents). + integrations: + type: array + nullable: true + description: A list of integrations to enable for this fine-tuning job. + maxItems: 5 + items: + oneOf: + - $ref: "#/components/schemas/FineTuningIntegration" + x-oaiExpandable: true + seed: + type: integer + description: The seed used for the fine-tuning job. + estimated_finish: + type: integer + nullable: true + description: The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running. required: + - created_at + - error + - finished_at + - fine_tuned_model + - hyperparameters + - id + - model - object - - user - - role + - organization_id + - result_files + - status + - trained_tokens + - training_file + - validation_file + - seed x-oaiMeta: - name: The user role object - example: | - { - "object": "user.role", - "user": { - "object": "organization.user", - "id": "user_abc123", - "name": "Ada Lovelace", - "email": "ada@example.com", - "role": "owner", - "added_at": 1711470000 - }, - "role": { - "object": "role", - "id": "role_01J1F8ROLE01", - "name": "API Group Manager", - "description": "Allows managing organization groups", - "permissions": [ - "api.groups.read", - "api.groups.write" - ], - "resource_type": "api.organization", - "predefined_role": false - } - } - UserRoleUpdateRequest: - type: object - properties: - role: - type: string - enum: - - owner - - reader - description: '`owner` or `reader`' - required: - - role - VadConfig: + name: The fine-tuning job object + example: *fine_tuning_example + + FineTuningIntegration: type: object - additionalProperties: false + title: Fine-Tuning Job Integration required: - type + - wandb properties: type: type: string - enum: - - server_vad - description: Must be set to `server_vad` to enable manual chunking using server side VAD. - prefix_padding_ms: - type: integer - default: 300 - description: | - Amount of audio to include before the VAD detected speech (in - milliseconds). - silence_duration_ms: - type: integer - default: 200 - description: | - Duration of silence to detect speech stop (in milliseconds). - With shorter values the model will respond more quickly, - but may jump in on short pauses from the user. - threshold: - type: number - default: 0.5 - description: | - Sensitivity threshold (0.0 to 1.0) for voice activity detection. A - higher threshold will require louder audio to activate the model, and - thus might perform better in noisy environments. - ValidateGraderRequest: - type: object - title: ValidateGraderRequest - properties: - grader: - type: object - description: The grader used for the fine-tuning job. - anyOf: - - $ref: '#/components/schemas/GraderStringCheck' - - $ref: '#/components/schemas/GraderTextSimilarity' - - $ref: '#/components/schemas/GraderPython' - - $ref: '#/components/schemas/GraderScoreModel' - - $ref: '#/components/schemas/GraderMulti' - required: - - grader - ValidateGraderResponse: - type: object - title: ValidateGraderResponse - properties: - grader: + description: "The type of the integration being enabled for the fine-tuning job" + enum: ["wandb"] + wandb: type: object - description: The grader used for the fine-tuning job. - anyOf: - - $ref: '#/components/schemas/GraderStringCheck' - - $ref: '#/components/schemas/GraderTextSimilarity' - - $ref: '#/components/schemas/GraderPython' - - $ref: '#/components/schemas/GraderScoreModel' - - $ref: '#/components/schemas/GraderMulti' - VectorStoreExpirationAfter: - type: object - title: Vector store expiration policy - description: The expiration policy for a vector store. - properties: - anchor: - description: 'Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.' - type: string - enum: - - last_active_at - x-stainless-const: true - days: - description: The number of days after the anchor time that the vector store will expire. - type: integer - minimum: 1 - maximum: 365 - required: - - anchor - - days - VectorStoreFileAttributes: - anyOf: - - type: object description: | - 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, booleans, or numbers. - maxProperties: 16 - propertyNames: - type: string - maxLength: 64 - additionalProperties: - anyOf: - - type: string - maxLength: 512 - - type: number - - type: boolean - x-oaiTypeLabel: map - - type: 'null' - VectorStoreFileBatchObject: + The settings for your integration with Weights and Biases. This payload specifies the project that + metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags + to your run, and set a default entity (team, username, etc) to be associated with your run. + required: + - project + properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: "my-wandb-project" + name: + description: | + A display name to set for the run. If not set, we will use the Job ID as the name. + nullable: true + type: string + entity: + description: | + The entity to use for the run. This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered WandB API key is used. + nullable: true + type: string + tags: + description: | + A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some + default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: "custom-tag" + + FineTuningJobEvent: type: object - title: Vector store file batch - description: A batch of files attached to a vector store. + description: Fine-tuning job event object properties: id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `vector_store.file_batch`. type: string - enum: - - vector_store.files_batch - x-stainless-const: true created_at: - description: The Unix timestamp (in seconds) for when the vector store files batch was created. type: integer - vector_store_id: - description: >- - The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. - type: string - status: - description: >- - The status of the vector store files batch, which can be either `in_progress`, `completed`, - `cancelled` or `failed`. - type: string - enum: - - in_progress - - completed - - cancelled - - failed - file_counts: - type: object - properties: - in_progress: - description: The number of files that are currently being processed. - type: integer - completed: - description: The number of files that have been processed. - type: integer - failed: - description: The number of files that have failed to process. - type: integer - cancelled: - description: The number of files that where cancelled. - type: integer - total: - description: The total number of files. - type: integer - required: - - in_progress - - completed - - cancelled - - failed - - total + level: + type: string + enum: ["info", "warn", "error"] + message: + type: string + object: + type: string + enum: [fine_tuning.job.event] required: - id - object - created_at - - vector_store_id - - status - - file_counts + - level + - message x-oaiMeta: - name: The vector store files batch object - beta: true + name: The fine-tuning job event object example: | { - "id": "vsfb_123", - "object": "vector_store.files_batch", - "created_at": 1698107661, - "vector_store_id": "vs_abc123", - "status": "completed", - "file_counts": { - "in_progress": 0, - "completed": 100, - "failed": 0, - "cancelled": 0, - "total": 100 - } + "object": "fine_tuning.job.event", + "id": "ftevent-abc123" + "created_at": 1677610602, + "level": "info", + "message": "Created fine-tuning job" } - VectorStoreFileContentResponse: - type: object - description: Represents the parsed content of a vector store file. - properties: - object: - type: string - enum: - - vector_store.file_content.page - description: The object type, which is always `vector_store.file_content.page` - x-stainless-const: true - data: - type: array - description: Parsed content of the file. - items: - type: object - properties: - type: - type: string - description: The content type (currently only `"text"`) - text: - type: string - description: The text content - has_more: - type: boolean - description: Indicates if there are more content pages to fetch. - next_page: - anyOf: - - type: string - description: The token for the next page, if any. - - type: 'null' - required: - - object - - data - - has_more - - next_page - VectorStoreFileObject: + + FineTuningJobCheckpoint: type: object - title: Vector store files - description: A list of files attached to a vector store. + title: FineTuningJobCheckpoint + description: | + The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use. properties: id: - description: The identifier, which can be referenced in API endpoints. type: string - object: - description: The object type, which is always `vector_store.file`. - type: string - enum: - - vector_store.file - x-stainless-const: true - usage_bytes: - description: >- - The total vector store usage in bytes. Note that this may be different from the original file - size. - type: integer + description: The checkpoint identifier, which can be referenced in the API endpoints. created_at: - description: The Unix timestamp (in seconds) for when the vector store file was created. type: integer - vector_store_id: - description: >- - The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. + description: The Unix timestamp (in seconds) for when the checkpoint was created. + fine_tuned_model_checkpoint: type: string - status: - description: >- - The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, - or `failed`. The status `completed` indicates that the vector store file is ready for use. + description: The name of the fine-tuned checkpoint model that is created. + step_number: + type: integer + description: The step number that the checkpoint was created at. + metrics: + type: object + description: Metrics at the step number during the fine-tuning job. + properties: + step: + type: number + train_loss: + type: number + train_mean_token_accuracy: + type: number + valid_loss: + type: number + valid_mean_token_accuracy: + type: number + full_valid_loss: + type: number + full_valid_mean_token_accuracy: + type: number + fine_tuning_job_id: type: string - enum: - - in_progress - - completed - - cancelled - - failed - last_error: - anyOf: - - type: object - description: The last error associated with this vector store file. Will be `null` if there are no errors. - properties: - code: - type: string - description: One of `server_error`, `unsupported_file`, or `invalid_file`. - enum: - - server_error - - unsupported_file - - invalid_file - message: - type: string - description: A human-readable description of the error. - required: - - code - - message - - type: 'null' - chunking_strategy: - $ref: '#/components/schemas/ChunkingStrategyResponse' - attributes: - $ref: '#/components/schemas/VectorStoreFileAttributes' + description: The name of the fine-tuning job that this checkpoint was created from. + object: + type: string + description: The object type, which is always "fine_tuning.job.checkpoint". + enum: [fine_tuning.job.checkpoint] required: + - created_at + - fine_tuning_job_id + - fine_tuned_model_checkpoint - id + - metrics - object - - usage_bytes - - created_at - - vector_store_id - - status - - last_error + - step_number x-oaiMeta: - name: The vector store file object - beta: true + name: The fine-tuning job checkpoint object example: | { - "id": "file-abc123", - "object": "vector_store.file", - "usage_bytes": 1234, - "created_at": 1698107661, - "vector_store_id": "vs_abc123", - "status": "completed", - "last_error": null, - "chunking_strategy": { - "type": "static", - "static": { - "max_chunk_size_tokens": 800, - "chunk_overlap_tokens": 400 + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", + "created_at": 1712211699, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom_suffix:9ABel2dg:ckpt-step-88", + "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", + "metrics": { + "step": 88, + "train_loss": 0.478, + "train_mean_token_accuracy": 0.924, + "valid_loss": 10.112, + "valid_mean_token_accuracy": 0.145, + "full_valid_loss": 0.567, + "full_valid_mean_token_accuracy": 0.944 + }, + "step_number": 88 + } + + FinetuneChatRequestInput: + type: object + description: The per-line training example of a fine-tuning input file for chat models + properties: + messages: + type: array + minItems: 1 + items: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" + - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" + - $ref: "#/components/schemas/FineTuneChatCompletionRequestAssistantMessage" + - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" + - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" + x-oaiExpandable: true + tools: + type: array + description: A list of tools the model may generate JSON inputs for. + items: + $ref: "#/components/schemas/ChatCompletionTool" + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + functions: + deprecated: true + description: A list of functions the model may generate JSON inputs for. + type: array + minItems: 1 + maxItems: 128 + items: + $ref: "#/components/schemas/ChatCompletionFunctions" + x-oaiMeta: + name: Training format for chat models + example: | + { + "messages": [ + { "role": "user", "content": "What is the weather in San Francisco?" }, + { + "role": "assistant", + "tool_calls": [ + { + "id": "call_id", + "type": "function", + "function": { + "name": "get_current_weather", + "arguments": "{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}" + } + } + ] } - } + ], + "parallel_tool_calls": false, + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and country, eg. San Francisco, USA" + }, + "format": { "type": "string", "enum": ["celsius", "fahrenheit"] } + }, + "required": ["location", "format"] + } + } + } + ] } - VectorStoreObject: + + FinetuneCompletionRequestInput: + type: object + description: The per-line training example of a fine-tuning input file for completions models + properties: + prompt: + type: string + description: The input prompt for this training example. + completion: + type: string + description: The desired completion for this training example. + x-oaiMeta: + name: Training format for completions models + example: | + { + "prompt": "What is the answer to 2+2", + "completion": "4" + } + + CompletionUsage: + type: object + description: Usage statistics for the completion request. + properties: + completion_tokens: + type: integer + description: Number of tokens in the generated completion. + prompt_tokens: + type: integer + description: Number of tokens in the prompt. + total_tokens: + type: integer + description: Total number of tokens used in the request (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + + RunCompletionUsage: + type: object + description: Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + properties: + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + nullable: true + + RunStepCompletionUsage: type: object - title: Vector store - description: A vector store is a collection of processed files can be used by the `file_search` tool. + description: Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. + properties: + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run step. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run step. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + nullable: true + + AssistantsApiResponseFormatOption: + description: | + Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + oneOf: + - type: string + description: > + `auto` is the default value + enum: [auto] + - $ref: "#/components/schemas/ResponseFormatText" + - $ref: "#/components/schemas/ResponseFormatJsonObject" + - $ref: "#/components/schemas/ResponseFormatJsonSchema" + x-oaiExpandable: true + + AssistantObject: + type: object + title: Assistant + description: Represents an `assistant` that can call the model and use tools. properties: id: description: The identifier, which can be referenced in API endpoints. type: string object: - description: The object type, which is always `vector_store`. + description: The object type, which is always `assistant`. type: string - enum: - - vector_store - x-stainless-const: true + enum: [assistant] created_at: - description: The Unix timestamp (in seconds) for when the vector store was created. + description: The Unix timestamp (in seconds) for when the assistant was created. type: integer name: - description: The name of the vector store. + description: &assistant_name_param_description | + The name of the assistant. The maximum length is 256 characters. type: string - usage_bytes: - description: The total number of bytes used by the files in the vector store. - type: integer - file_counts: + maxLength: 256 + nullable: true + description: + description: &assistant_description_param_description | + The description of the assistant. The maximum length is 512 characters. + type: string + maxLength: 512 + nullable: true + model: + description: *model_description + type: string + instructions: + description: &assistant_instructions_param_description | + The system instructions that the assistant uses. The maximum length is 256,000 characters. + type: string + maxLength: 256000 + nullable: true + tools: + description: &assistant_tools_param_description | + A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - in_progress: - description: The number of files that are currently being processed. - type: integer - completed: - description: The number of files that have been successfully processed. - type: integer - failed: - description: The number of files that have failed to process. - type: integer - cancelled: - description: The number of files that were cancelled. - type: integer - total: - description: The total number of files. - type: integer - required: - - in_progress - - completed - - failed - - cancelled - - total - status: - description: >- - The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A - status of `completed` indicates that the vector store is ready for use. - type: string - enum: - - expired - - in_progress - - completed - expires_after: - $ref: '#/components/schemas/VectorStoreExpirationAfter' - expires_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the vector store will expire. - type: integer - - type: 'null' - last_active_at: - anyOf: - - description: The Unix timestamp (in seconds) for when the vector store was last active. - type: integer - - type: 'null' + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true metadata: - $ref: '#/components/schemas/Metadata' + description: &metadata_description | + 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. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: &run_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &run_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - id - object - - usage_bytes - created_at - - status - - last_active_at - name - - file_counts + - description + - model + - instructions + - tools - metadata x-oaiMeta: - name: The vector store object - example: | - { - "id": "vs_123", - "object": "vector_store", - "created_at": 1698107661, - "usage_bytes": 123456, - "last_active_at": 1698107661, - "name": "my_vector_store", - "status": "completed", - "file_counts": { - "in_progress": 0, - "completed": 100, - "cancelled": 0, - "failed": 0, - "total": 100 - }, - "last_used_at": 1698107661 - } - VectorStoreSearchRequest: + name: The assistant object + beta: true + example: *create_assistants_example + + CreateAssistantRequest: type: object additionalProperties: false properties: - query: - description: A query string for a search + model: + description: *model_description + example: "gpt-4o" anyOf: - type: string - - type: array - items: - type: string - description: A list of queries to search for. - minItems: 1 - rewrite_query: - description: Whether to rewrite the natural language query for vector search. - type: boolean - default: false - max_num_results: - description: The maximum number of results to return. This number should be between 1 and 50 inclusive. - type: integer - default: 10 - minimum: 1 - maximum: 50 - filters: - description: A filter to apply based on file attributes. - anyOf: - - $ref: '#/components/schemas/ComparisonFilter' - - $ref: '#/components/schemas/CompoundFilter' - ranking_options: - description: Ranking options for search. + - type: string + enum: + [ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + name: + description: *assistant_name_param_description + type: string + nullable: true + maxLength: 256 + description: + description: *assistant_description_param_description + type: string + nullable: true + maxLength: 512 + instructions: + description: *assistant_instructions_param_description + type: string + nullable: true + maxLength: 256000 + tools: + description: *assistant_tools_param_description + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: type: object - additionalProperties: false + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - ranker: - description: Enable re-ranking; set to `none` to disable, which can help reduce latency. - type: string - enum: - - none - - auto - - default-2024-11-15 - default: auto - score_threshold: - type: number - minimum: 0 - maximum: 1 - default: 0 + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: | + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + maxItems: 10000 + items: + type: string + chunking_strategy: + # Ideally we'd reuse the chunking strategy schema here, but it doesn't expand properly + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + oneOf: + - type: object + title: Auto Chunking Strategy + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: ["auto"] + required: + - type + - type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: ["static"] + static: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: + type: integer + description: | + The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + required: + - type + - static + x-oaiExpandable: true + metadata: + type: object + description: | + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + oneOf: + - required: [vector_store_ids] + - required: [vector_stores] + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: *run_temperature_description + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - - query - x-oaiMeta: - name: Vector store search request - VectorStoreSearchResultContentObject: + - model + + ModifyAssistantRequest: type: object additionalProperties: false properties: - type: - description: The type of content. - type: string - enum: - - text - text: - description: The text content returned from search. + model: + description: *model_description + anyOf: + - type: string + name: + description: *assistant_name_param_description type: string - required: - - type - - text - x-oaiMeta: - name: Vector store search result content object - VectorStoreSearchResultItem: - type: object - additionalProperties: false - properties: - file_id: + nullable: true + maxLength: 256 + description: + description: *assistant_description_param_description type: string - description: The ID of the vector store file. - filename: + nullable: true + maxLength: 512 + instructions: + description: *assistant_instructions_param_description type: string - description: The name of the vector store file. - score: + nullable: true + maxLength: 256000 + tools: + description: *assistant_tools_param_description + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: + type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: *run_temperature_description + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: type: number - description: The similarity score for the result. minimum: 0 maximum: 1 - attributes: - $ref: '#/components/schemas/VectorStoreFileAttributes' - content: - type: array - description: Content chunks from the file. - items: - $ref: '#/components/schemas/VectorStoreSearchResultContentObject' + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + + DeleteAssistantResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [assistant.deleted] required: - - file_id - - filename - - score - - attributes - - content - x-oaiMeta: - name: Vector store search result item - VectorStoreSearchResultsPage: + - id + - object + - deleted + + ListAssistantsResponse: type: object - additionalProperties: false properties: object: type: string - enum: - - vector_store.search_results.page - description: The object type, which is always `vector_store.search_results.page` - x-stainless-const: true - search_query: - type: array - items: - type: string - description: The query used for this search. - minItems: 1 + example: "list" data: type: array - description: The list of search result items. items: - $ref: '#/components/schemas/VectorStoreSearchResultItem' + $ref: "#/components/schemas/AssistantObject" + first_id: + type: string + example: "asst_abc123" + last_id: + type: string + example: "asst_abc456" has_more: type: boolean - description: Indicates if there are more results to fetch. - next_page: - anyOf: - - type: string - description: The token for the next page, if any. - - type: 'null' + example: false required: - object - - search_query - data + - first_id + - last_id - has_more - - next_page x-oaiMeta: - name: Vector store search results page - Verbosity: - anyOf: - - type: string - enum: - - low - - medium - - high - default: medium - description: | - Constrains the verbosity of the model's response. Lower values will result in - more concise responses, while higher values will result in more verbose responses. - Currently supported values are `low`, `medium`, and `high`. - - type: 'null' - VoiceIdsShared: - example: ash - anyOf: - - type: string - - type: string - enum: - - alloy - - ash - - ballad - - coral - - echo - - sage - - shimmer - - verse - - marin - - cedar - Wait: + name: List assistants response object + group: chat + example: *list_assistants_example + + AssistantToolsCode: type: object - title: Wait - description: | - A wait action. + title: Code interpreter tool properties: type: type: string - enum: - - wait - default: wait - description: | - Specifies the event type. For a wait action, this property is - always set to `wait`. - x-stainless-const: true + description: "The type of tool being defined: `code_interpreter`" + enum: ["code_interpreter"] required: - type - WebSearchActionFind: + + AssistantToolsFileSearch: type: object - title: Find action - description: | - Action type "find": Searches for a pattern within a loaded page. + title: FileSearch tool properties: type: type: string - enum: - - find - description: | - The action type. - x-stainless-const: true - url: - type: string - format: uri - description: | - The URL of the page searched for the pattern. - pattern: - type: string - description: | - The pattern or text to search for within the page. + description: "The type of tool being defined: `file_search`" + enum: ["file_search"] + file_search: + type: object + description: Overrides for the file search tool. + properties: + max_num_results: + type: integer + minimum: 1 + maximum: 50 + description: | + The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. + + Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information. required: - type - - url - - pattern - WebSearchActionOpenPage: + + AssistantToolsFileSearchTypeOnly: type: object - title: Open page action - description: | - Action type "open_page" - Opens a specific URL from search results. + title: FileSearch tool properties: type: type: string - enum: - - open_page - description: | - The action type. - x-stainless-const: true - url: - type: string - format: uri - description: | - The URL opened by the model. + description: "The type of tool being defined: `file_search`" + enum: ["file_search"] required: - type - - url - WebSearchActionSearch: + + AssistantToolsFunction: type: object - title: Search action - description: | - Action type "search" - Performs a web search query. + title: Function tool properties: type: type: string - enum: - - search - description: | - The action type. - x-stainless-const: true - query: - type: string - description: | - The search query. - sources: - type: array - title: Web search sources - description: | - The sources used in the search. - items: - type: object - title: Web search source - description: | - A source used in the search. - properties: - type: - type: string - enum: - - url - description: | - The type of source. Always `url`. - x-stainless-const: true - url: - type: string - description: | - The URL of the source. - required: - - type - - url + description: "The type of tool being defined: `function`" + enum: ["function"] + function: + $ref: "#/components/schemas/FunctionObject" required: - type - - query - WebSearchApproximateLocation: - anyOf: - - type: object - title: Web search approximate location - description: | - The approximate location of the user. - properties: - type: - type: string - enum: - - approximate - description: The type of location approximation. Always `approximate`. - default: approximate - x-stainless-const: true - country: - anyOf: - - type: string - description: >- - The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, - e.g. `US`. - - type: 'null' - region: - anyOf: - - type: string - description: Free text input for the region of the user, e.g. `California`. - - type: 'null' - city: - anyOf: - - type: string - description: Free text input for the city of the user, e.g. `San Francisco`. - - type: 'null' - timezone: - anyOf: - - type: string - description: >- - The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. - `America/Los_Angeles`. - - type: 'null' - - type: 'null' - WebSearchContextSize: - type: string - description: | - 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. - enum: - - low - - medium - - high - default: medium - WebSearchLocation: - type: object - title: Web search location - description: Approximate location parameters for the search. - properties: - country: - type: string - description: | - The two-letter - [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, - e.g. `US`. - region: - type: string - description: | - Free text input for the region of the user, e.g. `California`. - city: - type: string - description: | - Free text input for the city of the user, e.g. `San Francisco`. - timezone: - type: string - description: | - The [IANA timezone](https://timeapi.io/documentation/iana-timezones) - of the user, e.g. `America/Los_Angeles`. - WebSearchTool: + - function + + TruncationObject: type: object - title: Web search - description: | - 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). + title: Thread Truncation Controls + description: Controls for how a thread will be truncated prior to the run. Use this to control the intial context window of the run. properties: type: type: string - enum: - - web_search - - web_search_2025_08_26 - description: The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. - default: web_search - filters: - anyOf: - - type: object - description: | - Filters for the search. - properties: - allowed_domains: - anyOf: - - type: array - title: Allowed domains for the search. - description: | - 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"]` - items: - type: string - description: Allowed domain for the search. - default: [] - - type: 'null' - - type: 'null' - user_location: - $ref: '#/components/schemas/WebSearchApproximateLocation' - search_context_size: - type: string - enum: - - low - - medium - - high - default: medium - description: >- - 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. + description: The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. + enum: ["auto", "last_messages"] + last_messages: + type: integer + description: The number of most recent messages from the thread when constructing the context for the run. + minimum: 1 + nullable: true required: - type - WebSearchToolCall: - type: object - title: Web search tool call + + AssistantsApiToolChoiceOption: description: | - The results of a web search tool call. See the - [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information. + Controls which (if any) tool is called by the model. + `none` means the model will not call any tools and instead generates a message. + `auto` is the default value and means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools before responding to the user. + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + + oneOf: + - type: string + description: > + `none` means the model will not call any tools and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools before responding to the user. + enum: [none, auto, required] + - $ref: "#/components/schemas/AssistantsNamedToolChoice" + x-oaiExpandable: true + + AssistantsNamedToolChoice: + type: object + description: Specifies a tool the model should use. Use to force the model to call a specific tool. properties: - id: - type: string - description: | - The unique ID of the web search tool call. type: type: string - enum: - - web_search_call - description: | - The type of the web search tool call. Always `web_search_call`. - x-stainless-const: true - status: - type: string - description: | - The status of the web search tool call. - enum: - - in_progress - - searching - - completed - - failed - action: + enum: ["function", "code_interpreter", "file_search"] + description: The type of the tool. If type is `function`, the function name must be set + function: type: object - description: | - An object describing the specific action taken in this web search call. - Includes details on how the model used the web (search, open_page, find). - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/WebSearchActionSearch' - - $ref: '#/components/schemas/WebSearchActionOpenPage' - - $ref: '#/components/schemas/WebSearchActionFind' - required: - - id - - type - - status - - action - WebhookBatchCancelled: - type: object - title: batch.cancelled - description: | - Sent when a batch API request has been cancelled. + properties: + name: + type: string + description: The name of the function to call. + required: + - name required: - - created_at - - id - - data - type + + RunObject: + type: object + title: A run on a thread + description: Represents an execution run on a [thread](/docs/api-reference/threads). properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run`. + type: string + enum: ["thread.run"] created_at: + description: The Unix timestamp (in seconds) for when the run was created. type: integer - description: | - The Unix timestamp (in seconds) of when the batch API request was cancelled. - id: + thread_id: + description: The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run. type: string - description: | - The unique ID of the event. - data: + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run. + type: string + status: + description: The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. + type: string + enum: + [ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired", + ] + required_action: type: object - description: | - Event data payload. + description: Details on the action required to continue the run. Will be `null` if no action is required. + nullable: true + properties: + type: + description: For now, this is always `submit_tool_outputs`. + type: string + enum: ["submit_tool_outputs"] + submit_tool_outputs: + type: object + description: Details on the tool outputs needed for this run to continue. + properties: + tool_calls: + type: array + description: A list of the relevant tool calls. + items: + $ref: "#/components/schemas/RunToolCallObject" + required: + - tool_calls required: - - id + - type + - submit_tool_outputs + last_error: + type: object + description: The last error associated with this run. Will be `null` if there are no errors. + nullable: true properties: - id: + code: type: string - description: | - The unique ID of the batch API request. - object: + description: One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. + enum: ["server_error", "rate_limit_exceeded", "invalid_prompt"] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + expires_at: + description: The Unix timestamp (in seconds) for when the run will expire. + type: integer + nullable: true + started_at: + description: The Unix timestamp (in seconds) for when the run was started. + type: integer + nullable: true + cancelled_at: + description: The Unix timestamp (in seconds) for when the run was cancelled. + type: integer + nullable: true + failed_at: + description: The Unix timestamp (in seconds) for when the run failed. + type: integer + nullable: true + completed_at: + description: The Unix timestamp (in seconds) for when the run was completed. + type: integer + nullable: true + incomplete_details: + description: Details on why the run is incomplete. Will be `null` if the run is not incomplete. + type: object + nullable: true + properties: + reason: + description: The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. + type: string + enum: ["max_completion_tokens", "max_prompt_tokens"] + model: + description: The model that the [assistant](/docs/api-reference/assistants) used for this run. type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: + instructions: + description: The instructions that the [assistant](/docs/api-reference/assistants) used for this run. type: string + tools: + description: The list of tools that the [assistant](/docs/api-reference/assistants) used for this run. + default: [] + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + usage: + $ref: "#/components/schemas/RunCompletionUsage" + temperature: + description: The sampling temperature used for this run. If not set, defaults to 1. + type: number + nullable: true + top_p: + description: The nucleus sampling value used for this run. If not set, defaults to 1. + type: number + nullable: true + max_prompt_tokens: + type: integer + nullable: true description: | - The type of the event. Always `batch.cancelled`. - enum: - - batch.cancelled - x-stainless-const: true + The maximum number of prompt tokens specified to have been used over the course of the run. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens specified to have been used over the course of the run. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - id + - object + - created_at + - thread_id + - assistant_id + - status + - required_action + - last_error + - expires_at + - started_at + - cancelled_at + - failed_at + - completed_at + - model + - instructions + - tools + - metadata + - usage + - incomplete_details + - max_prompt_tokens + - max_completion_tokens + - truncation_strategy + - tool_choice + - parallel_tool_calls + - response_format x-oaiMeta: - name: batch.cancelled - group: webhook-events + name: The run object + beta: true example: | { - "id": "evt_abc123", - "type": "batch.cancelled", - "created_at": 1719168000, - "data": { - "id": "batch_abc123" - } + "id": "run_abc123", + "object": "thread.run", + "created_at": 1698107661, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699073476, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699073498, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], + "metadata": {}, + "incomplete_details": null, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true } - WebhookBatchCompleted: + CreateRunRequest: type: object - title: batch.completed - description: | - Sent when a batch API request has been completed. - required: - - created_at - - id - - data - - type + additionalProperties: false properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the batch API request was completed. - id: + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. type: string - description: | - The unique ID of the event. - data: + model: + description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. + example: "gpt-4o" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + nullable: true + instructions: + description: Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + type: string + nullable: true + additional_instructions: + description: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. + type: string + nullable: true + additional_messages: + description: Adds additional messages to the thread before creating the run. + type: array + items: + $ref: "#/components/schemas/CreateMessageRequest" + nullable: true + tools: + description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + metadata: + description: *metadata_description type: object + x-oaiTypeLabel: map + nullable: true + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *run_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + stream: + type: boolean + nullable: true description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the batch API request. - object: - type: string + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string + The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true description: | - The type of the event. Always `batch.completed`. - enum: - - batch.completed - x-stainless-const: true - x-oaiMeta: - name: batch.completed - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "batch.completed", - "created_at": 1719168000, - "data": { - "id": "batch_abc123" - } - } - WebhookBatchExpired: - type: object - title: batch.expired - description: | - Sent when a batch API request has expired. + The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - - created_at - - id - - data - - type + - thread_id + - assistant_id + ListRunsResponse: + type: object properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the batch API request expired. - id: + object: type: string - description: | - The unique ID of the event. + example: "list" data: - type: object - description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the batch API request. - object: + type: array + items: + $ref: "#/components/schemas/RunObject" + first_id: type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: + example: "run_abc123" + last_id: type: string - description: | - The type of the event. Always `batch.expired`. - enum: - - batch.expired - x-stainless-const: true - x-oaiMeta: - name: batch.expired - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "batch.expired", - "created_at": 1719168000, - "data": { - "id": "batch_abc123" - } - } - WebhookBatchFailed: - type: object - title: batch.failed - description: | - Sent when a batch API request has failed. + example: "run_abc456" + has_more: + type: boolean + example: false required: - - created_at - - id + - object - data - - type + - first_id + - last_id + - has_more + ModifyRunRequest: + type: object + additionalProperties: false properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the batch API request failed. - id: - type: string - description: | - The unique ID of the event. - data: + metadata: + description: *metadata_description type: object - description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the batch API request. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `batch.failed`. - enum: - - batch.failed - x-stainless-const: true - x-oaiMeta: - name: batch.failed - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "batch.failed", - "created_at": 1719168000, - "data": { - "id": "batch_abc123" - } - } - WebhookEvalRunCanceled: + x-oaiTypeLabel: map + nullable: true + SubmitToolOutputsRunRequest: type: object - title: eval.run.canceled - description: | - Sent when an eval run has been canceled. - required: - - created_at - - id - - data - - type + additionalProperties: false properties: - created_at: - type: integer + tool_outputs: + description: A list of tools for which the outputs are being submitted. + type: array + items: + type: object + properties: + tool_call_id: + type: string + description: The ID of the tool call in the `required_action` object within the run object the output is being submitted for. + output: + type: string + description: The output of the tool call to be submitted to continue the run. + stream: + type: boolean + nullable: true description: | - The Unix timestamp (in seconds) of when the eval run was canceled. + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + required: + - tool_outputs + + RunToolCallObject: + type: object + description: Tool call objects + properties: id: type: string - description: | - The unique ID of the event. - data: + description: The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint. + type: + type: string + description: The type of tool call the output is required for. For now, this is always `function`. + enum: ["function"] + function: type: object - description: | - Event data payload. - required: - - id + description: The function definition. properties: - id: + name: type: string - description: | - The unique ID of the eval run. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `eval.run.canceled`. - enum: - - eval.run.canceled - x-stainless-const: true - x-oaiMeta: - name: eval.run.canceled - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "eval.run.canceled", - "created_at": 1719168000, - "data": { - "id": "evalrun_abc123" - } - } - WebhookEvalRunFailed: - type: object - title: eval.run.failed - description: | - Sent when an eval run has failed. + description: The name of the function. + arguments: + type: string + description: The arguments that the model expects you to pass to the function. + required: + - name + - arguments required: - - created_at - id - - data - type + - function + + CreateThreadAndRunRequest: + type: object + additionalProperties: false properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the eval run failed. - id: + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. + type: string + thread: + $ref: "#/components/schemas/CreateThreadRequest" + description: If no thread is provided, an empty thread will be created. + model: + description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. + example: "gpt-4o" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + nullable: true + instructions: + description: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. type: string + nullable: true + tools: + description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + tool_resources: + type: object description: | - The unique ID of the event. - data: + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description type: object + x-oaiTypeLabel: map + nullable: true + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *run_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + stream: + type: boolean + nullable: true description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the eval run. - object: - type: string + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string + The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true description: | - The type of the event. Always `eval.run.failed`. - enum: - - eval.run.failed - x-stainless-const: true - x-oaiMeta: - name: eval.run.failed - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "eval.run.failed", - "created_at": 1719168000, - "data": { - "id": "evalrun_abc123" - } - } - WebhookEvalRunSucceeded: - type: object - title: eval.run.succeeded - description: | - Sent when an eval run has succeeded. + The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - - created_at - - id - - data - - type + - thread_id + - assistant_id + + ThreadObject: + type: object + title: Thread + description: Represents a thread that contains [messages](/docs/api-reference/messages). properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the eval run succeeded. id: + description: The identifier, which can be referenced in API endpoints. type: string - description: | - The unique ID of the event. - data: - type: object - description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the eval run. object: + description: The object type, which is always `thread`. type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `eval.run.succeeded`. - enum: - - eval.run.succeeded - x-stainless-const: true - x-oaiMeta: - name: eval.run.succeeded - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "eval.run.succeeded", - "created_at": 1719168000, - "data": { - "id": "evalrun_abc123" - } - } - WebhookFineTuningJobCancelled: - type: object - title: fine_tuning.job.cancelled - description: | - Sent when a fine-tuning job has been cancelled. - required: - - created_at - - id - - data - - type - properties: + enum: ["thread"] created_at: + description: The Unix timestamp (in seconds) for when the thread was created. type: integer - description: | - The Unix timestamp (in seconds) of when the fine-tuning job was cancelled. - id: - type: string - description: | - The unique ID of the event. - data: + tool_resources: type: object description: | - Event data payload. - required: - - id + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - id: - type: string - description: | - The unique ID of the fine-tuning job. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `fine_tuning.job.cancelled`. - enum: - - fine_tuning.job.cancelled - x-stainless-const: true - x-oaiMeta: - name: fine_tuning.job.cancelled - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "fine_tuning.job.cancelled", - "created_at": 1719168000, - "data": { - "id": "ftjob_abc123" - } - } - WebhookFineTuningJobFailed: - type: object - title: fine_tuning.job.failed - description: | - Sent when a fine-tuning job has failed. + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true required: - - created_at - id - - data - - type - properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the fine-tuning job failed. - id: - type: string - description: | - The unique ID of the event. - data: - type: object - description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the fine-tuning job. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `fine_tuning.job.failed`. - enum: - - fine_tuning.job.failed - x-stainless-const: true + - object + - created_at + - tool_resources + - metadata x-oaiMeta: - name: fine_tuning.job.failed - group: webhook-events + name: The thread object + beta: true example: | { - "id": "evt_abc123", - "type": "fine_tuning.job.failed", - "created_at": 1719168000, - "data": { - "id": "ftjob_abc123" - } - } - WebhookFineTuningJobSucceeded: + "id": "thread_abc123", + "object": "thread", + "created_at": 1698107661, + "metadata": {} + } + + CreateThreadRequest: type: object - title: fine_tuning.job.succeeded - description: | - Sent when a fine-tuning job has succeeded. - required: - - created_at - - id - - data - - type + additionalProperties: false properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the fine-tuning job succeeded. - id: - type: string - description: | - The unique ID of the event. - data: + messages: + description: A list of [messages](/docs/api-reference/messages) to start the thread with. + type: array + items: + $ref: "#/components/schemas/CreateMessageRequest" + tool_resources: type: object description: | - Event data payload. - required: - - id + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - id: - type: string - description: | - The unique ID of the fine-tuning job. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `fine_tuning.job.succeeded`. - enum: - - fine_tuning.job.succeeded - x-stainless-const: true - x-oaiMeta: - name: fine_tuning.job.succeeded - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "fine_tuning.job.succeeded", - "created_at": 1719168000, - "data": { - "id": "ftjob_abc123" - } - } - WebhookRealtimeCallIncoming: - type: object - title: realtime.call.incoming - description: | - Sent when Realtime API Receives a incoming SIP call. - required: - - created_at - - id - - data - - type - properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the model response was completed. - id: - type: string - description: | - The unique ID of the event. - data: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: | + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + maxItems: 10000 + items: + type: string + chunking_strategy: + # Ideally we'd reuse the chunking strategy schema here, but it doesn't expand properly + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + oneOf: + - type: object + title: Auto Chunking Strategy + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: ["auto"] + required: + - type + - type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: ["static"] + static: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: + type: integer + description: | + The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + required: + - type + - static + x-oaiExpandable: true + metadata: + type: object + description: | + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + x-oaiExpandable: true + oneOf: + - required: [vector_store_ids] + - required: [vector_stores] + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + ModifyThreadRequest: + type: object + additionalProperties: false + properties: + tool_resources: type: object description: | - Event data payload. - required: - - call_id - - sip_headers + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - call_id: - type: string - description: | - The unique ID of this call. - sip_headers: - type: array - description: | - Headers from the SIP Invite. - items: - type: object - description: | - A header from the SIP Invite. - required: - - name - - value - properties: - name: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: type: string - description: | - Name of the SIP Header. - value: + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: type: string - description: | - Value of the SIP Header. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `realtime.call.incoming`. - enum: - - realtime.call.incoming - x-stainless-const: true - x-oaiMeta: - name: realtime.call.incoming - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "realtime.call.incoming", - "created_at": 1719168000, - "data": { - "call_id": "rtc_479a275623b54bdb9b6fbae2f7cbd408", - "sip_headers": [ - {"name": "Max-Forwards", "value": "63"}, - {"name": "CSeq", "value": "851287 INVITE"}, - {"name": "Content-Type", "value": "application/sdp"}, - ] - } - } - WebhookResponseCancelled: + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + DeleteThreadResponse: type: object - title: response.cancelled - description: | - Sent when a background response has been cancelled. - required: - - created_at - - id - - data - - type properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the model response was cancelled. id: type: string - description: | - The unique ID of the event. - data: - type: object - description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the model response. + deleted: + type: boolean object: type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `response.cancelled`. - enum: - - response.cancelled - x-stainless-const: true - x-oaiMeta: - name: response.cancelled - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "response.cancelled", - "created_at": 1719168000, - "data": { - "id": "resp_abc123" - } - } - WebhookResponseCompleted: - type: object - title: response.completed - description: | - Sent when a background response has been completed. + enum: [thread.deleted] required: - - created_at - id - - data - - type + - object + - deleted + + ListThreadsResponse: properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the model response was completed. - id: + object: type: string - description: | - The unique ID of the event. + example: "list" data: - type: object - description: | - Event data payload. - required: - - id - properties: - id: - type: string - description: | - The unique ID of the model response. - object: + type: array + items: + $ref: "#/components/schemas/ThreadObject" + first_id: type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: + example: "asst_abc123" + last_id: type: string - description: | - The type of the event. Always `response.completed`. - enum: - - response.completed - x-stainless-const: true - x-oaiMeta: - name: response.completed - group: webhook-events - example: | - { - "id": "evt_abc123", - "type": "response.completed", - "created_at": 1719168000, - "data": { - "id": "resp_abc123" - } - } - WebhookResponseFailed: - type: object - title: response.failed - description: | - Sent when a background response has failed. + example: "asst_abc456" + has_more: + type: boolean + example: false required: - - created_at - - id + - object - data - - type + - first_id + - last_id + - has_more + + MessageObject: + type: object + title: The message object + description: Represents a message within a [thread](/docs/api-reference/threads). properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.message`. + type: string + enum: ["thread.message"] created_at: + description: The Unix timestamp (in seconds) for when the message was created. type: integer - description: | - The Unix timestamp (in seconds) of when the model response failed. - id: + thread_id: + description: The [thread](/docs/api-reference/threads) ID that this message belongs to. type: string - description: | - The unique ID of the event. - data: + status: + description: The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. + type: string + enum: ["in_progress", "incomplete", "completed"] + incomplete_details: + description: On an incomplete message, details about why the message is incomplete. type: object - description: | - Event data payload. - required: - - id properties: - id: + reason: type: string - description: | - The unique ID of the model response. - object: + description: The reason the message is incomplete. + enum: + [ + "content_filter", + "max_tokens", + "run_cancelled", + "run_expired", + "run_failed", + ] + nullable: true + required: + - reason + completed_at: + description: The Unix timestamp (in seconds) for when the message was completed. + type: integer + nullable: true + incomplete_at: + description: The Unix timestamp (in seconds) for when the message was marked as incomplete. + type: integer + nullable: true + role: + description: The entity that produced the message. One of `user` or `assistant`. type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: + enum: ["user", "assistant"] + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageContentImageFileObject" + - $ref: "#/components/schemas/MessageContentImageUrlObject" + - $ref: "#/components/schemas/MessageContentTextObject" + - $ref: "#/components/schemas/MessageContentRefusalObject" + x-oaiExpandable: true + assistant_id: + description: If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message. type: string - description: | - The type of the event. Always `response.failed`. - enum: - - response.failed - x-stainless-const: true + nullable: true + run_id: + description: The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints. + type: string + nullable: true + attachments: + type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearchTypeOnly" + x-oaiExpandable: true + description: A list of files attached to the message, and the tools they were added to. + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - created_at + - thread_id + - status + - incomplete_details + - completed_at + - incomplete_at + - role + - content + - assistant_id + - run_id + - attachments + - metadata x-oaiMeta: - name: response.failed - group: webhook-events + name: The message object + beta: true example: | { - "id": "evt_abc123", - "type": "response.failed", - "created_at": 1719168000, - "data": { - "id": "resp_abc123" - } + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1698983503, + "thread_id": "thread_abc123", + "role": "assistant", + "content": [ + { + "type": "text", + "text": { + "value": "Hi! How can I help you today?", + "annotations": [] + } + } + ], + "assistant_id": "asst_abc123", + "run_id": "run_abc123", + "attachments": [], + "metadata": {} } - WebhookResponseIncomplete: + + MessageDeltaObject: type: object - title: response.incomplete + title: Message delta object description: | - Sent when a background response has been interrupted. - required: - - created_at - - id - - data - - type - properties: - created_at: - type: integer - description: | - The Unix timestamp (in seconds) of when the model response was interrupted. + Represents a message delta i.e. any changed fields on a message during streaming. + properties: id: + description: The identifier of the message, which can be referenced in API endpoints. type: string - description: | - The unique ID of the event. - data: + object: + description: The object type, which is always `thread.message.delta`. + type: string + enum: ["thread.message.delta"] + delta: + description: The delta containing the fields that have changed on the Message. type: object - description: | - Event data payload. - required: - - id properties: - id: + role: + description: The entity that produced the message. One of `user` or `assistant`. type: string - description: | - The unique ID of the model response. - object: - type: string - description: | - The object of the event. Always `event`. - enum: - - event - x-stainless-const: true - type: - type: string - description: | - The type of the event. Always `response.incomplete`. - enum: - - response.incomplete - x-stainless-const: true + enum: ["user", "assistant"] + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageDeltaContentImageFileObject" + - $ref: "#/components/schemas/MessageDeltaContentTextObject" + - $ref: "#/components/schemas/MessageDeltaContentRefusalObject" + - $ref: "#/components/schemas/MessageDeltaContentImageUrlObject" + x-oaiExpandable: true + required: + - id + - object + - delta x-oaiMeta: - name: response.incomplete - group: webhook-events + name: The message delta object + beta: true example: | { - "id": "evt_abc123", - "type": "response.incomplete", - "created_at": 1719168000, - "data": { - "id": "resp_abc123" + "id": "msg_123", + "object": "thread.message.delta", + "delta": { + "content": [ + { + "index": 0, + "type": "text", + "text": { "value": "Hello", "annotations": [] } + } + ] } } - IncludeEnum: - type: string - enum: - - file_search_call.results - - web_search_call.results - - web_search_call.action.sources - - message.input_image.image_url - - computer_call_output.output.image_url - - code_interpreter_call.outputs - - reasoning.encrypted_content - - message.output_text.logprobs - description: >- - 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 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. + CreateMessageRequest: + type: object + additionalProperties: false + required: + - role + - content + properties: + role: + type: string + enum: ["user", "assistant"] + description: | + The role of the entity that is creating the message. Allowed values include: + - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. + content: + oneOf: + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models/overview). + title: Array of content parts + items: + oneOf: + - $ref: "#/components/schemas/MessageContentImageFileObject" + - $ref: "#/components/schemas/MessageContentImageUrlObject" + - $ref: "#/components/schemas/MessageRequestContentTextObject" + x-oaiExpandable: true + minItems: 1 + x-oaiExpandable: true + attachments: + type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearchTypeOnly" + x-oaiExpandable: true + description: A list of files attached to the message, and the tools they should be added to. + required: + - file_id + - tools + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true - - `message.output_text.logprobs`: Include logprobs with assistant messages. + ModifyMessageRequest: + type: object + additionalProperties: false + properties: + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true - - `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). - MessageStatus: - type: string - enum: - - in_progress - - completed - - incomplete - MessageRole: - type: string - enum: - - unknown - - user - - assistant - - system - - critic - - discriminator - - developer - - tool - InputTextContent: + DeleteMessageResponse: + type: object properties: - type: + id: type: string - enum: - - input_text - description: The type of the input item. Always `input_text`. - default: input_text - x-stainless-const: true - text: + deleted: + type: boolean + object: type: string - description: The text input to the model. - type: object + enum: [thread.message.deleted] required: - - type - - text - title: Input text - description: A text input to the model. - FileCitationBody: + - id + - object + - deleted + + ListMessagesResponse: properties: - type: + object: type: string - enum: - - file_citation - description: The type of the file citation. Always `file_citation`. - default: file_citation - x-stainless-const: true - file_id: + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/MessageObject" + first_id: type: string - description: The ID of the file. - index: - type: integer - description: The index of the file in the list of files. - filename: + example: "msg_abc123" + last_id: type: string - description: The filename of the file cited. - type: object + example: "msg_abc123" + has_more: + type: boolean + example: false required: - - type - - file_id - - index - - filename - title: File citation - description: A citation to a file. - UrlCitationBody: + - object + - data + - first_id + - last_id + - has_more + + MessageContentImageFileObject: + title: Image file + type: object + description: References an image [File](/docs/api-reference/files) in the content of a message. properties: type: + description: Always `image_file`. type: string - enum: - - url_citation - description: The type of the URL citation. Always `url_citation`. - default: url_citation - x-stainless-const: true - url: - type: string - description: The URL of the web resource. - start_index: - type: integer - description: The index of the first character of the URL citation in the message. - end_index: - type: integer - description: The index of the last character of the URL citation in the message. - title: - type: string - description: The title of the web resource. - type: object + enum: ["image_file"] + image_file: + type: object + properties: + file_id: + description: The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. + type: string + detail: + type: string + description: Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. + enum: ["auto", "low", "high"] + default: "auto" + required: + - file_id required: - type - - url - - start_index - - end_index - - title - title: URL citation - description: A citation for a web resource used to generate a model response. - ContainerFileCitationBody: + - image_file + + MessageDeltaContentImageFileObject: + title: Image file + type: object + description: References an image [File](/docs/api-reference/files) in the content of a message. properties: - type: - type: string - enum: - - container_file_citation - description: The type of the container file citation. Always `container_file_citation`. - default: container_file_citation - x-stainless-const: true - container_id: - type: string - description: The ID of the container file. - file_id: - type: string - description: The ID of the file. - start_index: - type: integer - description: The index of the first character of the container file citation in the message. - end_index: + index: type: integer - description: The index of the last character of the container file citation in the message. - filename: + description: The index of the content part in the message. + type: + description: Always `image_file`. type: string - description: The filename of the container file cited. - type: object + enum: ["image_file"] + image_file: + type: object + properties: + file_id: + description: The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. + type: string + detail: + type: string + description: Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. + enum: ["auto", "low", "high"] + default: "auto" required: + - index - type - - container_id - - file_id - - start_index - - end_index - - filename - title: Container file citation - description: A citation for a container file used to generate a model response. - Annotation: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/FileCitationBody' - - $ref: '#/components/schemas/UrlCitationBody' - - $ref: '#/components/schemas/ContainerFileCitationBody' - - $ref: '#/components/schemas/FilePath' - TopLogProb: + + MessageContentImageUrlObject: + title: Image URL + type: object + description: References an image URL in the content of a message. properties: - token: + type: type: string - logprob: - type: number - bytes: - items: - type: integer - type: array - type: object + enum: ["image_url"] + description: The type of the content part. + image_url: + type: object + properties: + url: + type: string + description: "The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." + format: uri + detail: + type: string + description: Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto` + enum: ["auto", "low", "high"] + default: "auto" + required: + - url required: - - token - - logprob - - bytes - title: Top log probability - description: The top log probability of a token. - LogProb: + - type + - image_url + + MessageDeltaContentImageUrlObject: + title: Image URL + type: object + description: References an image URL in the content of a message. properties: - token: + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `image_url`. type: string - logprob: - type: number - bytes: - items: - type: integer - type: array - top_logprobs: - items: - $ref: '#/components/schemas/TopLogProb' - type: array - type: object + enum: ["image_url"] + image_url: + type: object + properties: + url: + description: "The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." + type: string + detail: + type: string + description: Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. + enum: ["auto", "low", "high"] + default: "auto" required: - - token - - logprob - - bytes - - top_logprobs - title: Log probability - description: The log probability of a token. - OutputTextContent: + - index + - type + + MessageContentTextObject: + title: Text + type: object + description: The text content that is part of a message. properties: type: + description: Always `text`. type: string - enum: - - output_text - description: The type of the output text. Always `output_text`. - default: output_text - x-stainless-const: true + enum: ["text"] text: - type: string - description: The text output from the model. - annotations: - items: - $ref: '#/components/schemas/Annotation' - type: array - description: The annotations of the text output. - logprobs: - items: - $ref: '#/components/schemas/LogProb' - type: array - type: object + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageContentTextAnnotationsFileCitationObject" + - $ref: "#/components/schemas/MessageContentTextAnnotationsFilePathObject" + x-oaiExpandable: true + required: + - value + - annotations required: - type - text - - annotations - title: Output text - description: A text output from the model. - TextContent: + + MessageContentRefusalObject: + title: Refusal + type: object + description: The refusal content generated by the assistant. properties: type: + description: Always `refusal`. type: string - enum: - - text - default: text - x-stainless-const: true - text: + enum: ["refusal"] + refusal: type: string - type: object + nullable: false required: - type - - text - title: Text Content - description: A text content. - SummaryTextContent: + - refusal + + MessageRequestContentTextObject: + title: Text + type: object + description: The text content that is part of a message. properties: type: + description: Always `text`. type: string - enum: - - summary_text - description: The type of the object. Always `summary_text`. - default: summary_text - x-stainless-const: true + enum: ["text"] text: type: string - description: A summary of the reasoning output from the model so far. - type: object + description: Text content to be sent to the model required: - type - text - title: Summary text - description: A summary text from the model. - ReasoningTextContent: + + MessageContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. properties: type: + description: Always `file_citation`. type: string - enum: - - reasoning_text - description: The type of the reasoning text. Always `reasoning_text`. - default: reasoning_text - x-stainless-const: true + enum: ["file_citation"] text: + description: The text in the message content that needs to be replaced. type: string - description: The reasoning text from the model. - type: object + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 required: - type - text - title: ReasoningTextContent - description: Reasoning text from the model. - RefusalContent: + - file_citation + - start_index + - end_index + + MessageContentTextAnnotationsFilePathObject: + title: File path + type: object + description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. properties: type: + description: Always `file_path`. type: string - enum: - - refusal - description: The type of the refusal. Always `refusal`. - default: refusal - x-stainless-const: true - refusal: + enum: ["file_path"] + text: + description: The text in the message content that needs to be replaced. type: string - description: The refusal explanation from the model. - type: object + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 required: - type - - refusal - title: Refusal - description: A refusal from the model. - ImageDetail: - type: string - enum: - - low - - high - - auto - InputImageContent: - properties: - type: - type: string - enum: - - input_image - description: The type of the input item. Always `input_image`. - default: input_image - x-stainless-const: true - image_url: - anyOf: - - type: string - description: >- - The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in - a data URL. - - type: 'null' - file_id: - anyOf: - - type: string - description: The ID of the file to be sent to the model. - - type: 'null' - detail: - $ref: '#/components/schemas/ImageDetail' - description: >- - The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults - to `auto`. + - text + - file_path + - start_index + - end_index + + MessageDeltaContentTextObject: + title: Text type: object - required: - - type - - detail - title: Input image - description: >- - An image input to the model. Learn about [image - inputs](https://platform.openai.com/docs/guides/vision). - ComputerScreenshotContent: + description: The text content that is part of a message. properties: + index: + type: integer + description: The index of the content part in the message. type: + description: Always `text`. type: string - enum: - - computer_screenshot - description: >- - Specifies the event type. For a computer screenshot, this property is always set to - `computer_screenshot`. - default: computer_screenshot - x-stainless-const: true - image_url: - anyOf: - - type: string - description: The URL of the screenshot image. - - type: 'null' - file_id: - anyOf: - - type: string - description: The identifier of an uploaded file that contains the screenshot. - - type: 'null' - type: object + enum: ["text"] + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject" + - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject" + x-oaiExpandable: true required: + - index - type - - image_url - - file_id - title: Computer screenshot - description: A screenshot of a computer. - InputFileContent: + + MessageDeltaContentRefusalObject: + title: Refusal + type: object + description: The refusal content that is part of a message. properties: + index: + type: integer + description: The index of the refusal part in the message. type: + description: Always `refusal`. type: string - enum: - - input_file - description: The type of the input item. Always `input_file`. - default: input_file - x-stainless-const: true - file_id: - anyOf: - - type: string - description: The ID of the file to be sent to the model. - - type: 'null' - filename: - type: string - description: The name of the file to be sent to the model. - file_url: - type: string - description: The URL of the file to be sent to the model. - file_data: + enum: ["refusal"] + refusal: type: string - description: | - The content of the file to be sent to the model. - type: object required: + - index - type - title: Input file - description: A file input to the model. - Message: + + MessageDeltaContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. properties: + index: + type: integer + description: The index of the annotation in the text content part. type: + description: Always `file_citation`. type: string - enum: - - message - description: The type of the message. Always set to `message`. - default: message - x-stainless-const: true - id: + enum: ["file_citation"] + text: + description: The text in the message content that needs to be replaced. type: string - description: The unique ID of the message. - status: - $ref: '#/components/schemas/MessageStatus' - description: >- - The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are - returned via API. - role: - $ref: '#/components/schemas/MessageRole' - description: >- - The role of the message. One of `unknown`, `user`, `assistant`, `system`, `critic`, - `discriminator`, `developer`, or `tool`. - content: - items: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/InputTextContent' - - $ref: '#/components/schemas/OutputTextContent' - - $ref: '#/components/schemas/TextContent' - - $ref: '#/components/schemas/SummaryTextContent' - - $ref: '#/components/schemas/ReasoningTextContent' - - $ref: '#/components/schemas/RefusalContent' - - $ref: '#/components/schemas/InputImageContent' - - $ref: '#/components/schemas/ComputerScreenshotContent' - - $ref: '#/components/schemas/InputFileContent' - type: array - description: The content of the message - type: object + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + quote: + description: The specific quote in the file. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 required: + - index - type - - id - - status - - role - - content - title: Message - description: A message to or from the model. - ClickButtonType: - type: string - enum: - - left - - right - - wheel - - back - - forward - ClickParam: + + MessageDeltaContentTextAnnotationsFilePathObject: + title: File path + type: object + description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. properties: + index: + type: integer + description: The index of the annotation in the text content part. type: + description: Always `file_path`. type: string - enum: - - click - description: Specifies the event type. For a click action, this property is always `click`. - default: click - x-stainless-const: true - button: - $ref: '#/components/schemas/ClickButtonType' - description: >- - Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, - `back`, or `forward`. - x: + enum: ["file_path"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + start_index: type: integer - description: The x-coordinate where the click occurred. - 'y': + minimum: 0 + end_index: type: integer - description: The y-coordinate where the click occurred. - type: object + minimum: 0 required: + - index - type - - button - - x - - 'y' - title: Click - description: A click action. - DoubleClickAction: + + RunStepObject: + type: object + title: Run steps + description: | + Represents a step in execution of a run. properties: + id: + description: The identifier of the run step, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run.step`. + type: string + enum: ["thread.run.step"] + created_at: + description: The Unix timestamp (in seconds) for when the run step was created. + type: integer + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) associated with the run step. + type: string + thread_id: + description: The ID of the [thread](/docs/api-reference/threads) that was run. + type: string + run_id: + description: The ID of the [run](/docs/api-reference/runs) that this run step is a part of. + type: string type: + description: The type of run step, which can be either `message_creation` or `tool_calls`. type: string - enum: - - double_click - description: >- - Specifies the event type. For a double click action, this property is always set to - `double_click`. - default: double_click - x-stainless-const: true - x: + enum: ["message_creation", "tool_calls"] + status: + description: The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`. + type: string + enum: ["in_progress", "cancelled", "failed", "completed", "expired"] + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: "#/components/schemas/RunStepDetailsMessageCreationObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsObject" + x-oaiExpandable: true + last_error: + type: object + description: The last error associated with this run step. Will be `null` if there are no errors. + nullable: true + properties: + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: ["server_error", "rate_limit_exceeded"] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + expired_at: + description: The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. type: integer - description: The x-coordinate where the double click occurred. - 'y': + nullable: true + cancelled_at: + description: The Unix timestamp (in seconds) for when the run step was cancelled. type: integer - description: The y-coordinate where the double click occurred. - type: object - required: - - type - - x - - 'y' - title: DoubleClick - description: A double click action. - DragPoint: - properties: - x: + nullable: true + failed_at: + description: The Unix timestamp (in seconds) for when the run step failed. type: integer - description: The x-coordinate. - 'y': + nullable: true + completed_at: + description: The Unix timestamp (in seconds) for when the run step completed. type: integer - description: The y-coordinate. - type: object - required: - - x - - 'y' - title: Coordinate - description: 'An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`.' - KeyPressAction: - properties: - type: - type: string - enum: - - keypress - description: Specifies the event type. For a keypress action, this property is always set to `keypress`. - default: keypress - x-stainless-const: true - keys: - items: - type: string - description: One of the keys the model is requesting to be pressed. - type: array - description: >- - The combination of keys the model is requesting to be pressed. This is an array of strings, each - representing a key. - type: object + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + usage: + $ref: "#/components/schemas/RunStepCompletionUsage" required: + - id + - object + - created_at + - assistant_id + - thread_id + - run_id - type - - keys - title: KeyPress - description: A collection of keypresses the model would like to perform. - ComputerCallSafetyCheckParam: + - status + - step_details + - last_error + - expired_at + - cancelled_at + - failed_at + - completed_at + - metadata + - usage + x-oaiMeta: + name: The run step object + beta: true + example: *run_step_object_example + + RunStepDeltaObject: + type: object + title: Run step delta object + description: | + Represents a run step delta i.e. any changed fields on a run step during streaming. properties: id: + description: The identifier of the run step, which can be referenced in API endpoints. type: string - description: The ID of the pending safety check. - code: - anyOf: - - type: string - description: The type of the pending safety check. - - type: 'null' - message: - anyOf: - - type: string - description: Details about the pending safety check. - - type: 'null' - type: object + object: + description: The object type, which is always `thread.run.step.delta`. + type: string + enum: ["thread.run.step.delta"] + delta: + description: The delta containing the fields that have changed on the run step. + type: object + properties: + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsObject" + x-oaiExpandable: true required: - id - description: A pending safety check for the computer call. - CodeInterpreterOutputLogs: + - object + - delta + x-oaiMeta: + name: The run step delta object + beta: true + example: | + { + "id": "step_123", + "object": "thread.run.step.delta", + "delta": { + "step_details": { + "type": "tool_calls", + "tool_calls": [ + { + "index": 0, + "id": "call_123", + "type": "code_interpreter", + "code_interpreter": { "input": "", "outputs": [] } + } + ] + } + } + } + + ListRunStepsResponse: properties: - type: + object: type: string - enum: - - logs - description: The type of the output. Always `logs`. - default: logs - x-stainless-const: true - logs: + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/RunStepObject" + first_id: type: string - description: The logs output from the code interpreter. - type: object + example: "step_abc123" + last_id: + type: string + example: "step_abc456" + has_more: + type: boolean + example: false required: - - type - - logs - title: Code interpreter output logs - description: The logs output from the code interpreter. - CodeInterpreterOutputImage: + - object + - data + - first_id + - last_id + - has_more + + RunStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. properties: type: + description: Always `message_creation`. type: string - enum: - - image - description: The type of the output. Always `image`. - default: image - x-stainless-const: true - url: - type: string - description: The URL of the image output from the code interpreter. - type: object + enum: ["message_creation"] + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - message_id required: - type - - url - title: Code interpreter output image - description: The image output from the code interpreter. - LocalShellExecAction: + - message_creation + + RunStepDeltaStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. properties: type: + description: Always `message_creation`. type: string - enum: - - exec - description: The type of the local shell action. Always `exec`. - default: exec - x-stainless-const: true - command: - items: - type: string - type: array - description: The command to run. - timeout_ms: - anyOf: - - type: integer - description: Optional timeout in milliseconds for the command. - - type: 'null' - working_directory: - anyOf: - - type: string - description: Optional working directory to run the command in. - - type: 'null' - env: - additionalProperties: - type: string + enum: ["message_creation"] + message_creation: type: object - description: Environment variables to set for the command. - x-oaiTypeLabel: map - user: - anyOf: - - type: string - description: Optional user to run the command as. - - type: 'null' - type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. required: - type - - command - - env - title: Local shell exec action - description: Execute a shell command on the server. - FunctionShellAction: - properties: - commands: - items: - type: string - description: A list of commands to run. - type: array - timeout_ms: - anyOf: - - type: integer - description: Optional timeout in milliseconds for the commands. - - type: 'null' - max_output_length: - anyOf: - - type: integer - description: Optional maximum number of characters to return from each command. - - type: 'null' + + RunStepDetailsToolCallsObject: + title: Tool calls type: object - required: - - commands - - timeout_ms - - max_output_length - title: Shell exec action - description: Execute a shell command. - LocalShellCallStatus: - type: string - enum: - - in_progress - - completed - - incomplete - FunctionShellCall: + description: Details of the tool call. properties: type: + description: Always `tool_calls`. type: string - enum: - - shell_call - description: The type of the item. Always `shell_call`. - default: shell_call - x-stainless-const: true - id: - type: string - description: The unique ID of the function shell tool call. Populated when this item is returned via API. - call_id: - type: string - description: The unique ID of the function shell tool call generated by the model. - action: - $ref: '#/components/schemas/FunctionShellAction' - description: The shell commands and limits that describe how to run the tool call. - status: - $ref: '#/components/schemas/LocalShellCallStatus' - description: The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. - created_by: - type: string - description: The ID of the entity that created this tool call. - type: object + enum: ["tool_calls"] + tool_calls: + type: array + description: | + An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + items: + oneOf: + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsFileSearchObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsFunctionObject" + x-oaiExpandable: true required: - type - - id - - call_id - - action - - status - title: Function shell tool call - description: A tool call that executes one or more shell commands in a managed environment. - FunctionShellCallOutputTimeoutOutcome: + - tool_calls + + RunStepDeltaStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. properties: type: + description: Always `tool_calls`. type: string - enum: - - timeout - description: The outcome type. Always `timeout`. - default: timeout - x-stainless-const: true - type: object + enum: ["tool_calls"] + tool_calls: + type: array + description: | + An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + items: + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject" + x-oaiExpandable: true required: - type - title: Function shell timeout outcome - description: Indicates that the function shell call exceeded its configured time limit. - FunctionShellCallOutputExitOutcome: + + RunStepDetailsToolCallsCodeObject: + title: Code Interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. properties: + id: + type: string + description: The ID of the tool call. type: type: string - enum: - - exit - description: The outcome type. Always `exit`. - default: exit - x-stainless-const: true - exit_code: - type: integer - description: Exit code from the shell process. - type: object + description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. + enum: ["code_interpreter"] + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + required: + - input + - outputs + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. + items: + type: object + oneOf: + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject" + x-oaiExpandable: true required: + - id - type - - exit_code - title: Function shell exit outcome - description: Indicates that the shell commands finished and returned an exit code. - FunctionShellCallOutputContent: - properties: - stdout: - type: string - stderr: - type: string - outcome: - title: Function shell call outcome - description: >- - Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output - chunk. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/FunctionShellCallOutputTimeoutOutcome' - - $ref: '#/components/schemas/FunctionShellCallOutputExitOutcome' - created_by: - type: string + - code_interpreter + + RunStepDeltaStepDetailsToolCallsCodeObject: + title: Code interpreter tool call type: object - required: - - stdout - - stderr - - outcome - title: Shell call output content - description: The content of a shell call output. - FunctionShellCallOutput: + description: Details of the Code Interpreter tool call the run step was involved in. properties: - type: - type: string - enum: - - shell_call_output - description: The type of the shell call output. Always `shell_call_output`. - default: shell_call_output - x-stainless-const: true + index: + type: integer + description: The index of the tool call in the tool calls array. id: type: string - description: The unique ID of the shell call output. Populated when this item is returned via API. - call_id: - type: string - description: The unique ID of the shell tool call generated by the model. - output: - items: - $ref: '#/components/schemas/FunctionShellCallOutputContent' - type: array - description: An array of shell call output contents - max_output_length: - anyOf: - - type: integer - description: >- - The maximum length of the shell command output. This is generated by the model and should be - passed back with the raw output. - - type: 'null' - created_by: - type: string - type: object - required: - - type - - id - - call_id - - output - - max_output_length - title: Shell call output - description: The output of a shell tool call. - ApplyPatchCallStatus: - type: string - enum: - - in_progress - - completed - ApplyPatchCreateFileOperation: - properties: + description: The ID of the tool call. type: type: string - enum: - - create_file - description: Create a new file with the provided diff. - default: create_file - x-stainless-const: true - path: - type: string - description: Path of the file to create. - diff: - type: string - description: Diff to apply. - type: object + description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. + enum: ["code_interpreter"] + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. + items: + type: object + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject" + x-oaiExpandable: true required: + - index - type - - path - - diff - title: Apply patch create file operation - description: Instruction describing how to create a file via the apply_patch tool. - ApplyPatchDeleteFileOperation: + + RunStepDetailsToolCallsCodeOutputLogsObject: + title: Code Interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. properties: type: + description: Always `logs`. type: string - enum: - - delete_file - description: Delete the specified file. - default: delete_file - x-stainless-const: true - path: + enum: ["logs"] + logs: type: string - description: Path of the file to delete. - type: object + description: The text output from the Code Interpreter tool call. required: - type - - path - title: Apply patch delete file operation - description: Instruction describing how to delete a file via the apply_patch tool. - ApplyPatchUpdateFileOperation: + - logs + + RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: + title: Code interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. properties: + index: + type: integer + description: The index of the output in the outputs array. type: + description: Always `logs`. type: string - enum: - - update_file - description: Update an existing file with the provided diff. - default: update_file - x-stainless-const: true - path: - type: string - description: Path of the file to update. - diff: + enum: ["logs"] + logs: type: string - description: Diff to apply. - type: object + description: The text output from the Code Interpreter tool call. required: + - index - type - - path - - diff - title: Apply patch update file operation - description: Instruction describing how to update a file via the apply_patch tool. - ApplyPatchToolCall: + + RunStepDetailsToolCallsCodeOutputImageObject: + title: Code Interpreter image output + type: object properties: type: + description: Always `image`. type: string - enum: - - apply_patch_call - description: The type of the item. Always `apply_patch_call`. - default: apply_patch_call - x-stainless-const: true - id: - type: string - description: The unique ID of the apply patch tool call. Populated when this item is returned via API. - call_id: - type: string - description: The unique ID of the apply patch tool call generated by the model. - status: - $ref: '#/components/schemas/ApplyPatchCallStatus' - description: The status of the apply patch tool call. One of `in_progress` or `completed`. - operation: - title: Apply patch operation - description: One of the create_file, delete_file, or update_file operations applied via apply_patch. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ApplyPatchCreateFileOperation' - - $ref: '#/components/schemas/ApplyPatchDeleteFileOperation' - - $ref: '#/components/schemas/ApplyPatchUpdateFileOperation' - created_by: - type: string - description: The ID of the entity that created this tool call. - type: object + enum: ["image"] + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - file_id required: - type - - id - - call_id - - status - - operation - title: Apply patch tool call - description: A tool call that applies file diffs by creating, deleting, or updating files. - ApplyPatchCallOutputStatus: - type: string - enum: - - completed - - failed - ApplyPatchToolCallOutput: + - image + + RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: + title: Code interpreter image output + type: object properties: + index: + type: integer + description: The index of the output in the outputs array. type: + description: Always `image`. type: string - enum: - - apply_patch_call_output - description: The type of the item. Always `apply_patch_call_output`. - default: apply_patch_call_output - x-stainless-const: true - id: - type: string - description: The unique ID of the apply patch tool call output. Populated when this item is returned via API. - call_id: - type: string - description: The unique ID of the apply patch tool call generated by the model. - status: - $ref: '#/components/schemas/ApplyPatchCallOutputStatus' - description: The status of the apply patch tool call output. One of `completed` or `failed`. - output: - anyOf: - - type: string - description: Optional textual output returned by the apply patch tool. - - type: 'null' - created_by: - type: string - description: The ID of the entity that created this tool call output. - type: object + enum: ["image"] + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string required: + - index - type - - id - - call_id - - status - title: Apply patch tool call output - description: The output emitted by an apply patch tool call. - MCPToolCallStatus: - type: string - enum: - - in_progress - - completed - - incomplete - - calling - - failed - DetailEnum: - type: string - enum: - - low - - high - - auto - FunctionCallItemStatus: - type: string - enum: - - in_progress - - completed - - incomplete - ComputerCallOutputItemParam: + + RunStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object properties: id: - anyOf: - - type: string - description: The ID of the computer tool call output. - example: cuo_123 - - type: 'null' - call_id: type: string - maxLength: 64 - minLength: 1 - description: The ID of the computer tool call that produced the output. + description: The ID of the tool call object. type: type: string - enum: - - computer_call_output - description: The type of the computer tool call output. Always `computer_call_output`. - default: computer_call_output - x-stainless-const: true - output: - $ref: '#/components/schemas/ComputerScreenshotImage' - acknowledged_safety_checks: - anyOf: - - items: - $ref: '#/components/schemas/ComputerCallSafetyCheckParam' - type: array - description: The safety checks reported by the API that have been acknowledged by the developer. - - type: 'null' - status: - anyOf: - - $ref: '#/components/schemas/FunctionCallItemStatus' - description: >- - The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated - when input items are returned via API. - - type: 'null' - type: object + description: The type of tool call. This is always going to be `file_search` for this type of tool call. + enum: ["file_search"] + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map required: - - call_id + - id - type - - output - title: Computer tool call output - description: The output of a computer tool call. - InputTextContentParam: - properties: - type: - type: string - enum: - - input_text - description: The type of the input item. Always `input_text`. - default: input_text - x-stainless-const: true - text: - type: string - maxLength: 10485760 - description: The text input to the model. + - file_search + + RunStepDeltaStepDetailsToolCallsFileSearchObject: + title: File search tool call type: object - required: - - type - - text - title: Input text - description: A text input to the model. - InputImageContentParamAutoParam: properties: - type: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: type: string - enum: - - input_image - description: The type of the input item. Always `input_image`. - default: input_image - x-stainless-const: true - image_url: - anyOf: - - type: string - maxLength: 20971520 - description: >- - The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in - a data URL. - - type: 'null' - file_id: - anyOf: - - type: string - description: The ID of the file to be sent to the model. - example: file-123 - - type: 'null' - detail: - anyOf: - - $ref: '#/components/schemas/DetailEnum' - description: >- - The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. - Defaults to `auto`. - - type: 'null' - type: object - required: - - type - title: Input image - description: >- - An image input to the model. Learn about [image - inputs](https://platform.openai.com/docs/guides/vision) - InputFileContentParam: - properties: + description: The ID of the tool call object. type: type: string - enum: - - input_file - description: The type of the input item. Always `input_file`. - default: input_file - x-stainless-const: true - file_id: - anyOf: - - type: string - description: The ID of the file to be sent to the model. - example: file-123 - - type: 'null' - filename: - anyOf: - - type: string - description: The name of the file to be sent to the model. - - type: 'null' - file_data: - anyOf: - - type: string - maxLength: 33554432 - description: The base64-encoded data of the file to be sent to the model. - - type: 'null' - file_url: - anyOf: - - type: string - description: The URL of the file to be sent to the model. - - type: 'null' - type: object + description: The type of tool call. This is always going to be `file_search` for this type of tool call. + enum: ["file_search"] + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map required: + - index - type - title: Input file - description: A file input to the model. - FunctionCallOutputItemParam: + - file_search + + RunStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call properties: id: - anyOf: - - type: string - description: The unique ID of the function tool call output. Populated when this item is returned via API. - example: fc_123 - - type: 'null' - call_id: type: string - maxLength: 64 - minLength: 1 - description: The unique ID of the function tool call generated by the model. + description: The ID of the tool call object. type: type: string - enum: - - function_call_output - description: The type of the function tool call output. Always `function_call_output`. - default: function_call_output - x-stainless-const: true - output: - description: Text, image, or file output of the function tool call. - anyOf: - - type: string - maxLength: 10485760 - description: A JSON string of the output of the function tool call. - - items: - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/InputTextContentParam' - - $ref: '#/components/schemas/InputImageContentParamAutoParam' - - $ref: '#/components/schemas/InputFileContentParam' - type: array - status: - anyOf: - - $ref: '#/components/schemas/FunctionCallItemStatus' - description: >- - The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when - items are returned via API. - - type: 'null' - type: object + description: The type of tool call. This is always going to be `function` for this type of tool call. + enum: ["function"] + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + type: string + description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + nullable: true + required: + - name + - arguments + - output required: - - call_id + - id - type - - output - title: Function tool call output - description: The output of a function tool call. - FunctionShellActionParam: - properties: - commands: - items: - type: string - type: array - description: Ordered shell commands for the execution environment to run. - timeout_ms: - anyOf: - - type: integer - description: Maximum wall-clock time in milliseconds to allow the shell commands to run. - - type: 'null' - max_output_length: - anyOf: - - type: integer - description: Maximum number of UTF-8 characters to capture from combined stdout and stderr output. - - type: 'null' + - function + + RunStepDeltaStepDetailsToolCallsFunctionObject: type: object - required: - - commands - title: Function shell action - description: Commands and limits describing how to run the function shell tool call. - FunctionShellCallItemStatus: - type: string - enum: - - in_progress - - completed - - incomplete - title: Function shell call status - description: Status values reported for function shell tool calls. - FunctionShellCallItemParam: + title: Function tool call properties: + index: + type: integer + description: The index of the tool call in the tool calls array. id: - anyOf: - - type: string - description: The unique ID of the function shell tool call. Populated when this item is returned via API. - example: sh_123 - - type: 'null' - call_id: type: string - maxLength: 64 - minLength: 1 - description: The unique ID of the function shell tool call generated by the model. + description: The ID of the tool call object. type: type: string - enum: - - shell_call - description: The type of the item. Always `function_shell_call`. - default: shell_call - x-stainless-const: true - action: - $ref: '#/components/schemas/FunctionShellActionParam' - description: The shell commands and limits that describe how to run the tool call. - status: - anyOf: - - $ref: '#/components/schemas/FunctionShellCallItemStatus' - description: The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. - - type: 'null' - type: object + description: The type of tool call. This is always going to be `function` for this type of tool call. + enum: ["function"] + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + type: string + description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + nullable: true required: - - call_id + - index - type - - action - title: Function shell tool call - description: A tool representing a request to execute one or more shell commands. - FunctionShellCallOutputTimeoutOutcomeParam: - properties: - type: - type: string - enum: - - timeout - description: The outcome type. Always `timeout`. - default: timeout - x-stainless-const: true + + VectorStoreExpirationAfter: type: object - required: - - type - title: Function shell timeout outcome - description: Indicates that the function shell call exceeded its configured time limit. - FunctionShellCallOutputExitOutcomeParam: + title: Vector store expiration policy + description: The expiration policy for a vector store. properties: - type: + anchor: + description: "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." type: string - enum: - - exit - description: The outcome type. Always `exit`. - default: exit - x-stainless-const: true - exit_code: + enum: ["last_active_at"] + days: + description: The number of days after the anchor time that the vector store will expire. type: integer - description: The exit code returned by the shell process. - type: object + minimum: 1 + maximum: 365 required: - - type - - exit_code - title: Function shell exit outcome - description: Indicates that the shell commands finished and returned an exit code. - FunctionShellCallOutputOutcomeParam: - title: Function shell call outcome - description: The exit or timeout outcome associated with this chunk. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam' - - $ref: '#/components/schemas/FunctionShellCallOutputExitOutcomeParam' - FunctionShellCallOutputContentParam: - properties: - stdout: - type: string - maxLength: 10485760 - description: Captured stdout output for this chunk of the shell call. - stderr: - type: string - maxLength: 10485760 - description: Captured stderr output for this chunk of the shell call. - outcome: - $ref: '#/components/schemas/FunctionShellCallOutputOutcomeParam' - description: The exit or timeout outcome associated with this chunk. + - anchor + - days + + VectorStoreObject: type: object - required: - - stdout - - stderr - - outcome - title: Function shell output chunk - description: Captured stdout and stderr for a portion of a function shell tool call output. - FunctionShellCallOutputItemParam: + title: Vector store + description: A vector store is a collection of processed files can be used by the `file_search` tool. properties: id: - anyOf: - - type: string - description: >- - The unique ID of the function shell tool call output. Populated when this item is returned via - API. - example: sho_123 - - type: 'null' - call_id: - type: string - maxLength: 64 - minLength: 1 - description: The unique ID of the function shell tool call generated by the model. - type: + description: The identifier, which can be referenced in API endpoints. type: string - enum: - - shell_call_output - description: The type of the item. Always `function_shell_call_output`. - default: shell_call_output - x-stainless-const: true - output: - items: - $ref: '#/components/schemas/FunctionShellCallOutputContentParam' - type: array - description: Captured chunks of stdout and stderr output, along with their associated outcomes. - max_output_length: - anyOf: - - type: integer - description: The maximum number of UTF-8 characters captured for this shell call's combined output. - - type: 'null' - type: object - required: - - call_id - - type - - output - title: Function shell tool call output - description: The streamed output items emitted by a function shell tool call. - ApplyPatchCallStatusParam: - type: string - enum: - - in_progress - - completed - title: Apply patch call status - description: Status values reported for apply_patch tool calls. - ApplyPatchCreateFileOperationParam: - properties: - type: + object: + description: The object type, which is always `vector_store`. type: string - enum: - - create_file - description: The operation type. Always `create_file`. - default: create_file - x-stainless-const: true - path: + enum: ["vector_store"] + created_at: + description: The Unix timestamp (in seconds) for when the vector store was created. + type: integer + name: + description: The name of the vector store. type: string - minLength: 1 - description: Path of the file to create relative to the workspace root. - diff: + usage_bytes: + description: The total number of bytes used by the files in the vector store. + type: integer + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been successfully processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that were cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - failed + - cancelled + - total + status: + description: The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. type: string - maxLength: 10485760 - description: Unified diff content to apply when creating the file. - type: object + enum: ["expired", "in_progress", "completed"] + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + expires_at: + description: The Unix timestamp (in seconds) for when the vector store will expire. + type: integer + nullable: true + last_active_at: + description: The Unix timestamp (in seconds) for when the vector store was last active. + type: integer + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true required: - - type - - path - - diff - title: Apply patch create file operation - description: Instruction for creating a new file via the apply_patch tool. - ApplyPatchDeleteFileOperationParam: - properties: - type: - type: string - enum: - - delete_file - description: The operation type. Always `delete_file`. - default: delete_file - x-stainless-const: true - path: - type: string - minLength: 1 - description: Path of the file to delete relative to the workspace root. + - id + - object + - usage_bytes + - created_at + - status + - last_active_at + - name + - file_counts + - metadata + x-oaiMeta: + name: The vector store object + beta: true + example: | + { + "id": "vs_123", + "object": "vector_store", + "created_at": 1698107661, + "usage_bytes": 123456, + "last_active_at": 1698107661, + "name": "my_vector_store", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "cancelled": 0, + "failed": 0, + "total": 100 + }, + "metadata": {}, + "last_used_at": 1698107661 + } + + CreateVectorStoreRequest: type: object - required: - - type - - path - title: Apply patch delete file operation - description: Instruction for deleting an existing file via the apply_patch tool. - ApplyPatchUpdateFileOperationParam: + additionalProperties: false properties: - type: - type: string - enum: - - update_file - description: The operation type. Always `update_file`. - default: update_file - x-stainless-const: true - path: - type: string - minLength: 1 - description: Path of the file to update relative to the workspace root. - diff: + file_ids: + description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + type: array + maxItems: 500 + items: + type: string + name: + description: The name of the vector store. type: string - maxLength: 10485760 - description: Unified diff content to apply to the existing file. + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + chunking_strategy: + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. + oneOf: + - $ref: "#/components/schemas/AutoChunkingStrategyRequestParam" + - $ref: "#/components/schemas/StaticChunkingStrategyRequestParam" + x-oaiExpandable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + UpdateVectorStoreRequest: type: object - required: - - type - - path - - diff - title: Apply patch update file operation - description: Instruction for updating an existing file via the apply_patch tool. - ApplyPatchOperationParam: - title: Apply patch operation - description: One of the create_file, delete_file, or update_file operations supplied to the apply_patch tool. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ApplyPatchCreateFileOperationParam' - - $ref: '#/components/schemas/ApplyPatchDeleteFileOperationParam' - - $ref: '#/components/schemas/ApplyPatchUpdateFileOperationParam' - ApplyPatchToolCallItemParam: + additionalProperties: false properties: - type: - type: string - enum: - - apply_patch_call - description: The type of the item. Always `apply_patch_call`. - default: apply_patch_call - x-stainless-const: true - id: - anyOf: - - type: string - description: The unique ID of the apply patch tool call. Populated when this item is returned via API. - example: apc_123 - - type: 'null' - call_id: + name: + description: The name of the vector store. type: string - maxLength: 64 - minLength: 1 - description: The unique ID of the apply patch tool call generated by the model. - status: - $ref: '#/components/schemas/ApplyPatchCallStatusParam' - description: The status of the apply patch tool call. One of `in_progress` or `completed`. - operation: - $ref: '#/components/schemas/ApplyPatchOperationParam' - description: The specific create, delete, or update instruction for the apply_patch tool call. - type: object - required: - - type - - call_id - - status - - operation - title: Apply patch tool call - description: A tool call representing a request to create, delete, or update files using diff patches. - ApplyPatchCallOutputStatusParam: - type: string - enum: - - completed - - failed - title: Apply patch call output status - description: Outcome values reported for apply_patch tool call outputs. - ApplyPatchToolCallOutputItemParam: + nullable: true + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + ListVectorStoresResponse: properties: - type: + object: type: string - enum: - - apply_patch_call_output - description: The type of the item. Always `apply_patch_call_output`. - default: apply_patch_call_output - x-stainless-const: true - id: - anyOf: - - type: string - description: >- - The unique ID of the apply patch tool call output. Populated when this item is returned via - API. - example: apco_123 - - type: 'null' - call_id: + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/VectorStoreObject" + first_id: type: string - maxLength: 64 - minLength: 1 - description: The unique ID of the apply patch tool call generated by the model. - status: - $ref: '#/components/schemas/ApplyPatchCallOutputStatusParam' - description: The status of the apply patch tool call output. One of `completed` or `failed`. - output: - anyOf: - - type: string - maxLength: 10485760 - description: Optional human-readable log text from the apply patch tool (e.g., patch results or errors). - - type: 'null' - type: object + example: "vs_abc123" + last_id: + type: string + example: "vs_abc456" + has_more: + type: boolean + example: false required: - - type - - call_id - - status - title: Apply patch tool call output - description: The streamed output emitted by an apply patch tool call. - ItemReferenceParam: + - object + - data + - first_id + - last_id + - has_more + + DeleteVectorStoreResponse: + type: object properties: - type: - anyOf: - - type: string - enum: - - item_reference - description: The type of item to reference. Always `item_reference`. - default: item_reference - x-stainless-const: true - - type: 'null' id: type: string - description: The ID of the item to reference. - type: object + deleted: + type: boolean + object: + type: string + enum: [vector_store.deleted] required: - id - title: Item reference - description: An internal identifier for an item to reference. - ConversationResource: + - object + - deleted + + VectorStoreFileObject: + type: object + title: Vector store files + description: A list of files attached to a vector store. properties: id: + description: The identifier, which can be referenced in API endpoints. type: string - description: The unique ID of the conversation. object: + description: The object type, which is always `vector_store.file`. type: string - enum: - - conversation - description: The object type, which is always `conversation`. - default: conversation - x-stainless-const: true - metadata: - description: >- - 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. + enum: ["vector_store.file"] + usage_bytes: + description: The total vector store usage in bytes. Note that this may be different from the original file size. + type: integer created_at: + description: The Unix timestamp (in seconds) for when the vector store file was created. type: integer - description: The time at which the conversation was created, measured in seconds since the Unix epoch. - type: object + vector_store_id: + description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + type: string + status: + description: The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + type: string + enum: ["in_progress", "completed", "cancelled", "failed"] + last_error: + type: object + description: The last error associated with this vector store file. Will be `null` if there are no errors. + nullable: true + properties: + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: ["server_error", "unsupported_file", "invalid_file"] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + chunking_strategy: + type: object + description: The strategy used to chunk the file. + oneOf: + - $ref: "#/components/schemas/StaticChunkingStrategyResponseParam" + - $ref: "#/components/schemas/OtherChunkingStrategyResponseParam" + x-oaiExpandable: true required: - id - object - - metadata + - usage_bytes - created_at - FunctionTool: + - vector_store_id + - status + - last_error + x-oaiMeta: + name: The vector store file object + beta: true + example: | + { + "id": "file-abc123", + "object": "vector_store.file", + "usage_bytes": 1234, + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "last_error": null, + "chunking_strategy": { + "type": "static", + "static": { + "max_chunk_size_tokens": 800, + "chunk_overlap_tokens": 400 + } + } + } + + OtherChunkingStrategyResponseParam: + type: object + title: Other Chunking Strategy + description: This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. + additionalProperties: false properties: type: type: string - enum: - - function - description: The type of the function tool. Always `function`. - default: function - x-stainless-const: true - name: - type: string - description: The name of the function to call. - description: - anyOf: - - type: string - description: >- - A description of the function. Used by the model to determine whether or not to call the - function. - - type: 'null' - parameters: - anyOf: - - additionalProperties: {} - type: object - description: A JSON schema object describing the parameters of the function. - x-oaiTypeLabel: map - - type: 'null' - strict: - anyOf: - - type: boolean - description: Whether to enforce strict parameter validation. Default `true`. - - type: 'null' - type: object + description: Always `other`. + enum: ["other"] required: - type - - name - - strict - - parameters - title: Function - description: >- - Defines a function in your own code the model can choose to call. Learn more about [function - calling](https://platform.openai.com/docs/guides/function-calling). - RankerVersionType: - type: string - enum: - - auto - - default-2024-11-15 - HybridSearchOptions: - properties: - embedding_weight: - type: number - description: The weight of the embedding in the reciprocal ranking fusion. - text_weight: - type: number - description: The weight of the text in the reciprocal ranking fusion. - type: object - required: - - embedding_weight - - text_weight - RankingOptions: - properties: - ranker: - $ref: '#/components/schemas/RankerVersionType' - description: The ranker to use for the file search. - score_threshold: - type: number - description: >- - The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will - attempt to return only the most relevant results, but may return fewer results. - hybrid_search: - $ref: '#/components/schemas/HybridSearchOptions' - description: >- - Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse - keyword matches when hybrid search is enabled. + + StaticChunkingStrategyResponseParam: type: object - required: [] - Filters: - anyOf: - - $ref: '#/components/schemas/ComparisonFilter' - - $ref: '#/components/schemas/CompoundFilter' - FileSearchTool: + title: Static Chunking Strategy + additionalProperties: false properties: type: type: string - enum: - - file_search - description: The type of the file search tool. Always `file_search`. - default: file_search - x-stainless-const: true - vector_store_ids: - items: - type: string - type: array - description: The IDs of the vector stores to search. - max_num_results: - type: integer - description: The maximum number of results to return. This number should be between 1 and 50 inclusive. - ranking_options: - $ref: '#/components/schemas/RankingOptions' - description: Ranking options for search. - filters: - anyOf: - - $ref: '#/components/schemas/Filters' - description: A filter to apply. - - type: 'null' - type: object + description: Always `static`. + enum: ["static"] + static: + $ref: "#/components/schemas/StaticChunkingStrategy" required: - type - - vector_store_ids - title: File search - description: >- - A tool that searches for relevant content from uploaded files. Learn more about the [file search - tool](https://platform.openai.com/docs/guides/tools-file-search). - ComputerEnvironment: - type: string - enum: - - windows - - mac - - linux - - ubuntu - - browser - ComputerUsePreviewTool: + - static + + StaticChunkingStrategy: + type: object + additionalProperties: false properties: - type: - type: string - enum: - - computer_use_preview - description: The type of the computer use tool. Always `computer_use_preview`. - default: computer_use_preview - x-stainless-const: true - environment: - $ref: '#/components/schemas/ComputerEnvironment' - description: The type of computer environment to control. - display_width: + max_chunk_size_tokens: type: integer - description: The width of the computer display. - display_height: + minimum: 100 + maximum: 4096 + description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: type: integer - description: The height of the computer display. - type: object + description: | + The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. required: - - type - - environment - - display_width - - display_height - title: Computer use preview - description: >- - A tool that controls a virtual computer. Learn more about the [computer - tool](https://platform.openai.com/docs/guides/tools-computer-use). - ContainerMemoryLimit: - type: string - enum: - - 1g - - 4g - - 16g - - 64g - InputFidelity: - type: string - enum: - - high - - low - description: >- - Control how much effort the model will exert to match the style and features, especially facial - features, of input images. This parameter is only supported for `gpt-image-1`. Unsupported for - `gpt-image-1-mini`. Supports `high` and `low`. Defaults to `low`. - LocalShellToolParam: + - max_chunk_size_tokens + - chunk_overlap_tokens + + AutoChunkingStrategyRequestParam: + type: object + title: Auto Chunking Strategy + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false properties: type: type: string - enum: - - local_shell - description: The type of the local shell tool. Always `local_shell`. - default: local_shell - x-stainless-const: true - type: object + description: Always `auto`. + enum: ["auto"] required: - type - title: Local shell tool - description: A tool that allows the model to execute shell commands in a local environment. - FunctionShellToolParam: + + StaticChunkingStrategyRequestParam: + type: object + title: Static Chunking Strategy + additionalProperties: false properties: type: type: string - enum: - - shell - description: The type of the shell tool. Always `shell`. - default: shell - x-stainless-const: true - type: object + description: Always `static`. + enum: ["static"] + static: + $ref: "#/components/schemas/StaticChunkingStrategy" required: - type - title: Shell tool - description: A tool that allows the model to execute shell commands. - CustomTextFormatParam: + - static + + ChunkingStrategyRequestParam: + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + oneOf: + - $ref: "#/components/schemas/AutoChunkingStrategyRequestParam" + - $ref: "#/components/schemas/StaticChunkingStrategyRequestParam" + x-oaiExpandable: true + + CreateVectorStoreFileRequest: + type: object + additionalProperties: false properties: - type: + file_id: + description: A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. type: string - enum: - - text - description: Unconstrained text format. Always `text`. - default: text - x-stainless-const: true - type: object + chunking_strategy: + $ref: "#/components/schemas/ChunkingStrategyRequestParam" required: - - type - title: Text format - description: Unconstrained free-form text. - GrammarSyntax1: - type: string - enum: - - lark - - regex - CustomGrammarFormatParam: + - file_id + + ListVectorStoreFilesResponse: properties: - type: + object: type: string - enum: - - grammar - description: Grammar format. Always `grammar`. - default: grammar - x-stainless-const: true - syntax: - $ref: '#/components/schemas/GrammarSyntax1' - description: The syntax of the grammar definition. One of `lark` or `regex`. - definition: + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/VectorStoreFileObject" + first_id: type: string - description: The grammar definition. - type: object + example: "file-abc123" + last_id: + type: string + example: "file-abc456" + has_more: + type: boolean + example: false required: - - type - - syntax - - definition - title: Grammar format - description: A grammar defined by the user. - CustomToolParam: + - object + - data + - first_id + - last_id + - has_more + + DeleteVectorStoreFileResponse: + type: object properties: - type: - type: string - enum: - - custom - description: The type of the custom tool. Always `custom`. - default: custom - x-stainless-const: true - name: + id: type: string - description: The name of the custom tool, used to identify it in tool calls. - description: + deleted: + type: boolean + object: type: string - description: Optional description of the custom tool, used to provide more context. - format: - description: The input format for the custom tool. Default is unconstrained text. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/CustomTextFormatParam' - - $ref: '#/components/schemas/CustomGrammarFormatParam' - type: object + enum: [vector_store.file.deleted] required: - - type - - name - title: Custom tool - description: >- - A custom tool that processes input using a specified format. Learn more about [custom - tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) - ApproximateLocation: + - id + - object + - deleted + + VectorStoreFileBatchObject: + type: object + title: Vector store file batch + description: A batch of files attached to a vector store. properties: - type: + id: + description: The identifier, which can be referenced in API endpoints. type: string - enum: - - approximate - description: The type of location approximation. Always `approximate`. - default: approximate - x-stainless-const: true - country: - anyOf: - - type: string - description: >- - The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. - `US`. - - type: 'null' - region: - anyOf: - - type: string - description: Free text input for the region of the user, e.g. `California`. - - type: 'null' - city: - anyOf: - - type: string - description: Free text input for the city of the user, e.g. `San Francisco`. - - type: 'null' - timezone: - anyOf: - - type: string - description: >- - The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. - `America/Los_Angeles`. - - type: 'null' + object: + description: The object type, which is always `vector_store.file_batch`. + type: string + enum: ["vector_store.files_batch"] + created_at: + description: The Unix timestamp (in seconds) for when the vector store files batch was created. + type: integer + vector_store_id: + description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + type: string + status: + description: The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + type: string + enum: ["in_progress", "completed", "cancelled", "failed"] + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that where cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - cancelled + - failed + - total + required: + - id + - object + - created_at + - vector_store_id + - status + - file_counts + x-oaiMeta: + name: The vector store files batch object + beta: true + example: | + { + "id": "vsfb_123", + "object": "vector_store.files_batch", + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "failed": 0, + "cancelled": 0, + "total": 100 + } + } + + CreateVectorStoreFileBatchRequest: type: object - required: - - type - SearchContextSize: - type: string - enum: - - low - - medium - - high - WebSearchPreviewTool: + additionalProperties: false properties: - type: - type: string - enum: - - web_search_preview - - web_search_preview_2025_03_11 - description: The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. - default: web_search_preview - x-stainless-const: true - user_location: - anyOf: - - $ref: '#/components/schemas/ApproximateLocation' - description: The user's location. - - type: 'null' - search_context_size: - $ref: '#/components/schemas/SearchContextSize' - description: >- - 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. + file_ids: + description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + type: array + minItems: 1 + maxItems: 500 + items: + type: string + chunking_strategy: + $ref: "#/components/schemas/ChunkingStrategyRequestParam" + required: + - file_ids + + AssistantStreamEvent: + description: | + Represents an event emitted when streaming a Run. + + Each event in a server-sent events stream has an `event` and `data` property: + + ``` + event: thread.created + data: {"id": "thread_123", "object": "thread", ...} + ``` + + We emit events whenever a new object is created, transitions to a new state, or is being + streamed in parts (deltas). For example, we emit `thread.run.created` when a new run + is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses + to create a message during a run, we emit a `thread.message.created event`, a + `thread.message.in_progress` event, many `thread.message.delta` events, and finally a + `thread.message.completed` event. + + We may add additional events over time, so we recommend handling unknown events gracefully + in your code. See the [Assistants API quickstart](/docs/assistants/overview) to learn how to + integrate the Assistants API with streaming. + oneOf: + - $ref: "#/components/schemas/ThreadStreamEvent" + - $ref: "#/components/schemas/RunStreamEvent" + - $ref: "#/components/schemas/RunStepStreamEvent" + - $ref: "#/components/schemas/MessageStreamEvent" + - $ref: "#/components/schemas/ErrorEvent" + - $ref: "#/components/schemas/DoneEvent" + x-oaiMeta: + name: Assistant stream events + beta: true + + ThreadStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.created"] + data: + $ref: "#/components/schemas/ThreadObject" + required: + - event + - data + description: Occurs when a new [thread](/docs/api-reference/threads/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [thread](/docs/api-reference/threads/object)" + + RunStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.run.created"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a new [run](/docs/api-reference/runs/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.queued"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `queued` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.in_progress"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to an `in_progress` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.requires_action"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `requires_action` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.completed"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.incomplete"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) ends with status `incomplete`. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.failed"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) fails. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.cancelling"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `cancelling` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.cancelled"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is cancelled. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.expired"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) expires. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + + RunStepStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.run.step.created"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is created. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.in_progress"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) moves to an `in_progress` state. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.delta"] + data: + $ref: "#/components/schemas/RunStepDeltaObject" + required: + - event + - data + description: Occurs when parts of a [run step](/docs/api-reference/runs/step-object) are being streamed. + x-oaiMeta: + dataDescription: "`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.completed"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.failed"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) fails. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.cancelled"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is cancelled. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.expired"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) expires. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + + MessageStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.message.created"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.in_progress"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) moves to an `in_progress` state. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.delta"] + data: + $ref: "#/components/schemas/MessageDeltaObject" + required: + - event + - data + description: Occurs when parts of a [Message](/docs/api-reference/messages/object) are being streamed. + x-oaiMeta: + dataDescription: "`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.completed"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.incomplete"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) ends before it is completed. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + + ErrorEvent: type: object - required: - - type - title: Web search preview - description: >- - 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). - ApplyPatchToolParam: properties: - type: + event: type: string - enum: - - apply_patch - description: The type of the tool. Always `apply_patch`. - default: apply_patch - x-stainless-const: true - type: object - required: - - type - title: Apply patch tool - description: Allows the assistant to create, delete, or update files using unified diffs. - ImageGenInputUsageDetails: - properties: - text_tokens: - type: integer - description: The number of text tokens in the input prompt. - image_tokens: - type: integer - description: The number of image tokens in the input prompt. - type: object + enum: ["error"] + data: + $ref: "#/components/schemas/Error" required: - - text_tokens - - image_tokens - title: Input usage details - description: The input tokens detailed information for the image generation. - ImageGenUsage: - properties: - input_tokens: - type: integer - description: The number of tokens (images and text) in the input prompt. - total_tokens: - type: integer - description: The total number of tokens (images and text) used for the image generation. - output_tokens: - type: integer - description: The number of output tokens generated by the model. - input_tokens_details: - $ref: '#/components/schemas/ImageGenInputUsageDetails' + - event + - data + description: Occurs when an [error](/docs/guides/error-codes/api-errors) occurs. This can happen due to an internal server error or a timeout. + x-oaiMeta: + dataDescription: "`data` is an [error](/docs/guides/error-codes/api-errors)" + + DoneEvent: type: object - required: - - input_tokens - - total_tokens - - output_tokens - - input_tokens_details - title: Image generation usage - description: For `gpt-image-1` only, the token usage information for the image generation. - SpecificApplyPatchParam: properties: - type: + event: type: string - enum: - - apply_patch - description: The tool to call. Always `apply_patch`. - default: apply_patch - x-stainless-const: true - type: object - required: - - type - title: Specific apply patch tool choice - description: Forces the model to call the apply_patch tool when executing a tool call. - SpecificFunctionShellParam: - properties: - type: + enum: ["done"] + data: type: string - enum: - - shell - description: The tool to call. Always `shell`. - default: shell - x-stainless-const: true - type: object + enum: ["[DONE]"] required: - - type - title: Specific shell tool choice - description: Forces the model to call the function shell tool when a tool call is required. - ConversationParam-2: - properties: - id: - type: string - description: The unique ID of the conversation. - example: conv_123 + - event + - data + description: Occurs when a stream ends. + x-oaiMeta: + dataDescription: "`data` is `[DONE]`" + + Batch: type: object - required: - - id - title: Conversation object - description: The conversation that this response belongs to. - Conversation-2: properties: id: type: string - description: The unique ID of the conversation. - type: object - required: - - id - title: Conversation - description: >- - The conversation that this response belongs to. Input items and output items from this response are - automatically added to this conversation. - CreateConversationBody: - properties: - metadata: - anyOf: - - $ref: '#/components/schemas/Metadata' - description: >- - 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. - - type: 'null' - items: - anyOf: - - items: - $ref: '#/components/schemas/InputItem' - type: array - maxItems: 20 - description: Initial items to include in the conversation context. You may add up to 20 items at a time. - - type: 'null' - type: object - required: [] - UpdateConversationBody: - properties: - metadata: - $ref: '#/components/schemas/Metadata' - description: >- - 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. - type: object - required: - - metadata - DeletedConversationResource: - properties: object: type: string + enum: [batch] + description: The object type, which is always `batch`. + endpoint: + type: string + description: The OpenAI API endpoint used by the batch. + + errors: + type: object + properties: + object: + type: string + description: The object type, which is always `list`. + data: + type: array + items: + type: object + properties: + code: + type: string + description: An error code identifying the error type. + message: + type: string + description: A human-readable message providing more details about the error. + param: + type: string + description: The name of the parameter that caused the error, if applicable. + nullable: true + line: + type: integer + description: The line number of the input file where the error occurred, if applicable. + nullable: true + input_file_id: + type: string + description: The ID of the input file for the batch. + completion_window: + type: string + description: The time frame within which the batch should be processed. + status: + type: string + description: The current status of the batch. enum: - - conversation.deleted - default: conversation.deleted - x-stainless-const: true - deleted: - type: boolean - id: + - validating + - failed + - in_progress + - finalizing + - completed + - expired + - cancelling + - cancelled + output_file_id: type: string - type: object + description: The ID of the file containing the outputs of successfully executed requests. + error_file_id: + type: string + description: The ID of the file containing the outputs of requests with errors. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was created. + in_progress_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started processing. + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch will expire. + finalizing_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started finalizing. + completed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was completed. + failed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch failed. + expired_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch expired. + cancelling_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started cancelling. + cancelled_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was cancelled. + request_counts: + type: object + properties: + total: + type: integer + description: Total number of requests in the batch. + completed: + type: integer + description: Number of requests that have been completed successfully. + failed: + type: integer + description: Number of requests that have failed. + required: + - total + - completed + - failed + description: The request counts for different statuses within the batch. + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true required: - - object - - deleted - id - OrderEnum: - type: string - enum: - - asc - - desc - VideoModel: - type: string - enum: - - sora-2 - - sora-2-pro - VideoStatus: - type: string - enum: - - queued - - in_progress - - completed - - failed - VideoSize: - type: string - enum: - - 720x1280 - - 1280x720 - - 1024x1792 - - 1792x1024 - VideoSeconds: - type: string - enum: - - '4' - - '8' - - '12' - Error-2: + - object + - endpoint + - input_file_id + - completion_window + - status + - created_at + x-oaiMeta: + name: The batch object + example: *batch_object + + BatchRequestInput: + type: object + description: The per-line object of the batch input file properties: - code: + custom_id: type: string - message: + description: A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch. + method: type: string + enum: ["POST"] + description: The HTTP method to be used for the request. Currently only `POST` is supported. + url: + type: string + description: The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. + x-oaiMeta: + name: The request input object + example: | + {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is 2+2?"}]}} + + BatchRequestOutput: type: object - required: - - code - - message - VideoResource: + description: The per-line object of the batch output and error files properties: id: type: string - description: Unique identifier for the video job. - object: + custom_id: type: string - enum: - - video - description: The object type, which is always `video`. - default: video - x-stainless-const: true - model: - $ref: '#/components/schemas/VideoModel' - description: The video generation model that produced the job. - status: - $ref: '#/components/schemas/VideoStatus' - description: Current lifecycle status of the video job. - progress: - type: integer - description: Approximate completion percentage for the generation task. - created_at: - type: integer - description: Unix timestamp (seconds) for when the job was created. - completed_at: - anyOf: - - type: integer - description: Unix timestamp (seconds) for when the job completed, if finished. - - type: 'null' - expires_at: - anyOf: - - type: integer - description: Unix timestamp (seconds) for when the downloadable assets expire, if set. - - type: 'null' - prompt: - anyOf: - - type: string - description: The prompt that was used to generate the video. - - type: 'null' - size: - $ref: '#/components/schemas/VideoSize' - description: The resolution of the generated video. - seconds: - $ref: '#/components/schemas/VideoSeconds' - description: Duration of the generated clip in seconds. - remixed_from_video_id: - anyOf: - - type: string - description: Identifier of the source video if this video is a remix. - - type: 'null' + description: A developer-provided per-request id that will be used to match outputs to inputs. + response: + type: object + nullable: true + properties: + status_code: + type: integer + description: The HTTP status code of the response + request_id: + type: string + description: An unique identifier for the OpenAI API request. Please include this request ID when contacting support. + body: + type: object + x-oaiTypeLabel: map + description: The JSON body of the response error: - anyOf: - - $ref: '#/components/schemas/Error-2' - description: Error payload that explains why generation failed, if applicable. - - type: 'null' + type: object + nullable: true + description: For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + x-oaiMeta: + name: The request output object + example: | + {"id": "batch_req_wnaDys", "custom_id": "request-2", "response": {"status_code": 200, "request_id": "req_c187b3", "body": {"id": "chatcmpl-9758Iw", "object": "chat.completion", "created": 1711475054, "model": "gpt-4o-mini", "choices": [{"index": 0, "message": {"role": "assistant", "content": "2 + 2 equals 4."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 24, "completion_tokens": 15, "total_tokens": 39}, "system_fingerprint": null}}, "error": null} + + ListBatchesResponse: type: object - required: - - id - - object - - model - - status - - progress - - created_at - - completed_at - - expires_at - - prompt - - size - - seconds - - remixed_from_video_id - - error - title: Video job - description: Structured information describing a generated video job. - VideoListResource: properties: - object: - description: The type of object returned, must be `list`. - default: list - x-stainless-const: true - const: list data: - items: - $ref: '#/components/schemas/VideoResource' type: array - description: A list of items + items: + $ref: "#/components/schemas/Batch" first_id: - anyOf: - - type: string - description: The ID of the first item in the list. - - type: 'null' + type: string + example: "batch_abc123" last_id: - anyOf: - - type: string - description: The ID of the last item in the list. - - type: 'null' + type: string + example: "batch_abc456" has_more: type: boolean - description: Whether there are more items available. - type: object + object: + type: string + enum: [list] required: - object - data - - first_id - - last_id - has_more - CreateVideoBody: - properties: - model: - $ref: '#/components/schemas/VideoModel' - description: The video generation model to use. Defaults to `sora-2`. - prompt: - type: string - maxLength: 32000 - minLength: 1 - description: Text prompt that describes the video to generate. - input_reference: - type: string - format: binary - description: Optional image reference that guides generation. - seconds: - $ref: '#/components/schemas/VideoSeconds' - description: Clip duration in seconds. Defaults to 4 seconds. - size: - $ref: '#/components/schemas/VideoSize' - description: Output resolution formatted as width x height. Defaults to 720x1280. + + AuditLogActorServiceAccount: type: object - required: - - prompt - title: Create video request - description: Parameters for creating a new video generation job. - DeletedVideoResource: + description: The service account that performed the audit logged action. properties: - object: - type: string - enum: - - video.deleted - description: The object type that signals the deletion response. - default: video.deleted - x-stainless-const: true - deleted: - type: boolean - description: Indicates that the video resource was deleted. id: type: string - description: Identifier of the deleted video. + description: The service account id. + + AuditLogActorUser: type: object - required: - - object - - deleted - - id - title: Deleted video response - description: Confirmation payload returned after deleting a video. - VideoContentVariant: - type: string - enum: - - video - - thumbnail - - spritesheet - CreateVideoRemixBody: + description: The user who performed the audit logged action. properties: - prompt: + id: type: string - maxLength: 32000 - minLength: 1 - description: Updated text prompt that directs the remix generation. + description: The user id. + email: + type: string + description: The user email. + + AuditLogActorApiKey: type: object - required: - - prompt - title: Create video remix request - description: Parameters for remixing an existing generated video. - TruncationEnum: - type: string - enum: - - auto - - disabled - TokenCountsBody: + description: The API Key used to perform the audit logged action. properties: - model: - anyOf: - - type: string - description: >- - Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of - models with different capabilities, performance characteristics, and price points. Refer to - the [model guide](https://platform.openai.com/docs/models) to browse and compare available - models. - - type: 'null' - input: - anyOf: - - description: Text, image, or file inputs to the model, used to generate a response - anyOf: - - type: string - maxLength: 10485760 - description: A text input to the model, equivalent to a text input with the `user` role. - - items: - $ref: '#/components/schemas/InputItem' - type: array - - type: 'null' - previous_response_id: - anyOf: - - type: string - description: >- - 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`. - example: resp_123 - - type: 'null' - tools: - anyOf: - - items: - $ref: '#/components/schemas/Tool' - type: array - description: >- - 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. - - type: 'null' - text: - anyOf: - - $ref: '#/components/schemas/ResponseTextParam' - - type: 'null' - reasoning: - anyOf: - - $ref: '#/components/schemas/Reasoning' - description: >- - **gpt-5 and o-series models only** Configuration options for [reasoning - models](https://platform.openai.com/docs/guides/reasoning). - - type: 'null' - truncation: - $ref: '#/components/schemas/TruncationEnum' - description: >- - The truncation strategy to use for the model response. - `auto`: If the input to this Response - exceeds the model's context window size, the model will truncate the response to fit the context - window by dropping items from the beginning of the conversation. - `disabled` (default): If the - input size will exceed the context window size for a model, the request will fail with a 400 - error. - instructions: - anyOf: - - type: string - description: >- - A system (or developer) message inserted into the model's context. - - When used along with `previous_response_id`, the instructions from a previous response will - not be carried over to the next response. This makes it simple to swap out system (or - developer) messages in new responses. - - type: 'null' - conversation: - anyOf: - - $ref: '#/components/schemas/ConversationParam' - - type: 'null' - tool_choice: - anyOf: - - $ref: '#/components/schemas/ToolChoiceParam' - - type: 'null' - parallel_tool_calls: - anyOf: - - type: boolean - description: Whether to allow the model to run tool calls in parallel. - - type: 'null' + id: + type: string + description: The tracking id of the API key. + type: + type: string + description: The type of API key. Can be either `user` or `service_account`. + enum: ["user", "service_account"] + user: + $ref: "#/components/schemas/AuditLogActorUser" + service_account: + $ref: "#/components/schemas/AuditLogActorServiceAccount" + + AuditLogActorSession: type: object - required: [] - TokenCountsResource: + description: The session in which the audit logged action was performed. properties: - object: + user: + $ref: "#/components/schemas/AuditLogActorUser" + ip_address: type: string - enum: - - response.input_tokens - default: response.input_tokens - x-stainless-const: true - input_tokens: - type: integer + description: The IP address from which the action was performed. + + AuditLogActor: type: object - required: - - object - - input_tokens - title: Token counts - example: - object: response.input_tokens - input_tokens: 123 - ChatkitWorkflowTracing: + description: The actor who performed the audit logged action. properties: - enabled: - type: boolean - description: Indicates whether tracing is enabled. + type: + type: string + description: The type of actor. Is either `session` or `api_key`. + enum: ["session", "api_key"] + session: + type: object + $ref: "#/components/schemas/AuditLogActorSession" + api_key: + type: object + $ref: "#/components/schemas/AuditLogActorApiKey" + + AuditLogEventType: + type: string + description: The event type. + x-oaiExpandable: true + enum: + - api_key.created + - api_key.updated + - api_key.deleted + - invite.sent + - invite.accepted + - invite.deleted + - login.succeeded + - login.failed + - logout.succeeded + - logout.failed + - organization.updated + - project.created + - project.updated + - project.archived + - service_account.created + - service_account.updated + - service_account.deleted + - user.added + - user.updated + - user.deleted + + AuditLog: type: object - required: - - enabled - title: Tracing Configuration - description: Controls diagnostic tracing during the session. - ChatkitWorkflow: + description: A log of a user action or configuration change within this organization. properties: id: type: string - description: Identifier of the workflow backing the session. - version: - anyOf: - - type: string - description: >- - Specific workflow version used for the session. Defaults to null when using the latest - deployment. - - type: 'null' - state_variables: - anyOf: - - additionalProperties: - anyOf: - - type: string - - type: integer - - type: boolean - - type: number + description: The ID of this log. + type: + $ref: "#/components/schemas/AuditLogEventType" + + effective_at: + type: integer + description: The Unix timestamp (in seconds) of the event. + project: + type: object + description: The project that the action was scoped to. Absent for actions not scoped to projects. + properties: + id: + type: string + description: The project ID. + name: + type: string + description: The project title. + actor: + $ref: "#/components/schemas/AuditLogActor" + api_key.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + data: + type: object + description: The payload used to create the API key. + properties: + scopes: + type: array + items: + type: string + description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` + api_key.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + changes_requested: + type: object + description: The payload used to update the API key. + properties: + scopes: + type: array + items: + type: string + description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` + api_key.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + invite.sent: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + data: + type: object + description: The payload used to create the invite. + properties: + email: + type: string + description: The email invited to the organization. + role: + type: string + description: The role the email was invited to be. Is either `owner` or `member`. + invite.accepted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + invite.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + login.failed: + type: object + description: The details for events with this `type`. + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + logout.failed: + type: object + description: The details for events with this `type`. + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + organization.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The organization ID. + changes_requested: + type: object + description: The payload used to update the organization settings. + properties: + title: + type: string + description: The organization title. + description: + type: string + description: The organization description. + name: + type: string + description: The organization name. + settings: + type: object + properties: + threads_ui_visibility: + type: string + description: Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. + usage_dashboard_visibility: + type: string + description: Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`. + project.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + data: type: object - description: >- - State variable key-value pairs applied when invoking the workflow. Defaults to null when no - overrides were provided. - x-oaiTypeLabel: map - - type: 'null' - tracing: - $ref: '#/components/schemas/ChatkitWorkflowTracing' - description: Tracing settings applied to the workflow. - type: object - required: - - id - - version - - state_variables - - tracing - title: Workflow - description: Workflow metadata and state returned for the session. - ChatSessionRateLimits: - properties: - max_requests_per_1_minute: - type: integer - description: Maximum allowed requests per one-minute window. - type: object - required: - - max_requests_per_1_minute - title: Rate limits - description: Active per-minute request limit for the session. - ChatSessionStatus: - type: string - enum: - - active - - expired - - cancelled - ChatSessionAutomaticThreadTitling: - properties: - enabled: - type: boolean - description: Whether automatic thread titling is enabled. - type: object - required: - - enabled - title: Automatic thread titling - description: Automatic thread title preferences for the session. - ChatSessionFileUpload: - properties: - enabled: - type: boolean - description: Indicates if uploads are enabled for the session. - max_file_size: - anyOf: - - type: integer - description: Maximum upload size in megabytes. - - type: 'null' - max_files: - anyOf: - - type: integer - description: Maximum number of uploads allowed during the session. - - type: 'null' - type: object - required: - - enabled - - max_file_size - - max_files - title: File upload settings - description: Upload permissions and limits applied to the session. - ChatSessionHistory: - properties: - enabled: - type: boolean - description: Indicates if chat history is persisted for the session. - recent_threads: - anyOf: - - type: integer - description: >- - Number of prior threads surfaced in history views. Defaults to null when all history is - retained. - - type: 'null' - type: object - required: - - enabled - - recent_threads - title: History settings - description: History retention preferences returned for the session. - ChatSessionChatkitConfiguration: - properties: - automatic_thread_titling: - $ref: '#/components/schemas/ChatSessionAutomaticThreadTitling' - description: Automatic thread titling preferences. - file_upload: - $ref: '#/components/schemas/ChatSessionFileUpload' - description: Upload settings for the session. - history: - $ref: '#/components/schemas/ChatSessionHistory' - description: History retention configuration. - type: object - required: - - automatic_thread_titling - - file_upload - - history - title: ChatKit configuration - description: ChatKit configuration for the session. - ChatSessionResource: - properties: - id: - type: string - description: Identifier for the ChatKit session. - object: - type: string - enum: - - chatkit.session - description: Type discriminator that is always `chatkit.session`. - default: chatkit.session - x-stainless-const: true - expires_at: - type: integer - description: Unix timestamp (in seconds) for when the session expires. - client_secret: - type: string - description: Ephemeral client secret that authenticates session requests. - workflow: - $ref: '#/components/schemas/ChatkitWorkflow' - description: Workflow metadata for the session. - user: - type: string - description: User identifier associated with the session. - rate_limits: - $ref: '#/components/schemas/ChatSessionRateLimits' - description: Resolved rate limit values. - max_requests_per_1_minute: - type: integer - description: Convenience copy of the per-minute request limit. - status: - $ref: '#/components/schemas/ChatSessionStatus' - description: Current lifecycle state of the session. - chatkit_configuration: - $ref: '#/components/schemas/ChatSessionChatkitConfiguration' - description: Resolved ChatKit feature configuration for the session. - type: object - required: - - id - - object - - expires_at - - client_secret - - workflow - - user - - rate_limits - - max_requests_per_1_minute - - status - - chatkit_configuration - title: The chat session object - description: Represents a ChatKit session and its resolved configuration. - WorkflowTracingParam: - properties: - enabled: - type: boolean - description: Whether tracing is enabled during the session. Defaults to true. - type: object - required: [] - title: Tracing Configuration - description: Controls diagnostic tracing during the session. - WorkflowParam: - properties: - id: - type: string - description: Identifier for the workflow invoked by the session. - version: - type: string - description: Specific workflow version to run. Defaults to the latest deployed version. - state_variables: - additionalProperties: - anyOf: - - type: string - maxLength: 10485760 - - type: integer - - type: boolean - - type: number + description: The payload used to create the project. + properties: + name: + type: string + description: The project name. + title: + type: string + description: The title of the project as seen on the dashboard. + project.updated: type: object - maxProperties: 64 - description: >- - State variables forwarded to the workflow. Keys may be up to 64 characters, values must be - primitive types, and the map defaults to an empty object. - x-oaiTypeLabel: map - tracing: - $ref: '#/components/schemas/WorkflowTracingParam' - description: >- - Optional tracing overrides for the workflow invocation. When omitted, tracing is enabled by - default. - type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + description: The payload used to update the project. + properties: + title: + type: string + description: The title of the project as seen on the dashboard. + project.archived: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + service_account.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + data: + type: object + description: The payload used to create the service account. + properties: + role: + type: string + description: The role of the service account. Is either `owner` or `member`. + service_account.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + changes_requested: + type: object + description: The payload used to updated the service account. + properties: + role: + type: string + description: The role of the service account. Is either `owner` or `member`. + service_account.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + user.added: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The user ID. + data: + type: object + description: The payload used to add the user to the project. + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + user.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + description: The payload used to update the user. + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + user.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The user ID. required: - id - title: Workflow settings - description: Workflow reference and overrides applied to the chat session. - ExpiresAfterParam: - properties: - anchor: - type: string - enum: - - created_at - description: Base timestamp used to calculate expiration. Currently fixed to `created_at`. - default: created_at - x-stainless-const: true - seconds: - type: integer - maximum: 600 - minimum: 1 - description: Number of seconds after the anchor when the session expires. - type: object - required: - - anchor - - seconds - title: Expiration overrides - description: Controls when the session expires relative to an anchor timestamp. - RateLimitsParam: - properties: - max_requests_per_1_minute: - type: integer - minimum: 1 - description: Maximum number of requests allowed per minute for the session. Defaults to 10. - type: object - required: [] - title: Rate limit overrides - description: Controls request rate limits for the session. - AutomaticThreadTitlingParam: - properties: - enabled: - type: boolean - description: Enable automatic thread title generation. Defaults to true. - type: object - required: [] - title: Automatic thread titling configuration - description: Controls whether ChatKit automatically generates thread titles. - FileUploadParam: - properties: - enabled: - type: boolean - description: Enable uploads for this session. Defaults to false. - max_file_size: - type: integer - maximum: 512 - minimum: 1 - description: >- - Maximum size in megabytes for each uploaded file. Defaults to 512 MB, which is the maximum - allowable size. - max_files: - type: integer - minimum: 1 - description: Maximum number of files that can be uploaded to the session. Defaults to 10. - type: object - required: [] - title: File upload configuration - description: Controls whether users can upload files. - HistoryParam: - properties: - enabled: - type: boolean - description: Enables chat users to access previous ChatKit threads. Defaults to true. - recent_threads: - type: integer - minimum: 1 - description: Number of recent ChatKit threads users have access to. Defaults to unlimited when unset. - type: object - required: [] - title: Chat history configuration - description: Controls how much historical context is retained for the session. - ChatkitConfigurationParam: - properties: - automatic_thread_titling: - $ref: '#/components/schemas/AutomaticThreadTitlingParam' - description: >- - Configuration for automatic thread titling. When omitted, automatic thread titling is enabled by - default. - file_upload: - $ref: '#/components/schemas/FileUploadParam' - description: >- - Configuration for upload enablement and limits. When omitted, uploads are disabled by default - (max_files 10, max_file_size 512 MB). - history: - $ref: '#/components/schemas/HistoryParam' - description: >- - Configuration for chat history retention. When omitted, history is enabled by default with no - limit on recent_threads (null). - type: object - required: [] - title: ChatKit configuration overrides - description: Optional per-session configuration settings for ChatKit behavior. - CreateChatSessionBody: - properties: - workflow: - $ref: '#/components/schemas/WorkflowParam' - description: Workflow that powers the session. - user: - type: string - minLength: 1 - description: >- - A free-form string that identifies your end user; ensures this Session can access other objects - that have the same `user` scope. - expires_after: - $ref: '#/components/schemas/ExpiresAfterParam' - description: Optional override for session expiration timing in seconds from creation. Defaults to 10 minutes. - rate_limits: - $ref: '#/components/schemas/RateLimitsParam' - description: Optional override for per-minute request limits. When omitted, defaults to 10. - chatkit_configuration: - $ref: '#/components/schemas/ChatkitConfigurationParam' - description: Optional overrides for ChatKit runtime configuration features + - type + - effective_at + - actor + x-oaiMeta: + name: The audit log object + example: | + { + "id": "req_xxx_20240101", + "type": "api_key.created", + "effective_at": 1720804090, + "actor": { + "type": "session", + "session": { + "user": { + "id": "user-xxx", + "email": "user@example.com" + }, + "ip_address": "127.0.0.1", + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" + } + }, + "api_key.created": { + "id": "key_xxxx", + "data": { + "scopes": ["resource.operation"] + } + } + } + + ListAuditLogsResponse: type: object - required: - - workflow - - user - title: Create chat session request - description: Parameters for provisioning a new ChatKit session. - UserMessageInputText: properties: - type: - type: string - enum: - - input_text - description: Type discriminator that is always `input_text`. - default: input_text - x-stainless-const: true - text: + object: type: string - description: Plain-text content supplied by the user. - type: object - required: - - type - - text - title: User message input - description: Text block that a user contributed to the thread. - UserMessageQuotedText: - properties: - type: + enum: [list] + data: + type: array + items: + $ref: "#/components/schemas/AuditLog" + first_id: type: string - enum: - - quoted_text - description: Type discriminator that is always `quoted_text`. - default: quoted_text - x-stainless-const: true - text: + example: "audit_log-defb456h8dks" + last_id: type: string - description: Quoted text content. - type: object + example: "audit_log-hnbkd8s93s" + has_more: + type: boolean + required: - - type - - text - title: User message quoted text - description: Quoted snippet that the user referenced in their message. - AttachmentType: - type: string - enum: - - image - - file - Attachment: + - object + - data + - first_id + - last_id + - has_more + + Invite: + type: object + description: Represents an individual `invite` to the organization. properties: - type: - $ref: '#/components/schemas/AttachmentType' - description: Attachment discriminator. + object: + type: string + enum: [organization.invite] + description: The object type, which is always `organization.invite` id: type: string - description: Identifier for the attachment. - name: + description: The identifier, which can be referenced in API endpoints + email: type: string - description: Original display name for the attachment. - mime_type: + description: The email address of the individual to whom the invite was sent + role: type: string - description: MIME type of the attachment. - preview_url: - anyOf: - - type: string - description: Preview URL for rendering the attachment inline. - - type: 'null' - type: object - required: - - type - - id - - name - - mime_type - - preview_url - title: Attachment - description: Attachment metadata included on thread items. - ToolChoice: - properties: - id: + enum: [owner, reader] + description: "`owner` or `reader`" + status: type: string - description: Identifier of the requested tool. - type: object + enum: [accepted, expired, pending] + description: "`accepted`,`expired`, or `pending`" + invited_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite was sent. + expires_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite expires. + accepted_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite was accepted. + required: + - object - id - title: Tool choice - description: Tool selection that the assistant should honor when executing the item. - InferenceOptions: - properties: - tool_choice: - anyOf: - - $ref: '#/components/schemas/ToolChoice' - description: Preferred tool to invoke. Defaults to null when ChatKit should auto-select. - - type: 'null' - model: - anyOf: - - type: string - description: Model name that generated the response. Defaults to null when using the session default. - - type: 'null' + - email + - role + - status + - invited_at + - expires_at + x-oaiMeta: + name: The invite object + example: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } + + InviteListResponse: type: object - required: - - tool_choice - - model - title: Inference options - description: Model and tool overrides applied when generating the assistant response. - UserMessageItem: properties: - id: - type: string - description: Identifier of the thread item. object: type: string - enum: - - chatkit.thread_item - description: Type discriminator that is always `chatkit.thread_item`. - default: chatkit.thread_item - x-stainless-const: true - created_at: - type: integer - description: Unix timestamp (in seconds) for when the item was created. - thread_id: - type: string - description: Identifier of the parent thread. - type: - type: string - enum: - - chatkit.user_message - default: chatkit.user_message - x-stainless-const: true - content: - items: - description: Content blocks that comprise a user message. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/UserMessageInputText' - - $ref: '#/components/schemas/UserMessageQuotedText' + enum: [list] + description: The object type, which is always `list` + data: type: array - description: Ordered content elements supplied by the user. - attachments: items: - $ref: '#/components/schemas/Attachment' - type: array - description: Attachments associated with the user message. Defaults to an empty list. - inference_options: - anyOf: - - $ref: '#/components/schemas/InferenceOptions' - description: Inference overrides applied to the message. Defaults to null when unset. - - type: 'null' - type: object + $ref: "#/components/schemas/Invite" + first_id: + type: string + description: The first `invite_id` in the retrieved `list` + last_id: + type: string + description: The last `invite_id` in the retrieved `list` + has_more: + type: boolean + description: The `has_more` property is used for pagination to indicate there are additional results. required: - - id - object - - created_at - - thread_id - - type - - content - - attachments - - inference_options - title: User Message Item - description: User-authored messages within a thread. - FileAnnotationSource: + - data + + InviteRequest: + type: object properties: - type: + email: type: string - enum: - - file - description: Type discriminator that is always `file`. - default: file - x-stainless-const: true - filename: + description: "Send an email to this address" + role: type: string - description: Filename referenced by the annotation. - type: object + enum: [reader, owner] + description: "`owner` or `reader`" required: - - type - - filename - title: File annotation source - description: Attachment source referenced by an annotation. - FileAnnotation: - properties: - type: - type: string - enum: - - file - description: Type discriminator that is always `file` for this annotation. - default: file - x-stainless-const: true - source: - $ref: '#/components/schemas/FileAnnotationSource' - description: File attachment referenced by the annotation. + - email + - role + + InviteDeleteResponse: type: object - required: - - type - - source - title: File annotation - description: Annotation that references an uploaded file. - UrlAnnotationSource: properties: - type: + object: type: string - enum: - - url - description: Type discriminator that is always `url`. - default: url - x-stainless-const: true - url: + enum: [organization.invite.deleted] + description: The object type, which is always `organization.invite.deleted` + id: type: string - description: URL referenced by the annotation. - type: object + deleted: + type: boolean required: - - type - - url - title: URL annotation source - description: URL backing an annotation entry. - UrlAnnotation: - properties: - type: - type: string - enum: - - url - description: Type discriminator that is always `url` for this annotation. - default: url - x-stainless-const: true - source: - $ref: '#/components/schemas/UrlAnnotationSource' - description: URL referenced by the annotation. + - object + - id + - deleted + + User: type: object - required: - - type - - source - title: URL annotation - description: Annotation that references a URL. - ResponseOutputText: + description: Represents an individual `user` within an organization. properties: - type: + object: type: string - enum: - - output_text - description: Type discriminator that is always `output_text`. - default: output_text - x-stainless-const: true - text: + enum: [organization.user] + description: The object type, which is always `organization.user` + id: type: string - description: Assistant generated text. - annotations: - items: - description: Annotation object describing a cited source. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/FileAnnotation' - - $ref: '#/components/schemas/UrlAnnotation' - type: array - description: Ordered list of annotations attached to the response text. - type: object + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: [owner, reader] + description: "`owner` or `reader`" + added_at: + type: integer + description: The Unix timestamp (in seconds) of when the user was added. required: - - type - - text - - annotations - title: Assistant message content - description: Assistant response text accompanied by optional annotations. - AssistantMessageItem: + - object + - id + - name + - email + - role + - added_at + x-oaiMeta: + name: The user object + example: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + + UserListResponse: + type: object properties: - id: - type: string - description: Identifier of the thread item. object: type: string - enum: - - chatkit.thread_item - description: Type discriminator that is always `chatkit.thread_item`. - default: chatkit.thread_item - x-stainless-const: true - created_at: - type: integer - description: Unix timestamp (in seconds) for when the item was created. - thread_id: + enum: [list] + data: + type: array + items: + $ref: "#/components/schemas/User" + first_id: type: string - description: Identifier of the parent thread. - type: + last_id: type: string - enum: - - chatkit.assistant_message - description: Type discriminator that is always `chatkit.assistant_message`. - default: chatkit.assistant_message - x-stainless-const: true - content: - items: - $ref: '#/components/schemas/ResponseOutputText' - type: array - description: Ordered assistant response segments. - type: object + has_more: + type: boolean required: - - id - object - - created_at - - thread_id - - type - - content - title: Assistant message - description: Assistant-authored message within a thread. - WidgetMessageItem: + - data + - first_id + - last_id + - has_more + + UserRoleUpdateRequest: + type: object properties: - id: + role: type: string - description: Identifier of the thread item. + enum: [owner, reader] + description: "`owner` or `reader`" + required: + - role + + UserDeleteResponse: + type: object + properties: object: type: string - enum: - - chatkit.thread_item - description: Type discriminator that is always `chatkit.thread_item`. - default: chatkit.thread_item - x-stainless-const: true - created_at: - type: integer - description: Unix timestamp (in seconds) for when the item was created. - thread_id: - type: string - description: Identifier of the parent thread. - type: - type: string - enum: - - chatkit.widget - description: Type discriminator that is always `chatkit.widget`. - default: chatkit.widget - x-stainless-const: true - widget: + enum: [organization.user.deleted] + id: type: string - description: Serialized widget payload rendered in the UI. - type: object + deleted: + type: boolean required: - - id - object - - created_at - - thread_id - - type - - widget - title: Widget message - description: Thread item that renders a widget payload. - ClientToolCallStatus: - type: string - enum: - - in_progress - - completed - ClientToolCallItem: + - id + - deleted + + Project: + type: object + description: Represents an individual project. properties: id: type: string - description: Identifier of the thread item. + description: The identifier, which can be referenced in API endpoints object: type: string - enum: - - chatkit.thread_item - description: Type discriminator that is always `chatkit.thread_item`. - default: chatkit.thread_item - x-stainless-const: true + enum: [organization.project] + description: The object type, which is always `organization.project` + name: + type: string + description: The name of the project. This appears in reporting. created_at: type: integer - description: Unix timestamp (in seconds) for when the item was created. - thread_id: - type: string - description: Identifier of the parent thread. - type: - type: string - enum: - - chatkit.client_tool_call - description: Type discriminator that is always `chatkit.client_tool_call`. - default: chatkit.client_tool_call - x-stainless-const: true + description: The Unix timestamp (in seconds) of when the project was created. + archived_at: + type: integer + nullable: true + description: The Unix timestamp (in seconds) of when the project was archived or `null`. status: - $ref: '#/components/schemas/ClientToolCallStatus' - description: Execution status for the tool call. - call_id: - type: string - description: Identifier for the client tool call. - name: - type: string - description: Tool name that was invoked. - arguments: type: string - description: JSON-encoded arguments that were sent to the tool. - output: - anyOf: - - type: string - description: JSON-encoded output captured from the tool. Defaults to null while execution is in progress. - - type: 'null' - type: object + enum: [active, archived] + description: "`active` or `archived`" required: - id - object + - name - created_at - - thread_id - - type - status - - call_id - - name - - arguments - - output - title: Client tool call - description: Record of a client side tool invocation initiated by the assistant. - TaskType: - type: string - enum: - - custom - - thought - TaskItem: + x-oaiMeta: + name: The project object + example: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + + ProjectListResponse: + type: object properties: - id: - type: string - description: Identifier of the thread item. object: type: string - enum: - - chatkit.thread_item - description: Type discriminator that is always `chatkit.thread_item`. - default: chatkit.thread_item - x-stainless-const: true - created_at: - type: integer - description: Unix timestamp (in seconds) for when the item was created. - thread_id: + enum: [list] + data: + type: array + items: + $ref: "#/components/schemas/Project" + first_id: type: string - description: Identifier of the parent thread. - type: + last_id: type: string - enum: - - chatkit.task - description: Type discriminator that is always `chatkit.task`. - default: chatkit.task - x-stainless-const: true - task_type: - $ref: '#/components/schemas/TaskType' - description: Subtype for the task. - heading: - anyOf: - - type: string - description: Optional heading for the task. Defaults to null when not provided. - - type: 'null' - summary: - anyOf: - - type: string - description: Optional summary that describes the task. Defaults to null when omitted. - - type: 'null' - type: object + has_more: + type: boolean required: - - id - object - - created_at - - thread_id - - type - - task_type - - heading - - summary - title: Task item - description: Task emitted by the workflow to show progress and status updates. - TaskGroupTask: + - data + - first_id + - last_id + - has_more + + ProjectCreateRequest: + type: object properties: - type: - $ref: '#/components/schemas/TaskType' - description: Subtype for the grouped task. - heading: - anyOf: - - type: string - description: Optional heading for the grouped task. Defaults to null when not provided. - - type: 'null' - summary: - anyOf: - - type: string - description: Optional summary that describes the grouped task. Defaults to null when omitted. - - type: 'null' + name: + type: string + description: The friendly name of the project, this name appears in reports. + required: + - name + + ProjectUpdateRequest: type: object + properties: + name: + type: string + description: The updated name of the project, this name appears in reports. required: - - type - - heading - - summary - title: Task group task - description: Task entry that appears within a TaskGroup. - TaskGroupItem: + - name + + DefaultProjectErrorResponse: + type: object properties: - id: + code: + type: integer + message: type: string - description: Identifier of the thread item. + required: + - code + - message + + ProjectUser: + type: object + description: Represents an individual user in a project. + properties: object: type: string - enum: - - chatkit.thread_item - description: Type discriminator that is always `chatkit.thread_item`. - default: chatkit.thread_item - x-stainless-const: true - created_at: - type: integer - description: Unix timestamp (in seconds) for when the item was created. - thread_id: + enum: [organization.project.user] + description: The object type, which is always `organization.project.user` + id: type: string - description: Identifier of the parent thread. - type: + description: The identifier, which can be referenced in API endpoints + name: type: string - enum: - - chatkit.task_group - description: Type discriminator that is always `chatkit.task_group`. - default: chatkit.task_group - x-stainless-const: true - tasks: - items: - $ref: '#/components/schemas/TaskGroupTask' - type: array - description: Tasks included in the group. - type: object + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: [owner, member] + description: "`owner` or `member`" + added_at: + type: integer + description: The Unix timestamp (in seconds) of when the project was added. + required: - - id - object - - created_at - - thread_id - - type - - tasks - title: Task group - description: Collection of workflow tasks grouped together in the thread. - ThreadItem: - title: The thread item - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/UserMessageItem' - - $ref: '#/components/schemas/AssistantMessageItem' - - $ref: '#/components/schemas/WidgetMessageItem' - - $ref: '#/components/schemas/ClientToolCallItem' - - $ref: '#/components/schemas/TaskItem' - - $ref: '#/components/schemas/TaskGroupItem' - ThreadItemListResource: + - id + - name + - email + - role + - added_at + x-oaiMeta: + name: The project user object + example: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + + ProjectUserListResponse: + type: object properties: object: - description: The type of object returned, must be `list`. - default: list - x-stainless-const: true - const: list + type: string data: - items: - $ref: '#/components/schemas/ThreadItem' type: array - description: A list of items + items: + $ref: "#/components/schemas/ProjectUser" first_id: - anyOf: - - type: string - description: The ID of the first item in the list. - - type: 'null' + type: string last_id: - anyOf: - - type: string - description: The ID of the last item in the list. - - type: 'null' + type: string has_more: type: boolean - description: Whether there are more items available. - type: object required: - object - data - first_id - last_id - has_more - title: Thread Items - description: A paginated list of thread items rendered for the ChatKit API. - ActiveStatus: + + ProjectUserCreateRequest: + type: object properties: - type: + user_id: type: string - enum: - - active - description: Status discriminator that is always `active`. - default: active - x-stainless-const: true - type: object + description: The ID of the user. + role: + type: string + enum: [owner, member] + description: "`owner` or `member`" required: - - type - title: Active thread status - description: Indicates that a thread is active. - LockedStatus: + - user_id + - role + + ProjectUserUpdateRequest: + type: object properties: - type: + role: type: string - enum: - - locked - description: Status discriminator that is always `locked`. - default: locked - x-stainless-const: true - reason: - anyOf: - - type: string - description: Reason that the thread was locked. Defaults to null when no reason is recorded. - - type: 'null' - type: object + enum: [owner, member] + description: "`owner` or `member`" required: - - type - - reason - title: Locked thread status - description: Indicates that a thread is locked and cannot accept new input. - ClosedStatus: + - role + + ProjectUserDeleteResponse: + type: object properties: - type: + object: type: string - enum: - - closed - description: Status discriminator that is always `closed`. - default: closed - x-stainless-const: true - reason: - anyOf: - - type: string - description: Reason that the thread was closed. Defaults to null when no reason is recorded. - - type: 'null' - type: object + enum: [organization.project.user.deleted] + id: + type: string + deleted: + type: boolean required: - - type - - reason - title: Closed thread status - description: Indicates that a thread has been closed. - ThreadResource: + - object + - id + - deleted + + ProjectServiceAccount: + type: object + description: Represents an individual service account in a project. properties: + object: + type: string + enum: [organization.project.service_account] + description: The object type, which is always `organization.project.service_account` id: type: string - description: Identifier of the thread. - object: + description: The identifier, which can be referenced in API endpoints + name: type: string - enum: - - chatkit.thread - description: Type discriminator that is always `chatkit.thread`. - default: chatkit.thread - x-stainless-const: true + description: The name of the service account + role: + type: string + enum: [owner, member] + description: "`owner` or `member`" created_at: type: integer - description: Unix timestamp (in seconds) for when the thread was created. - title: - anyOf: - - type: string - description: >- - Optional human-readable title for the thread. Defaults to null when no title has been - generated. - - type: 'null' - status: - description: Current status for the thread. Defaults to `active` for newly created threads. - discriminator: - propertyName: type - anyOf: - - $ref: '#/components/schemas/ActiveStatus' - - $ref: '#/components/schemas/LockedStatus' - - $ref: '#/components/schemas/ClosedStatus' - user: - type: string - description: Free-form string that identifies your end user who owns the thread. - type: object + description: The Unix timestamp (in seconds) of when the service account was created required: - - id - object + - id + - name + - role - created_at - - title - - status - - user - title: The thread object - description: Represents a ChatKit thread and its current status. - example: - id: cthr_def456 - object: chatkit.thread - created_at: 1712345600 - title: Demo feedback - status: - type: active - user: user_456 - DeletedThreadResource: - properties: - id: - type: string - description: Identifier of the deleted thread. - object: - type: string - enum: - - chatkit.thread.deleted - description: Type discriminator that is always `chatkit.thread.deleted`. - default: chatkit.thread.deleted - x-stainless-const: true - deleted: - type: boolean - description: Indicates that the thread has been deleted. + x-oaiMeta: + name: The project service account object + example: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + + ProjectServiceAccountListResponse: type: object - required: - - id - - object - - deleted - title: Deleted thread - description: Confirmation payload returned after deleting a thread. - ThreadListResource: properties: object: - description: The type of object returned, must be `list`. - default: list - x-stainless-const: true - const: list + type: string + enum: [list] data: - items: - $ref: '#/components/schemas/ThreadResource' type: array - description: A list of items + items: + $ref: "#/components/schemas/ProjectServiceAccount" first_id: - anyOf: - - type: string - description: The ID of the first item in the list. - - type: 'null' + type: string last_id: - anyOf: - - type: string - description: The ID of the last item in the list. - - type: 'null' + type: string has_more: type: boolean - description: Whether there are more items available. - type: object required: - object - data - first_id - last_id - has_more - title: Threads - description: A paginated list of ChatKit threads. - RealtimeConnectParams: - type: object - properties: - model: - type: string - call_id: - type: string - ModerationImageURLInput: + + ProjectServiceAccountCreateRequest: type: object - description: An object describing an image to classify. properties: - type: - description: Always `image_url`. + name: type: string - enum: - - image_url - x-stainless-const: true - image_url: - type: object - description: Contains either an image URL or a data URL for a base64 encoded image. - properties: - url: - type: string - description: Either a URL of the image or the base64 encoded image data. - format: uri - example: https://example.com/image.jpg - required: - - url + description: The name of the service account being created. required: - - type - - image_url - ModerationTextInput: + - name + + ProjectServiceAccountCreateResponse: type: object - description: An object describing text to classify. properties: - type: - description: Always `text`. + object: type: string - enum: - - text - x-stainless-const: true - text: - description: A string of text to classify. + enum: [organization.project.service_account] + id: type: string - example: I want to kill them - required: - - type - - text - ComparisonFilterValueItems: - anyOf: - - type: string - - type: number - ChunkingStrategyResponse: - type: object - description: The strategy used to chunk the file. - anyOf: - - $ref: '#/components/schemas/StaticChunkingStrategyResponseParam' - - $ref: '#/components/schemas/OtherChunkingStrategyResponseParam' - discriminator: - propertyName: type - FilePurpose: - description: > - The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision - fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets - type: string - enum: - - assistants - - batch - - fine-tune - - vision - - user_data - - evals - BatchError: - type: object - properties: - code: + name: type: string - description: An error code identifying the error type. - message: + role: type: string - description: A human-readable message providing more details about the error. - param: - anyOf: - - type: string - description: The name of the parameter that caused the error, if applicable. - - type: 'null' - line: - anyOf: - - type: integer - description: The line number of the input file where the error occurred, if applicable. - - type: 'null' - BatchRequestCounts: - type: object - properties: - total: - type: integer - description: Total number of requests in the batch. - completed: - type: integer - description: Number of requests that have been completed successfully. - failed: + enum: [member] + description: Service accounts can only have one role of type `member` + created_at: type: integer - description: Number of requests that have failed. - required: - - total - - completed - - failed - description: The request counts for different statuses within the batch. - AssistantTool: - anyOf: - - $ref: '#/components/schemas/AssistantToolsCode' - - $ref: '#/components/schemas/AssistantToolsFileSearch' - - $ref: '#/components/schemas/AssistantToolsFunction' - discriminator: - propertyName: type - TextAnnotationDelta: - anyOf: - - $ref: '#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject' - - $ref: '#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject' - discriminator: - propertyName: type - TextAnnotation: - anyOf: - - $ref: '#/components/schemas/MessageContentTextAnnotationsFileCitationObject' - - $ref: '#/components/schemas/MessageContentTextAnnotationsFilePathObject' - discriminator: - propertyName: type - RunStepDetailsToolCall: - anyOf: - - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeObject' - - $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchObject' - - $ref: '#/components/schemas/RunStepDetailsToolCallsFunctionObject' - discriminator: - propertyName: type - RunStepDeltaStepDetailsToolCall: - anyOf: - - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject' - - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject' - - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject' - discriminator: - propertyName: type - MessageContent: - anyOf: - - $ref: '#/components/schemas/MessageContentImageFileObject' - - $ref: '#/components/schemas/MessageContentImageUrlObject' - - $ref: '#/components/schemas/MessageContentTextObject' - - $ref: '#/components/schemas/MessageContentRefusalObject' - discriminator: - propertyName: type - MessageContentDelta: - anyOf: - - $ref: '#/components/schemas/MessageDeltaContentImageFileObject' - - $ref: '#/components/schemas/MessageDeltaContentTextObject' - - $ref: '#/components/schemas/MessageDeltaContentRefusalObject' - - $ref: '#/components/schemas/MessageDeltaContentImageUrlObject' - discriminator: - propertyName: type - ChatModel: - type: string - enum: - - gpt-5.1 - - gpt-5.1-2025-11-13 - - gpt-5.1-codex - - gpt-5.1-mini - - gpt-5.1-chat-latest - - gpt-5 - - gpt-5-mini - - gpt-5-nano - - gpt-5-2025-08-07 - - gpt-5-mini-2025-08-07 - - gpt-5-nano-2025-08-07 - - gpt-5-chat-latest - - gpt-4.1 - - gpt-4.1-mini - - gpt-4.1-nano - - gpt-4.1-2025-04-14 - - gpt-4.1-mini-2025-04-14 - - gpt-4.1-nano-2025-04-14 - - o4-mini - - o4-mini-2025-04-16 - - o3 - - o3-2025-04-16 - - o3-mini - - o3-mini-2025-01-31 - - o1 - - o1-2024-12-17 - - o1-preview - - o1-preview-2024-09-12 - - o1-mini - - o1-mini-2024-09-12 - - gpt-4o - - gpt-4o-2024-11-20 - - gpt-4o-2024-08-06 - - gpt-4o-2024-05-13 - - gpt-4o-audio-preview - - gpt-4o-audio-preview-2024-10-01 - - gpt-4o-audio-preview-2024-12-17 - - gpt-4o-audio-preview-2025-06-03 - - gpt-4o-mini-audio-preview - - gpt-4o-mini-audio-preview-2024-12-17 - - gpt-4o-search-preview - - gpt-4o-mini-search-preview - - gpt-4o-search-preview-2025-03-11 - - gpt-4o-mini-search-preview-2025-03-11 - - chatgpt-4o-latest - - codex-mini-latest - - gpt-4o-mini - - gpt-4o-mini-2024-07-18 - - gpt-4-turbo - - gpt-4-turbo-2024-04-09 - - gpt-4-0125-preview - - gpt-4-turbo-preview - - gpt-4-1106-preview - - gpt-4-vision-preview - - gpt-4 - - gpt-4-0314 - - gpt-4-0613 - - gpt-4-32k - - gpt-4-32k-0314 - - gpt-4-32k-0613 - - gpt-3.5-turbo - - gpt-3.5-turbo-16k - - gpt-3.5-turbo-0301 - - gpt-3.5-turbo-0613 - - gpt-3.5-turbo-1106 - - gpt-3.5-turbo-0125 - - gpt-3.5-turbo-16k-0613 - x-stainless-nominal: false - Summary: - properties: - type: - type: string - enum: - - summary_text - description: The type of the object. Always `summary_text`. - default: summary_text - x-stainless-const: true - text: - type: string - description: A summary of the reasoning output from the model so far. - type: object + api_key: + $ref: "#/components/schemas/ProjectServiceAccountApiKey" required: - - type - - text - title: Summary text - description: A summary text from the model. - CreateThreadAndRunRequestWithoutStream: + - object + - id + - name + - role + - created_at + - api_key + + ProjectServiceAccountApiKey: type: object - additionalProperties: false properties: - assistant_id: - description: >- - The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - execute this run. - type: string - thread: - $ref: '#/components/schemas/CreateThreadRequest' - model: - description: >- - The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute - this run. If a value is provided here, it will override the model associated with the assistant. - If not, the model associated with the assistant will be used. - anyOf: - - type: string - - type: string - enum: - - gpt-5 - - gpt-5-mini - - gpt-5-nano - - gpt-5-2025-08-07 - - gpt-5-mini-2025-08-07 - - gpt-5-nano-2025-08-07 - - gpt-4.1 - - gpt-4.1-mini - - gpt-4.1-nano - - gpt-4.1-2025-04-14 - - gpt-4.1-mini-2025-04-14 - - gpt-4.1-nano-2025-04-14 - - gpt-4o - - gpt-4o-2024-11-20 - - gpt-4o-2024-08-06 - - gpt-4o-2024-05-13 - - gpt-4o-mini - - gpt-4o-mini-2024-07-18 - - gpt-4.5-preview - - gpt-4.5-preview-2025-02-27 - - gpt-4-turbo - - gpt-4-turbo-2024-04-09 - - gpt-4-0125-preview - - gpt-4-turbo-preview - - gpt-4-1106-preview - - gpt-4-vision-preview - - gpt-4 - - gpt-4-0314 - - gpt-4-0613 - - gpt-4-32k - - gpt-4-32k-0314 - - gpt-4-32k-0613 - - gpt-3.5-turbo - - gpt-3.5-turbo-16k - - gpt-3.5-turbo-0613 - - gpt-3.5-turbo-1106 - - gpt-3.5-turbo-0125 - - gpt-3.5-turbo-16k-0613 - x-oaiTypeLabel: string - nullable: true - instructions: - description: >- - Override the default system message of the assistant. This is useful for modifying the behavior on - a per-run basis. + object: type: string - nullable: true - tools: - description: >- - Override the tools the assistant can use for this run. This is useful for modifying the behavior - on a per-run basis. - nullable: true - type: array - maxItems: 20 - items: - $ref: '#/components/schemas/AssistantTool' - tool_resources: - type: object - description: > - A set of resources that are used by the assistant's tools. The resources are specific to the type - of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the - `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: > - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available - to the `code_interpreter` tool. There can be a maximum of 20 files associated with the - tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: > - The ID of the [vector - store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to - this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - nullable: true - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model considers - the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the - top 10% probability mass are considered. - + enum: [organization.project.service_account.api_key] + description: The object type, which is always `organization.project.service_account.api_key` - We generally recommend altering this or temperature but not both. - max_prompt_tokens: - type: integer - nullable: true - description: > - The maximum number of prompt tokens that may be used over the course of the run. The run will make - a best effort to use only the number of prompt tokens specified, across multiple turns of the run. - If the run exceeds the number of prompt tokens specified, the run will end with status - `incomplete`. See `incomplete_details` for more info. - minimum: 256 - max_completion_tokens: - type: integer - nullable: true - description: > - The maximum number of completion tokens that may be used over the course of the run. The run will - make a best effort to use only the number of completion tokens specified, across multiple turns of - the run. If the run exceeds the number of completion tokens specified, the run will end with - status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - truncation_strategy: - allOf: - - $ref: '#/components/schemas/TruncationObject' - - nullable: true - tool_choice: - allOf: - - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - - nullable: true - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - response_format: - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - nullable: true - required: *ref_0 - CreateRunRequestWithoutStream: - type: object - additionalProperties: false - properties: - assistant_id: - description: >- - The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - execute this run. + value: type: string - model: - description: >- - The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute - this run. If a value is provided here, it will override the model associated with the assistant. - If not, the model associated with the assistant will be used. - anyOf: - - type: string - - $ref: '#/components/schemas/AssistantSupportedModels' - x-oaiTypeLabel: string - nullable: true - reasoning_effort: - $ref: '#/components/schemas/ReasoningEffort' - instructions: - description: >- - Overrides the - [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the - assistant. This is useful for modifying the behavior on a per-run basis. + name: type: string - nullable: true - additional_instructions: - description: >- - Appends additional instructions at the end of the instructions for the run. This is useful for - modifying the behavior on a per-run basis without overriding other instructions. + created_at: + type: integer + id: type: string - nullable: true - additional_messages: - description: Adds additional messages to the thread before creating the run. - type: array - items: - $ref: '#/components/schemas/CreateMessageRequest' - nullable: true - tools: - description: >- - Override the tools the assistant can use for this run. This is useful for modifying the behavior - on a per-run basis. - nullable: true - type: array - maxItems: 20 - items: - $ref: '#/components/schemas/AssistantTool' - metadata: - $ref: '#/components/schemas/Metadata' - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: > - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: > - An alternative to sampling with temperature, called nucleus sampling, where the model considers - the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the - top 10% probability mass are considered. - + required: + - object + - value + - name + - created_at + - id - We generally recommend altering this or temperature but not both. - max_prompt_tokens: - type: integer - nullable: true - description: > - The maximum number of prompt tokens that may be used over the course of the run. The run will make - a best effort to use only the number of prompt tokens specified, across multiple turns of the run. - If the run exceeds the number of prompt tokens specified, the run will end with status - `incomplete`. See `incomplete_details` for more info. - minimum: 256 - max_completion_tokens: - type: integer - nullable: true - description: > - The maximum number of completion tokens that may be used over the course of the run. The run will - make a best effort to use only the number of completion tokens specified, across multiple turns of - the run. If the run exceeds the number of completion tokens specified, the run will end with - status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - truncation_strategy: - allOf: - - $ref: '#/components/schemas/TruncationObject' - - nullable: true - tool_choice: - allOf: - - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' - - nullable: true - parallel_tool_calls: - $ref: '#/components/schemas/ParallelToolCalls' - response_format: - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' - nullable: true - required: *ref_0 - SubmitToolOutputsRunRequestWithoutStream: + ProjectServiceAccountDeleteResponse: type: object - additionalProperties: false properties: - tool_outputs: - description: A list of tools for which the outputs are being submitted. - type: array - items: - type: object - properties: - tool_call_id: - type: string - description: >- - The ID of the tool call in the `required_action` object within the run object the output is - being submitted for. - output: - type: string - description: The output of the tool call to be submitted to continue the run. + object: + type: string + enum: [organization.project.service_account.deleted] + id: + type: string + deleted: + type: boolean required: - - tool_outputs - RunStatus: - description: >- - The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, - `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. - type: string - enum: - - queued - - in_progress - - requires_action - - cancelling - - cancelled - - failed - - completed - - incomplete - - expired - RunStepDeltaObjectDelta: - description: The delta containing the fields that have changed on the run step. + - object + - id + - deleted + + ProjectApiKey: type: object + description: Represents an individual API key in a project. properties: - step_details: + object: + type: string + enum: [organization.project.api_key] + description: The object type, which is always `organization.project.api_key` + redacted_value: + type: string + description: The redacted value of the API key + name: + type: string + description: The name of the API key + created_at: + type: integer + description: The Unix timestamp (in seconds) of when the API key was created + id: + type: string + description: The identifier, which can be referenced in API endpoints + owner: type: object - description: The details of the run step. - anyOf: - - $ref: '#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject' - - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsObject' - discriminator: - propertyName: type - CodeInterpreterContainerAuto: + properties: + type: + type: string + enum: [user, service_account] + description: "`user` or `service_account`" + user: + $ref: "#/components/schemas/ProjectUser" + service_account: + $ref: "#/components/schemas/ProjectServiceAccount" + required: + - object + - redacted_value + - name + - created_at + - id + - owner + x-oaiMeta: + name: The project API key object + example: | + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } + + ProjectApiKeyListResponse: + type: object properties: - type: + object: type: string - enum: - - auto - description: Always `auto`. - default: auto - x-stainless-const: true - file_ids: - items: - type: string - example: file-123 + enum: [list] + data: type: array - maxItems: 50 - description: An optional list of uploaded files to make available to your code. - memory_limit: - anyOf: - - $ref: '#/components/schemas/ContainerMemoryLimit' - - type: 'null' + items: + $ref: "#/components/schemas/ProjectApiKey" + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + + ProjectApiKeyDeleteResponse: type: object + properties: + object: + type: string + enum: [organization.project.api_key.deleted] + id: + type: string + deleted: + type: boolean required: - - type - title: CodeInterpreterToolAuto - description: >- - Configuration for a code interpreter container. Optionally specify the IDs of the files to run the - code on. - x-stainless-naming: - go: - type_name: ToolCodeInterpreterContainerCodeInterpreterContainerAuto - securitySchemes: - ApiKeyAuth: - type: http - scheme: bearer + - object + - id + - deleted + +security: + - ApiKeyAuth: [] + x-oaiMeta: navigationGroups: - - id: responses - title: Responses API - - id: webhooks - title: Webhooks - id: endpoints - title: Platform APIs - - id: vector_stores - title: Vector stores - - id: chatkit - title: ChatKit - beta: true - - id: containers - title: Containers - - id: realtime - title: Realtime - - id: chat - title: Chat Completions + title: Endpoints - id: assistants title: Assistants - beta: true - id: administration title: Administration - id: legacy title: Legacy groups: - - id: responses - title: Responses - description: | - OpenAI's most advanced interface for generating model responses. Supports - text and image inputs, and text outputs. Create stateful interactions - with the model, using the output of previous responses as input. Extend - the model's capabilities with built-in tools for file search, web search, - computer use, and more. Allow the model access to external systems and data - using function calling. - - Related guides: - - [Quickstart](https://platform.openai.com/docs/quickstart?api-mode=responses) - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text?api-mode=responses) - - [Image inputs](https://platform.openai.com/docs/guides/images?api-mode=responses) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses) - - [Function calling](https://platform.openai.com/docs/guides/function-calling?api-mode=responses) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses) - - [Extend the models with tools](https://platform.openai.com/docs/guides/tools?api-mode=responses) - navigationGroup: responses - sections: - - type: endpoint - key: createResponse - path: create - - type: endpoint - key: getResponse - path: get - - type: endpoint - key: deleteResponse - path: delete - - type: endpoint - key: cancelResponse - path: cancel - - type: endpoint - key: listInputItems - path: input-items - - type: endpoint - key: Getinputtokencounts - path: input-tokens - - type: object - key: Response - path: object - - type: object - key: ResponseItemList - path: list - - id: conversations - title: Conversations - description: | - Create and manage conversations to store and retrieve conversation state across Response API calls. - navigationGroup: responses - sections: - - type: endpoint - key: createConversation - path: create - - type: endpoint - key: getConversation - path: retrieve - - type: endpoint - key: updateConversation - path: update - - type: endpoint - key: deleteConversation - path: delete - - type: endpoint - key: listConversationItems - path: list-items - - type: endpoint - key: createConversationItems - path: create-items - - type: endpoint - key: getConversationItem - path: get-item - - type: endpoint - key: deleteConversationItem - path: delete-item - - type: object - key: Conversation - path: object - - type: object - key: ConversationItemList - path: list-items-object - - id: responses-streaming - title: Streaming events - description: > - When you [create a Response](https://platform.openai.com/docs/api-reference/responses/create) with - - `stream` set to `true`, the server will emit server-sent events to the - - client as the Response is generated. This section contains the events that - - are emitted by the server. - - - [Learn more about streaming - responses](https://platform.openai.com/docs/guides/streaming-responses?api-mode=responses). - navigationGroup: responses - sections: - - type: object - key: ResponseCreatedEvent - path: - - type: object - key: ResponseInProgressEvent - path: - - type: object - key: ResponseCompletedEvent - path: - - type: object - key: ResponseFailedEvent - path: - - type: object - key: ResponseIncompleteEvent - path: - - type: object - key: ResponseOutputItemAddedEvent - path: - - type: object - key: ResponseOutputItemDoneEvent - path: - - type: object - key: ResponseContentPartAddedEvent - path: - - type: object - key: ResponseContentPartDoneEvent - path: - - type: object - key: ResponseTextDeltaEvent - path: response/output_text/delta - - type: object - key: ResponseTextDoneEvent - path: response/output_text/done - - type: object - key: ResponseRefusalDeltaEvent - path: - - type: object - key: ResponseRefusalDoneEvent - path: - - type: object - key: ResponseFunctionCallArgumentsDeltaEvent - path: - - type: object - key: ResponseFunctionCallArgumentsDoneEvent - path: - - type: object - key: ResponseFileSearchCallInProgressEvent - path: - - type: object - key: ResponseFileSearchCallSearchingEvent - path: - - type: object - key: ResponseFileSearchCallCompletedEvent - path: - - type: object - key: ResponseWebSearchCallInProgressEvent - path: - - type: object - key: ResponseWebSearchCallSearchingEvent - path: - - type: object - key: ResponseWebSearchCallCompletedEvent - path: - - type: object - key: ResponseReasoningSummaryPartAddedEvent - path: - - type: object - key: ResponseReasoningSummaryPartDoneEvent - path: - - type: object - key: ResponseReasoningSummaryTextDeltaEvent - path: - - type: object - key: ResponseReasoningSummaryTextDoneEvent - path: - - type: object - key: ResponseReasoningTextDeltaEvent - path: - - type: object - key: ResponseReasoningTextDoneEvent - path: - - type: object - key: ResponseImageGenCallCompletedEvent - path: - - type: object - key: ResponseImageGenCallGeneratingEvent - path: - - type: object - key: ResponseImageGenCallInProgressEvent - path: - - type: object - key: ResponseImageGenCallPartialImageEvent - path: - - type: object - key: ResponseMCPCallArgumentsDeltaEvent - path: - - type: object - key: ResponseMCPCallArgumentsDoneEvent - path: - - type: object - key: ResponseMCPCallCompletedEvent - path: - - type: object - key: ResponseMCPCallFailedEvent - path: - - type: object - key: ResponseMCPCallInProgressEvent - path: - - type: object - key: ResponseMCPListToolsCompletedEvent - path: - - type: object - key: ResponseMCPListToolsFailedEvent - path: - - type: object - key: ResponseMCPListToolsInProgressEvent - path: - - type: object - key: ResponseCodeInterpreterCallInProgressEvent - path: - - type: object - key: ResponseCodeInterpreterCallInterpretingEvent - path: - - type: object - key: ResponseCodeInterpreterCallCompletedEvent - path: - - type: object - key: ResponseCodeInterpreterCallCodeDeltaEvent - path: - - type: object - key: ResponseCodeInterpreterCallCodeDoneEvent - path: - - type: object - key: ResponseOutputTextAnnotationAddedEvent - path: - - type: object - key: ResponseQueuedEvent - path: - - type: object - key: ResponseCustomToolCallInputDeltaEvent - path: - - type: object - key: ResponseCustomToolCallInputDoneEvent - path: - - type: object - key: ResponseErrorEvent - path: - - id: webhook-events - title: Webhook Events - description: | - Webhooks are HTTP requests sent by OpenAI to a URL you specify when certain - events happen during the course of API usage. - - [Learn more about webhooks](https://platform.openai.com/docs/guides/webhooks). - navigationGroup: webhooks - sections: - - type: object - key: WebhookResponseCompleted - path: - - type: object - key: WebhookResponseCancelled - path: - - type: object - key: WebhookResponseFailed - path: - - type: object - key: WebhookResponseIncomplete - path: - - type: object - key: WebhookBatchCompleted - path: - - type: object - key: WebhookBatchCancelled - path: - - type: object - key: WebhookBatchExpired - path: - - type: object - key: WebhookBatchFailed - path: - - type: object - key: WebhookFineTuningJobSucceeded - path: - - type: object - key: WebhookFineTuningJobFailed - path: - - type: object - key: WebhookFineTuningJobCancelled - path: - - type: object - key: WebhookEvalRunSucceeded - path: - - type: object - key: WebhookEvalRunFailed - path: - - type: object - key: WebhookEvalRunCanceled - path: - - type: object - key: WebhookRealtimeCallIncoming - path: + # > General Notes + # The `groups` section is used to generate the API reference pages and navigation, in the same + # order listed below. Additionally, each `group` can have a list of `sections`, each of which + # will become a navigation subroute and subsection under the group. Each section has: + # - `type`: Currently, either an `endpoint` or `object`, depending on how the section needs to + # be rendered + # - `key`: The reference key that can be used to lookup the section definition + # - `path`: The path (url) of the section, which is used to generate the navigation link. + # + # > The `object` sections maps to a schema component and the following fields are read for rendering + # - `x-oaiMeta.name`: The name of the object, which will become the section title + # - `x-oaiMeta.example`: The example object, which will be used to generate the example sample (always JSON) + # - `description`: The description of the object, which will be used to generate the section description + # + # > The `endpoint` section maps to an operation path and the following fields are read for rendering: + # - `x-oaiMeta.name`: The name of the endpoint, which will become the section title + # - `x-oaiMeta.examples`: The endpoint examples, which can be an object (meaning a single variation, most + # endpoints, or an array of objects, meaning multiple variations, e.g. the + # chat completion and completion endpoints, with streamed and non-streamed examples. + # - `x-oaiMeta.returns`: text describing what the endpoint returns. + # - `summary`: The summary of the endpoint, which will be used to generate the section description - id: audio title: Audio description: | Learn how to turn audio into text or text into audio. - Related guide: [Speech to text](https://platform.openai.com/docs/guides/speech-to-text) + Related guide: [Speech to text](/docs/guides/speech-to-text) navigationGroup: endpoints sections: - type: endpoint @@ -67880,99 +16456,32 @@ x-oaiMeta: - type: object key: CreateTranscriptionResponseJson path: json-object - - type: object - key: CreateTranscriptionResponseDiarizedJson - path: diarized-json-object - type: object key: CreateTranscriptionResponseVerboseJson path: verbose-json-object - - type: object - key: SpeechAudioDeltaEvent - path: speech-audio-delta-event - - type: object - key: SpeechAudioDoneEvent - path: speech-audio-done-event - - type: object - key: TranscriptTextDeltaEvent - path: transcript-text-delta-event - - type: object - key: TranscriptTextSegmentEvent - path: transcript-text-segment-event - - type: object - key: TranscriptTextDoneEvent - path: transcript-text-done-event - - id: videos - title: Videos - description: | - Generate videos. - navigationGroup: endpoints - sections: - - type: endpoint - key: createVideo - path: create - - type: endpoint - key: CreateVideoRemix - path: remix - - type: endpoint - key: ListVideos - path: list - - type: endpoint - key: GetVideo - path: retrieve - - type: endpoint - key: DeleteVideo - path: delete - - type: endpoint - key: RetrieveVideoContent - path: content - - type: object - key: VideoResource - path: object - - id: images - title: Images + - id: chat + title: Chat description: | - Given a prompt and/or an input image, the model will generate a new image. - Related guide: [Image generation](https://platform.openai.com/docs/guides/images) + Given a list of messages comprising a conversation, the model will return a response. + + Related guide: [Chat Completions](/docs/guides/text-generation) navigationGroup: endpoints sections: - type: endpoint - key: createImage + key: createChatCompletion path: create - - type: endpoint - key: createImageEdit - path: createEdit - - type: endpoint - key: createImageVariation - path: createVariation - type: object - key: ImagesResponse + key: CreateChatCompletionResponse path: object - - id: images-streaming - title: Image Streaming - description: | - Stream image generation and editing in real time with server-sent events. - [Learn more about image streaming](https://platform.openai.com/docs/guides/image-generation). - navigationGroup: endpoints - sections: - - type: object - key: ImageGenPartialImageEvent - path: - type: object - key: ImageGenCompletedEvent - path: - - type: object - key: ImageEditPartialImageEvent - path: - - type: object - key: ImageEditCompletedEvent - path: + key: CreateChatCompletionStreamResponse + path: streaming - id: embeddings title: Embeddings - description: > - Get a vector representation of a given input that can be easily consumed by machine learning models - and algorithms. + description: | + Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. - Related guide: [Embeddings](https://platform.openai.com/docs/guides/embeddings) + Related guide: [Embeddings](/docs/guides/embeddings) navigationGroup: endpoints sections: - type: endpoint @@ -67981,103 +16490,12 @@ x-oaiMeta: - type: object key: Embedding path: object - - id: chatkit - title: ChatKit - beta: true - description: | - Manage ChatKit sessions, threads, and file uploads for internal integrations. - navigationGroup: chatkit - sections: - - type: endpoint - key: CreateChatSessionMethod - beta: true - path: sessions/create - - type: endpoint - key: CancelChatSessionMethod - beta: true - path: sessions/cancel - - type: endpoint - key: ListThreadsMethod - beta: true - path: threads/list - - type: endpoint - key: GetThreadMethod - beta: true - path: threads/retrieve - - type: endpoint - key: DeleteThreadMethod - beta: true - path: threads/delete - - type: endpoint - key: ListThreadItemsMethod - beta: true - path: threads/list-items - - type: object - key: ChatSessionResource - path: sessions/object - - type: object - key: ThreadResource - path: threads/object - - type: object - key: ThreadItemListResource - path: threads/item-list - - id: evals - title: Evals - description: | - Create, manage, and run evals in the OpenAI platform. - Related guide: [Evals](https://platform.openai.com/docs/guides/evals) - navigationGroup: endpoints - sections: - - type: endpoint - key: createEval - path: create - - type: endpoint - key: getEval - path: get - - type: endpoint - key: updateEval - path: update - - type: endpoint - key: deleteEval - path: delete - - type: endpoint - key: listEvals - path: list - - type: endpoint - key: getEvalRuns - path: getRuns - - type: endpoint - key: getEvalRun - path: getRun - - type: endpoint - key: createEvalRun - path: createRun - - type: endpoint - key: cancelEvalRun - path: cancelRun - - type: endpoint - key: deleteEvalRun - path: deleteRun - - type: endpoint - key: getEvalRunOutputItem - path: getRunOutputItem - - type: endpoint - key: getEvalRunOutputItems - path: getRunOutputItems - - type: object - key: Eval - path: object - - type: object - key: EvalRun - path: run-object - - type: object - key: EvalRunOutputItem - path: run-output-item-object - id: fine-tuning title: Fine-tuning description: | Manage fine-tuning jobs to tailor a model to your specific training data. - Related guide: [Fine-tune models](https://platform.openai.com/docs/guides/fine-tuning) + + Related guide: [Fine-tune models](/docs/guides/fine-tuning) navigationGroup: endpoints sections: - type: endpoint @@ -68093,637 +16511,163 @@ x-oaiMeta: key: listFineTuningJobCheckpoints path: list-checkpoints - type: endpoint - key: listFineTuningCheckpointPermissions - path: list-permissions - - type: endpoint - key: createFineTuningCheckpointPermission - path: create-permission - - type: endpoint - key: deleteFineTuningCheckpointPermission - path: delete-permission - - type: endpoint - key: retrieveFineTuningJob - path: retrieve - - type: endpoint - key: cancelFineTuningJob - path: cancel - - type: endpoint - key: resumeFineTuningJob - path: resume - - type: endpoint - key: pauseFineTuningJob - path: pause - - type: object - key: FineTuneChatRequestInput - path: chat-input - - type: object - key: FineTunePreferenceRequestInput - path: preference-input - - type: object - key: FineTuneReinforcementRequestInput - path: reinforcement-input - - type: object - key: FineTuningJob - path: object - - type: object - key: FineTuningJobEvent - path: event-object - - type: object - key: FineTuningJobCheckpoint - path: checkpoint-object - - type: object - key: FineTuningCheckpointPermission - path: permission-object - - id: graders - title: Graders - description: | - Manage and run graders in the OpenAI platform. - Related guide: [Graders](https://platform.openai.com/docs/guides/graders) - navigationGroup: endpoints - sections: - - type: object - key: GraderStringCheck - path: string-check - - type: object - key: GraderTextSimilarity - path: text-similarity - - type: object - key: GraderScoreModel - path: score-model - - type: object - key: GraderLabelModel - path: label-model - - type: object - key: GraderPython - path: python - - type: object - key: GraderMulti - path: multi - - type: endpoint - key: runGrader - path: run - - type: endpoint - key: validateGrader - path: validate - beta: true - - id: batch - title: Batch - description: > - Create large batches of API requests for asynchronous processing. The Batch API returns completions - within 24 hours for a 50% discount. - - Related guide: [Batch](https://platform.openai.com/docs/guides/batch) - navigationGroup: endpoints - sections: - - type: endpoint - key: createBatch - path: create - - type: endpoint - key: retrieveBatch - path: retrieve - - type: endpoint - key: cancelBatch - path: cancel - - type: endpoint - key: listBatches - path: list - - type: object - key: Batch - path: object - - type: object - key: BatchRequestInput - path: request-input - - type: object - key: BatchRequestOutput - path: request-output - - id: files - title: Files - description: > - Files are used to upload documents that can be used with features like - [Assistants](https://platform.openai.com/docs/api-reference/assistants), - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning), and [Batch - API](https://platform.openai.com/docs/guides/batch). - navigationGroup: endpoints - sections: - - type: endpoint - key: createFile - path: create - - type: endpoint - key: listFiles - path: list - - type: endpoint - key: retrieveFile - path: retrieve - - type: endpoint - key: deleteFile - path: delete - - type: endpoint - key: downloadFile - path: retrieve-contents - - type: object - key: OpenAIFile - path: object - - id: uploads - title: Uploads - description: | - Allows you to upload large files in multiple parts. - navigationGroup: endpoints - sections: - - type: endpoint - key: createUpload - path: create - - type: endpoint - key: addUploadPart - path: add-part - - type: endpoint - key: completeUpload - path: complete - - type: endpoint - key: cancelUpload - path: cancel - - type: object - key: Upload - path: object - - type: object - key: UploadPart - path: part-object - - id: models - title: Models - description: > - List and describe the various models available in the API. You can refer to the - [Models](https://platform.openai.com/docs/models) documentation to understand what models are - available and the differences between them. - navigationGroup: endpoints - sections: - - type: endpoint - key: listModels - path: list - - type: endpoint - key: retrieveModel - path: retrieve - - type: endpoint - key: deleteModel - path: delete - - type: object - key: Model - path: object - - id: moderations - title: Moderations - description: > - Given text and/or image inputs, classifies if those inputs are potentially harmful across several - categories. - - Related guide: [Moderations](https://platform.openai.com/docs/guides/moderation) - navigationGroup: endpoints - sections: - - type: endpoint - key: createModeration - path: create - - type: object - key: CreateModerationResponse - path: object - - id: vector-stores - title: Vector stores - description: > - Vector stores power semantic search for the Retrieval API and the `file_search` tool in the Responses - and Assistants APIs. - - - Related guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search) - navigationGroup: vector_stores - sections: - - type: endpoint - key: createVectorStore - path: create - - type: endpoint - key: listVectorStores - path: list - - type: endpoint - key: getVectorStore - path: retrieve - - type: endpoint - key: modifyVectorStore - path: modify - - type: endpoint - key: deleteVectorStore - path: delete - - type: endpoint - key: searchVectorStore - path: search - - type: object - key: VectorStoreObject - path: object - - id: vector-stores-files - title: Vector store files - description: | - Vector store files represent files inside a vector store. - - Related guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search) - navigationGroup: vector_stores - sections: - - type: endpoint - key: createVectorStoreFile - path: createFile - - type: endpoint - key: listVectorStoreFiles - path: listFiles - - type: endpoint - key: getVectorStoreFile - path: getFile - - type: endpoint - key: retrieveVectorStoreFileContent - path: getContent - - type: endpoint - key: updateVectorStoreFileAttributes - path: updateAttributes - - type: endpoint - key: deleteVectorStoreFile - path: deleteFile - - type: object - key: VectorStoreFileObject - path: file-object - - id: vector-stores-file-batches - title: Vector store file batches - description: | - Vector store file batches represent operations to add multiple files to a vector store. - Related guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search) - navigationGroup: vector_stores - sections: - - type: endpoint - key: createVectorStoreFileBatch - path: createBatch - - type: endpoint - key: getVectorStoreFileBatch - path: getBatch - - type: endpoint - key: cancelVectorStoreFileBatch - path: cancelBatch + key: retrieveFineTuningJob + path: retrieve - type: endpoint - key: listFilesInVectorStoreBatch - path: listBatchFiles + key: cancelFineTuningJob + path: cancel - type: object - key: VectorStoreFileBatchObject - path: batch-object - - id: containers - title: Containers + key: FinetuneChatRequestInput + path: chat-input + - type: object + key: FinetuneCompletionRequestInput + path: completions-input + - type: object + key: FineTuningJob + path: object + - type: object + key: FineTuningJobEvent + path: event-object + - type: object + key: FineTuningJobCheckpoint + path: checkpoint-object + - id: batch + title: Batch description: | - Create and manage containers for use with the Code Interpreter tool. - navigationGroup: containers + Create large batches of API requests for asynchronous processing. The Batch API returns completions within 24 hours for a 50% discount. + + Related guide: [Batch](/docs/guides/batch) + navigationGroup: endpoints sections: - type: endpoint - key: CreateContainer - path: createContainers + key: createBatch + path: create - type: endpoint - key: ListContainers - path: listContainers + key: retrieveBatch + path: retrieve - type: endpoint - key: RetrieveContainer - path: retrieveContainer + key: cancelBatch + path: cancel - type: endpoint - key: DeleteContainer - path: deleteContainer + key: listBatches + path: list - type: object - key: ContainerResource + key: Batch path: object - - id: container-files - title: Container Files + - type: object + key: BatchRequestInput + path: request-input + - type: object + key: BatchRequestOutput + path: request-output + - id: files + title: Files description: | - Create and manage container files for use with the Code Interpreter tool. - navigationGroup: containers + Files are used to upload documents that can be used with features like [Assistants](/docs/api-reference/assistants), [Fine-tuning](/docs/api-reference/fine-tuning), and [Batch API](/docs/guides/batch). + navigationGroup: endpoints sections: - type: endpoint - key: CreateContainerFile - path: createContainerFile + key: createFile + path: create - type: endpoint - key: ListContainerFiles - path: listContainerFiles + key: listFiles + path: list - type: endpoint - key: RetrieveContainerFile - path: retrieveContainerFile + key: retrieveFile + path: retrieve - type: endpoint - key: RetrieveContainerFileContent - path: retrieveContainerFileContent + key: deleteFile + path: delete - type: endpoint - key: DeleteContainerFile - path: deleteContainerFile + key: downloadFile + path: retrieve-contents - type: object - key: ContainerFileResource + key: OpenAIFile path: object - - id: realtime - title: Realtime - description: | - Communicate with a multimodal model in real time over low latency interfaces - like WebRTC, WebSocket, and SIP. Natively supports speech-to-speech - as well as text, image, and audio inputs and outputs. - - [Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime). - navigationGroup: realtime - sections: - - type: endpoint - key: create-realtime-call - path: create-call - - id: realtime-sessions - title: Client secrets - description: > - REST API endpoint to generate ephemeral client secrets for use in client-side - - applications. Client secrets are short-lived tokens that can be passed to a client app, - - such as a web frontend or mobile client, which grants access to the Realtime API without - - leaking your main API key. You can configure a custom TTL for each client secret. - - - You can also attach session configuration options to the client secret, which will be - - applied to any sessions created using that client secret, but these can also be overridden - - by the client connection. - - - [Learn more about authentication with client secrets over - WebRTC](https://platform.openai.com/docs/guides/realtime-webrtc). - navigationGroup: realtime - sections: - - type: endpoint - key: create-realtime-client-secret - path: create-realtime-client-secret - - type: object - key: RealtimeCreateClientSecretResponse - path: create-secret-response - - id: realtime-calls - title: Calls + - id: uploads + title: Uploads description: | - REST endpoints for controlling WebRTC or SIP calls with the Realtime API. - Accept or reject an incoming call, transfer it to another destination, or hang up the - call once you are finished. - navigationGroup: realtime + Allows you to upload large files in multiple parts. + navigationGroup: endpoints sections: - type: endpoint - key: accept-realtime-call - path: accept-call + key: createUpload + path: create - type: endpoint - key: reject-realtime-call - path: reject-call + key: addUploadPart + path: add-part - type: endpoint - key: refer-realtime-call - path: refer-call + key: completeUpload + path: complete - type: endpoint - key: hangup-realtime-call - path: hangup-call - - id: realtime-client-events - title: Client events - description: | - These are events that the OpenAI Realtime WebSocket server will accept from the client. - navigationGroup: realtime - sections: - - type: object - key: RealtimeClientEventSessionUpdate - path: - - type: object - key: RealtimeClientEventInputAudioBufferAppend - path: - - type: object - key: RealtimeClientEventInputAudioBufferCommit - path: - - type: object - key: RealtimeClientEventInputAudioBufferClear - path: - - type: object - key: RealtimeClientEventConversationItemCreate - path: - - type: object - key: RealtimeClientEventConversationItemRetrieve - path: - - type: object - key: RealtimeClientEventConversationItemTruncate - path: - - type: object - key: RealtimeClientEventConversationItemDelete - path: - - type: object - key: RealtimeClientEventResponseCreate - path: + key: cancelUpload + path: cancel - type: object - key: RealtimeClientEventResponseCancel - path: + key: Upload + path: object - type: object - key: RealtimeClientEventOutputAudioBufferClear - path: - - id: realtime-server-events - title: Server events + key: UploadPart + path: part-object + - id: images + title: Images description: | - These are events emitted from the OpenAI Realtime WebSocket server to the client. - navigationGroup: realtime - sections: - - type: object - key: RealtimeServerEventError - path: - - type: object - key: RealtimeServerEventSessionCreated - path: - - type: object - key: RealtimeServerEventSessionUpdated - path: - - type: object - key: RealtimeServerEventConversationItemAdded - path: - - type: object - key: RealtimeServerEventConversationItemDone - path: - - type: object - key: RealtimeServerEventConversationItemRetrieved - path: - - type: object - key: RealtimeServerEventConversationItemInputAudioTranscriptionCompleted - path: - - type: object - key: RealtimeServerEventConversationItemInputAudioTranscriptionDelta - path: - - type: object - key: RealtimeServerEventConversationItemInputAudioTranscriptionSegment - path: - - type: object - key: RealtimeServerEventConversationItemInputAudioTranscriptionFailed - path: - - type: object - key: RealtimeServerEventConversationItemTruncated - path: - - type: object - key: RealtimeServerEventConversationItemDeleted - path: - - type: object - key: RealtimeServerEventInputAudioBufferCommitted - path: - - type: object - key: RealtimeServerEventInputAudioBufferCleared - path: - - type: object - key: RealtimeServerEventInputAudioBufferSpeechStarted - path: - - type: object - key: RealtimeServerEventInputAudioBufferSpeechStopped - path: - - type: object - key: RealtimeServerEventInputAudioBufferTimeoutTriggered - path: - - type: object - key: RealtimeServerEventOutputAudioBufferStarted - path: - - type: object - key: RealtimeServerEventOutputAudioBufferStopped - path: - - type: object - key: RealtimeServerEventOutputAudioBufferCleared - path: - - type: object - key: RealtimeServerEventResponseCreated - path: - - type: object - key: RealtimeServerEventResponseDone - path: - - type: object - key: RealtimeServerEventResponseOutputItemAdded - path: - - type: object - key: RealtimeServerEventResponseOutputItemDone - path: - - type: object - key: RealtimeServerEventResponseContentPartAdded - path: - - type: object - key: RealtimeServerEventResponseContentPartDone - path: - - type: object - key: RealtimeServerEventResponseTextDelta - path: - - type: object - key: RealtimeServerEventResponseTextDone - path: - - type: object - key: RealtimeServerEventResponseAudioTranscriptDelta - path: - - type: object - key: RealtimeServerEventResponseAudioTranscriptDone - path: - - type: object - key: RealtimeServerEventResponseAudioDelta - path: - - type: object - key: RealtimeServerEventResponseAudioDone - path: - - type: object - key: RealtimeServerEventResponseFunctionCallArgumentsDelta - path: - - type: object - key: RealtimeServerEventResponseFunctionCallArgumentsDone - path: - - type: object - key: RealtimeServerEventResponseMCPCallArgumentsDelta - path: - - type: object - key: RealtimeServerEventResponseMCPCallArgumentsDone - path: - - type: object - key: RealtimeServerEventResponseMCPCallInProgress - path: - - type: object - key: RealtimeServerEventResponseMCPCallCompleted - path: - - type: object - key: RealtimeServerEventResponseMCPCallFailed - path: - - type: object - key: RealtimeServerEventMCPListToolsInProgress - path: - - type: object - key: RealtimeServerEventMCPListToolsCompleted - path: - - type: object - key: RealtimeServerEventMCPListToolsFailed - path: - - type: object - key: RealtimeServerEventRateLimitsUpdated - path: - - id: chat - title: Chat Completions - description: > - The Chat Completions API endpoint will generate a model response from a - - list of messages comprising a conversation. - - - Related guides: - - - [Quickstart](https://platform.openai.com/docs/quickstart?api-mode=chat) - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text?api-mode=chat) - - - [Image inputs](https://platform.openai.com/docs/guides/images?api-mode=chat) - - - [Audio inputs and outputs](https://platform.openai.com/docs/guides/audio?api-mode=chat) - - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat) - - - [Function calling](https://platform.openai.com/docs/guides/function-calling?api-mode=chat) - - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=chat) - - - **Starting a new project?** We recommend trying - [Responses](https://platform.openai.com/docs/api-reference/responses) - - to take advantage of the latest OpenAI platform features. Compare + Given a prompt and/or an input image, the model will generate a new image. - [Chat Completions with - Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). - navigationGroup: chat + Related guide: [Image generation](/docs/guides/images) + navigationGroup: endpoints sections: - type: endpoint - key: createChatCompletion + key: createImage path: create - type: endpoint - key: getChatCompletion - path: get + key: createImageEdit + path: createEdit - type: endpoint - key: getChatCompletionMessages - path: getMessages + key: createImageVariation + path: createVariation + - type: object + key: Image + path: object + - id: models + title: Models + description: | + List and describe the various models available in the API. You can refer to the [Models](/docs/models) documentation to understand what models are available and the differences between them. + navigationGroup: endpoints + sections: - type: endpoint - key: listChatCompletions + key: listModels path: list - type: endpoint - key: updateChatCompletion - path: update + key: retrieveModel + path: retrieve - type: endpoint - key: deleteChatCompletion + key: deleteModel path: delete - type: object - key: CreateChatCompletionResponse + key: Model path: object - - type: object - key: ChatCompletionList - path: list-object - - type: object - key: ChatCompletionMessageList - path: message-list - - id: chat-streaming - title: Streaming + - id: moderations + title: Moderations description: | - Stream Chat Completions in real time. Receive chunks of completions - returned from the model using server-sent events. - [Learn more](https://platform.openai.com/docs/guides/streaming-responses?api-mode=chat). - navigationGroup: chat + Given some input text, outputs if the model classifies it as potentially harmful across several categories. + + Related guide: [Moderations](/docs/guides/moderation) + navigationGroup: endpoints sections: + - type: endpoint + key: createModeration + path: create - type: object - key: CreateChatCompletionStreamResponse - path: streaming + key: CreateModerationResponse + path: object + - id: assistants title: Assistants beta: true description: | Build assistants that can call models and use tools to perform tasks. - [Get started with the Assistants API](https://platform.openai.com/docs/assistants) + [Get started with the Assistants API](/docs/assistants) navigationGroup: assistants sections: - type: endpoint @@ -68750,7 +16694,7 @@ x-oaiMeta: description: | Create threads that assistants can interact with. - Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) + Related guide: [Assistants](/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint @@ -68774,7 +16718,7 @@ x-oaiMeta: description: | Create messages within threads - Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) + Related guide: [Assistants](/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint @@ -68801,7 +16745,7 @@ x-oaiMeta: description: | Represents an execution run on a thread. - Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) + Related guide: [Assistants](/docs/assistants/overview) navigationGroup: assistants sections: - type: endpoint @@ -68829,41 +16773,110 @@ x-oaiMeta: key: RunObject path: object - id: run-steps - title: Run steps + title: Run Steps + beta: true + description: | + Represents the steps (model and tool calls) taken during the run. + + Related guide: [Assistants](/docs/assistants/overview) + navigationGroup: assistants + sections: + - type: endpoint + key: listRunSteps + path: listRunSteps + - type: endpoint + key: getRunStep + path: getRunStep + - type: object + key: RunStepObject + path: step-object + - id: vector-stores + title: Vector Stores + beta: true + description: | + Vector stores are used to store files for use by the `file_search` tool. + + Related guide: [File Search](/docs/assistants/tools/file-search) + navigationGroup: assistants + sections: + - type: endpoint + key: createVectorStore + path: create + - type: endpoint + key: listVectorStores + path: list + - type: endpoint + key: getVectorStore + path: retrieve + - type: endpoint + key: modifyVectorStore + path: modify + - type: endpoint + key: deleteVectorStore + path: delete + - type: object + key: VectorStoreObject + path: object + - id: vector-stores-files + title: Vector Store Files + beta: true + description: | + Vector store files represent files inside a vector store. + + Related guide: [File Search](/docs/assistants/tools/file-search) + navigationGroup: assistants + sections: + - type: endpoint + key: createVectorStoreFile + path: createFile + - type: endpoint + key: listVectorStoreFiles + path: listFiles + - type: endpoint + key: getVectorStoreFile + path: getFile + - type: endpoint + key: deleteVectorStoreFile + path: deleteFile + - type: object + key: VectorStoreFileObject + path: file-object + - id: vector-stores-file-batches + title: Vector Store File Batches beta: true description: | - Represents the steps (model and tool calls) taken during the run. + Vector store file batches represent operations to add multiple files to a vector store. - Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview) + Related guide: [File Search](/docs/assistants/tools/file-search) navigationGroup: assistants sections: - type: endpoint - key: listRunSteps - path: listRunSteps + key: createVectorStoreFileBatch + path: createBatch - type: endpoint - key: getRunStep - path: getRunStep + key: getVectorStoreFileBatch + path: getBatch + - type: endpoint + key: cancelVectorStoreFileBatch + path: cancelBatch + - type: endpoint + key: listFilesInVectorStoreBatch + path: listBatchFiles - type: object - key: RunStepObject - path: step-object + key: VectorStoreFileBatchObject + path: batch-object - id: assistants-streaming title: Streaming beta: true - description: > + description: | Stream the result of executing a Run or resuming a Run after submitting tool outputs. - You can stream events from the [Create Thread and - Run](https://platform.openai.com/docs/api-reference/runs/createThreadAndRun), - - [Create Run](https://platform.openai.com/docs/api-reference/runs/createRun), and [Submit Tool - Outputs](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) - - endpoints by passing `"stream": true`. The response will be a [Server-Sent - events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) stream. + You can stream events from the [Create Thread and Run](/docs/api-reference/runs/createThreadAndRun), + [Create Run](/docs/api-reference/runs/createRun), and [Submit Tool Outputs](/docs/api-reference/runs/submitToolOutputs) + endpoints by passing `"stream": true`. The response will be a [Server-Sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) stream. Our Node and Python SDKs provide helpful utilities to make streaming easy. Reference the - - [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn more. + [Assistants API quickstart](/docs/assistants/overview) to learn more. navigationGroup: assistants sections: - type: object @@ -68875,73 +16888,23 @@ x-oaiMeta: - type: object key: AssistantStreamEvent path: events + - id: administration - title: Administration - description: > - Programmatically manage your organization. + title: Overview + description: | + Programmatically manage your organization. - The Audit Logs endpoint provides a log of all actions taken in the organization for security and - monitoring purposes. + The Audit Logs endpoint provides a log of all actions taken in the + organization for security and monitoring purposes. - To access these endpoints please generate an Admin API Key through the [API Platform Organization - overview](/organization/admin-keys). Admin API keys cannot be used for non-administration endpoints. + To access these endpoints please generate an Admin API Key through the [API Platform Organization overview](/organization/admin-keys). Admin API keys cannot be used for non-administration endpoints. - For best practices on setting up your organization, please refer to this - [guide](https://platform.openai.com/docs/guides/production-best-practices#setting-up-your-organization) + For best practices on setting up your organization, please refer to this [guide](/docs/guides/production-best-practices/setting-up-your-organization) navigationGroup: administration - - id: admin-api-keys - title: Admin API Keys - description: > - Admin API keys enable Organization Owners to programmatically manage various aspects of their - organization, including users, projects, and API keys. These keys provide administrative capabilities, - such as creating, updating, and deleting users; managing projects; and overseeing API key lifecycles. - - Key Features of Admin API Keys: - - - - User Management: Invite new users, update roles, and remove users from the organization. - - - - Project Management: Create, update, archive projects, and manage user assignments within projects. - - - - API Key Oversight: List, retrieve, and delete API keys associated with projects. - - - Only Organization Owners have the authority to create and utilize Admin API keys. To manage these - keys, Organization Owners can navigate to the Admin Keys section of their API Platform dashboard. - - - For direct access to the Admin Keys management page, Organization Owners can use the following link: - - - [https://platform.openai.com/settings/organization/admin-keys](https://platform.openai.com/settings/organization/admin-keys) - - - It's crucial to handle Admin API keys with care due to their elevated permissions. Adhering to best - practices, such as regular key rotation and assigning appropriate permissions, enhances security and - ensures proper governance within the organization. - navigationGroup: administration - sections: - - type: endpoint - key: admin-api-keys-list - path: list - - type: endpoint - key: admin-api-keys-create - path: create - - type: endpoint - key: admin-api-keys-get - path: listget - - type: endpoint - key: admin-api-keys-delete - path: delete - - type: object - key: AdminApiKey - path: object - id: invite title: Invites - description: Invite and manage invitations for an organization. + description: Invite and manage invitations for an organization. Invited users are automatically added to the Default project. navigationGroup: administration sections: - type: endpoint @@ -68959,10 +16922,11 @@ x-oaiMeta: - type: object key: Invite path: object + - id: users title: Users description: | - Manage users and their role in an organization. + Manage users and their role in an organization. Users will be automatically added to the Default project. navigationGroup: administration sections: - type: endpoint @@ -68980,127 +16944,12 @@ x-oaiMeta: - type: object key: User path: object - - id: groups - title: Groups - description: > - Manage reusable collections of users for organization-wide access control and maintain their - membership. - navigationGroup: administration - sections: - - type: endpoint - key: list-groups - path: list - - type: endpoint - key: create-group - path: create - - type: endpoint - key: update-group - path: update - - type: endpoint - key: delete-group - path: delete - - type: endpoint - key: list-group-users - path: users/list - - type: endpoint - key: add-group-user - path: users/add - - type: endpoint - key: remove-group-user - path: users/delete - - type: object - key: GroupUserAssignment - path: users/assignment-object - - type: object - key: Group - path: object - - id: roles - title: Roles - description: > - Create and manage custom roles that can be assigned to groups and users at the organization or project - level. - navigationGroup: administration - sections: - - type: endpoint - key: list-roles - path: list - - type: endpoint - key: create-role - path: create - - type: endpoint - key: update-role - path: update - - type: endpoint - key: delete-role - path: delete - - type: endpoint - key: list-project-roles - path: project/list - - type: endpoint - key: create-project-role - path: project/create - - type: endpoint - key: update-project-role - path: project/update - - type: endpoint - key: delete-project-role - path: project/delete - - type: object - key: Role - path: object - - id: role-assignments - title: Role assignments - description: | - Assign and remove roles for users and groups at the organization or project level. - navigationGroup: administration - sections: - - type: endpoint - key: list-group-role-assignments - path: organization/groups/list - - type: endpoint - key: assign-group-role - path: organization/groups/assign - - type: endpoint - key: unassign-group-role - path: organization/groups/delete - - type: endpoint - key: list-user-role-assignments - path: organization/users/list - - type: endpoint - key: assign-user-role - path: organization/users/assign - - type: endpoint - key: unassign-user-role - path: organization/users/delete - - type: endpoint - key: list-project-group-role-assignments - path: projects/groups/list - - type: endpoint - key: assign-project-group-role - path: projects/groups/assign - - type: endpoint - key: unassign-project-group-role - path: projects/groups/delete - - type: endpoint - key: list-project-user-role-assignments - path: projects/users/list - - type: endpoint - key: assign-project-user-role - path: projects/users/assign - - type: endpoint - key: unassign-project-user-role - path: projects/users/delete - - type: object - key: GroupRoleAssignment - path: objects/group - - type: object - key: UserRoleAssignment - path: objects/user + - id: projects title: Projects description: | - Manage the projects within an orgnanization includes creation, updating, and archiving or projects. - The Default project cannot be archived. + Manage the projects within an orgnanization includes creation, updating, and archiving or projects. + The Default project cannot be modified or archived. navigationGroup: administration sections: - type: endpoint @@ -69121,10 +16970,12 @@ x-oaiMeta: - type: object key: Project path: object + - id: project-users - title: Project users + title: Project Users description: | - Manage users within a project, including adding, updating roles, and removing users. + Manage users within a project, including adding, updating roles, and removing users. + Users cannot be removed from the Default project, unless they are being removed from the organization. navigationGroup: administration sections: - type: endpoint @@ -69132,7 +16983,7 @@ x-oaiMeta: path: list - type: endpoint key: create-project-user - path: create + path: creeate - type: endpoint key: retrieve-project-user path: retrieve @@ -69145,33 +16996,12 @@ x-oaiMeta: - type: object key: ProjectUser path: object - - id: project-groups - title: Project groups - description: | - Manage which groups have access to a project and the role they receive. - navigationGroup: administration - sections: - - type: endpoint - key: list-project-groups - path: list - - type: endpoint - key: add-project-group - path: add - - type: endpoint - key: remove-project-group - path: delete - - type: object - key: ProjectGroup - path: object - - id: project-service-accounts - title: Project service accounts - description: > - Manage service accounts within a project. A service account is a bot user that is not associated with - a user. - - If a user leaves an organization, their keys and membership in projects will no longer work. Service - accounts + - id: project-service-accounts + title: Project Service Accounts + description: | + Manage service accounts within a project. A service account is a bot user that is not associated with a user. + If a user leaves an organization, their keys and membership in projects will no longer work. Service accounts do not have this limitation. However, service accounts can also be deleted from a project. navigationGroup: administration sections: @@ -69190,13 +17020,12 @@ x-oaiMeta: - type: object key: ProjectServiceAccount path: object - - id: project-api-keys - title: Project API keys - description: > - Manage API keys for a given project. Supports listing and deleting keys for users. - This API does not allow issuing keys for users, as users need to authorize themselves to generate - keys. + - id: project-api-keys + title: Project API Keys + description: | + Manage API keys for a given project. Supports listing and deleting keys for users. + This API does not allow issuing keys for users, as users need to authorize themselves to generate keys. navigationGroup: administration sections: - type: endpoint @@ -69211,30 +17040,13 @@ x-oaiMeta: - type: object key: ProjectApiKey path: object - - id: project-rate-limits - title: Project rate limits - description: > - Manage rate limits per model for projects. Rate limits may be configured to be equal to or lower than - the organization's rate limits. - navigationGroup: administration - sections: - - type: endpoint - key: list-project-rate-limits - path: list - - type: endpoint - key: update-project-rate-limits - path: update - - type: object - key: ProjectRateLimit - path: object - - id: audit-logs - title: Audit logs - description: > - Logs of user actions and configuration changes within this organization. - To log events, an Organization Owner must activate logging in the [Data Controls - Settings](/settings/organization/data-controls/data-retention). + - id: audit-logs + title: Audit Logs + description: | + Logs of user actions and configuration changes within this organization. + To log events, you must activate logging in the [Organization Settings](/settings/organization/general). Once activated, for security reasons, logging cannot be deactivated. navigationGroup: administration sections: @@ -69244,332 +17056,17 @@ x-oaiMeta: - type: object key: AuditLog path: object - - id: usage - title: Usage - description: > - The **Usage API** provides detailed insights into your activity across the OpenAI API. It also - includes a separate [Costs endpoint](https://platform.openai.com/docs/api-reference/usage/costs), - which offers visibility into your spend, breaking down consumption by invoice line items and project - IDs. - - - While the Usage API delivers granular usage data, it may not always reconcile perfectly with the Costs - due to minor differences in how usage and spend are recorded. For financial purposes, we recommend - using the [Costs endpoint](https://platform.openai.com/docs/api-reference/usage/costs) or the [Costs - tab](/settings/organization/usage) in the Usage Dashboard, which will reconcile back to your billing - invoice. - navigationGroup: administration - sections: - - type: endpoint - key: usage-completions - path: completions - - type: object - key: UsageCompletionsResult - path: completions_object - - type: endpoint - key: usage-embeddings - path: embeddings - - type: object - key: UsageEmbeddingsResult - path: embeddings_object - - type: endpoint - key: usage-moderations - path: moderations - - type: object - key: UsageModerationsResult - path: moderations_object - - type: endpoint - key: usage-images - path: images - - type: object - key: UsageImagesResult - path: images_object - - type: endpoint - key: usage-audio-speeches - path: audio_speeches - - type: object - key: UsageAudioSpeechesResult - path: audio_speeches_object - - type: endpoint - key: usage-audio-transcriptions - path: audio_transcriptions - - type: object - key: UsageAudioTranscriptionsResult - path: audio_transcriptions_object - - type: endpoint - key: usage-vector-stores - path: vector_stores - - type: object - key: UsageVectorStoresResult - path: vector_stores_object - - type: endpoint - key: usage-code-interpreter-sessions - path: code_interpreter_sessions - - type: object - key: UsageCodeInterpreterSessionsResult - path: code_interpreter_sessions_object - - type: endpoint - key: usage-costs - path: costs - - type: object - key: CostsResult - path: costs_object - - id: certificates - beta: true - title: Certificates - description: > - Manage Mutual TLS certificates across your organization and projects. - - [Learn more about Mutual - TLS.](https://help.openai.com/en/articles/10876024-openai-mutual-tls-beta-program) - navigationGroup: administration - sections: - - type: endpoint - key: uploadCertificate - path: uploadCertificate - - type: endpoint - key: getCertificate - path: getCertificate - - type: endpoint - key: modifyCertificate - path: modifyCertificate - - type: endpoint - key: deleteCertificate - path: deleteCertificate - - type: endpoint - key: listOrganizationCertificates - path: listOrganizationCertificates - - type: endpoint - key: listProjectCertificates - path: listProjectCertificates - - type: endpoint - key: activateOrganizationCertificates - path: activateOrganizationCertificates - - type: endpoint - key: deactivateOrganizationCertificates - path: deactivateOrganizationCertificates - - type: endpoint - key: activateProjectCertificates - path: activateProjectCertificates - - type: endpoint - key: deactivateProjectCertificates - path: deactivateProjectCertificates - - type: object - key: Certificate - path: object - id: completions title: Completions legacy: true navigationGroup: legacy - description: > - Given a prompt, the model will return one or more predicted completions along with the probabilities - of alternative tokens at each position. Most developer should use our [Chat Completions - API](https://platform.openai.com/docs/guides/text-generation#text-generation-models) to leverage our - best and newest models. + description: | + Given a prompt, the model will return one or more predicted completions along with the probabilities of alternative tokens at each position. Most developer should use our [Chat Completions API](/docs/guides/text-generation/text-generation-models) to leverage our best and newest models. sections: - type: endpoint key: createCompletion path: create - type: object key: CreateCompletionResponse - path: object - - id: realtime_beta - title: Realtime Beta - legacy: true - navigationGroup: legacy - description: > - Communicate with a multimodal model in real time over low latency interfaces like WebRTC, WebSocket, - and SIP. Natively supports speech-to-speech as well as text, image, and audio inputs and outputs. - - [Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime). - - id: realtime-beta-sessions - title: Realtime Beta session tokens - description: | - REST API endpoint to generate ephemeral session tokens for use in client-side - applications. - navigationGroup: legacy - sections: - - type: endpoint - key: create-realtime-session - path: create - - type: endpoint - key: create-realtime-transcription-session - path: create-transcription - - type: object - key: RealtimeSessionCreateResponse - path: session_object - - type: object - key: RealtimeTranscriptionSessionCreateResponse - path: transcription_session_object - - id: realtime-beta-client-events - title: Realtime Beta client events - description: | - These are events that the OpenAI Realtime WebSocket server will accept from the client. - navigationGroup: legacy - sections: - - type: object - key: RealtimeBetaClientEventSessionUpdate - path: - - type: object - key: RealtimeBetaClientEventInputAudioBufferAppend - path: - - type: object - key: RealtimeBetaClientEventInputAudioBufferCommit - path: - - type: object - key: RealtimeBetaClientEventInputAudioBufferClear - path: - - type: object - key: RealtimeBetaClientEventConversationItemCreate - path: - - type: object - key: RealtimeBetaClientEventConversationItemRetrieve - path: - - type: object - key: RealtimeBetaClientEventConversationItemTruncate - path: - - type: object - key: RealtimeBetaClientEventConversationItemDelete - path: - - type: object - key: RealtimeBetaClientEventResponseCreate - path: - - type: object - key: RealtimeBetaClientEventResponseCancel - path: - - type: object - key: RealtimeBetaClientEventTranscriptionSessionUpdate - path: - - type: object - key: RealtimeBetaClientEventOutputAudioBufferClear - path: - - id: realtime-beta-server-events - title: Realtime Beta server events - description: | - These are events emitted from the OpenAI Realtime WebSocket server to the client. - navigationGroup: legacy - sections: - - type: object - key: RealtimeBetaServerEventError - path: - - type: object - key: RealtimeBetaServerEventSessionCreated - path: - - type: object - key: RealtimeBetaServerEventSessionUpdated - path: - - type: object - key: RealtimeBetaServerEventTranscriptionSessionCreated - path: - - type: object - key: RealtimeBetaServerEventTranscriptionSessionUpdated - path: - - type: object - key: RealtimeBetaServerEventConversationItemCreated - path: - - type: object - key: RealtimeBetaServerEventConversationItemRetrieved - path: - - type: object - key: RealtimeBetaServerEventConversationItemInputAudioTranscriptionCompleted - path: - - type: object - key: RealtimeBetaServerEventConversationItemInputAudioTranscriptionDelta - path: - - type: object - key: RealtimeBetaServerEventConversationItemInputAudioTranscriptionSegment - path: - - type: object - key: RealtimeBetaServerEventConversationItemInputAudioTranscriptionFailed - path: - - type: object - key: RealtimeBetaServerEventConversationItemTruncated - path: - - type: object - key: RealtimeBetaServerEventConversationItemDeleted - path: - - type: object - key: RealtimeBetaServerEventInputAudioBufferCommitted - path: - - type: object - key: RealtimeBetaServerEventInputAudioBufferCleared - path: - - type: object - key: RealtimeBetaServerEventInputAudioBufferSpeechStarted - path: - - type: object - key: RealtimeBetaServerEventInputAudioBufferSpeechStopped - path: - - type: object - key: RealtimeServerEventInputAudioBufferTimeoutTriggered - path: - - type: object - key: RealtimeBetaServerEventResponseCreated - path: - - type: object - key: RealtimeBetaServerEventResponseDone - path: - - type: object - key: RealtimeBetaServerEventResponseOutputItemAdded - path: - - type: object - key: RealtimeBetaServerEventResponseOutputItemDone - path: - - type: object - key: RealtimeBetaServerEventResponseContentPartAdded - path: - - type: object - key: RealtimeBetaServerEventResponseContentPartDone - path: - - type: object - key: RealtimeBetaServerEventResponseTextDelta - path: - - type: object - key: RealtimeBetaServerEventResponseTextDone - path: - - type: object - key: RealtimeBetaServerEventResponseAudioTranscriptDelta - path: - - type: object - key: RealtimeBetaServerEventResponseAudioTranscriptDone - path: - - type: object - key: RealtimeBetaServerEventResponseAudioDelta - path: - - type: object - key: RealtimeBetaServerEventResponseAudioDone - path: - - type: object - key: RealtimeBetaServerEventResponseFunctionCallArgumentsDelta - path: - - type: object - key: RealtimeBetaServerEventResponseFunctionCallArgumentsDone - path: - - type: object - key: RealtimeBetaServerEventResponseMCPCallArgumentsDelta - path: - - type: object - key: RealtimeBetaServerEventResponseMCPCallArgumentsDone - path: - - type: object - key: RealtimeBetaServerEventResponseMCPCallInProgress - path: - - type: object - key: RealtimeBetaServerEventResponseMCPCallCompleted - path: - - type: object - key: RealtimeBetaServerEventResponseMCPCallFailed - path: - - type: object - key: RealtimeBetaServerEventMCPListToolsInProgress - path: - - type: object - key: RealtimeBetaServerEventMCPListToolsCompleted - path: - - type: object - key: RealtimeBetaServerEventMCPListToolsFailed - path: - - type: object - key: RealtimeBetaServerEventRateLimitsUpdated - path: + path: object \ No newline at end of file