UNPKG

openai

Version:

The official TypeScript library for the OpenAI API

920 lines (815 loc) • 24.4 kB
// File generated from our OpenAPI spec by Castiron. See CONTRIBUTING.md for details. import { APIResource } from '../../core/resource'; import * as ConversationsAPI from './conversations'; import * as ResponsesAPI from '../responses/responses'; import { APIPromise } from '../../core/api-promise'; import { ConversationCursorPage, type ConversationCursorPageParams, PagePromise, } from '../../core/pagination'; import { RequestOptions } from '../../internal/request-options'; import { path } from '../../internal/utils/path'; function resolveResourceRequestOptions( options: RequestOptions | undefined, buildOptions: (options: RequestOptions | undefined) => RequestOptions | Promise<RequestOptions>, ): Promise<RequestOptions> { return Promise.resolve(options).then(buildOptions); } // Recognizable options across SDK runtime versions. Keep this independent of // private RequestOptions fields so older handwritten runtimes still compile. const normalizeRequestOptionsForQueryKeys = new Set([ 'method', 'path', 'query', 'body', 'headers', 'maxRetries', 'stream', 'timeout', 'httpAgent', 'fetchOptions', 'signal', 'idempotencyKey', 'defaultBaseURL', '__metadata', '__binaryRequest', '__binaryResponse', '__streamClass', '__streamMode', '__security', '__synthesizeEventData', ]); function normalizeRequestOptionsForQuery( value: unknown, queryKeys: ReadonlyArray<string>, options: RequestOptions | undefined, ): | ({ [K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query']?: RequestOptions[K]; } & { [ K in | 'method' | 'path' | 'body' | 'stream' | 'httpAgent' | 'fetchOptions' | 'defaultBaseURL' | '__metadata' | '__binaryRequest' | '__binaryResponse' | '__streamClass' | '__streamMode' | '__security' | '__synthesizeEventData' ]?: never; }) | undefined { if (typeof value !== 'object' || value === null) return undefined; // Optional never fields can still be explicitly undefined unless consumers // enable exactOptionalPropertyTypes. Snapshot data without invoking getters. const entries = Object.entries(Object.getOwnPropertyDescriptors(value)).filter( ([, descriptor]) => descriptor.enumerable && (!('value' in descriptor) || descriptor.value !== undefined), ); const keys = entries.map(([key]) => key); const requestOnly = keys.some( (key) => normalizeRequestOptionsForQueryKeys.has(key) && !queryKeys.includes(key), ); if (!requestOnly) return undefined; // Declared query fields, including stream, must use the query argument. // Mixing them with request-only options is ambiguous and could change the return type. if ( options !== undefined || keys.some((key) => !normalizeRequestOptionsForQueryKeys.has(key) || queryKeys.includes(key)) ) { throw new TypeError('Query parameters and request options must be passed as separate arguments.'); } // The query position must not gain authority to change the request destination // or transport. Those overrides require the explicit request options argument. if ( keys.some( (key) => !['headers', 'maxRetries', 'timeout', 'signal', 'idempotencyKey', 'query'].includes(key), ) ) { throw new TypeError('Pass transport overrides in the explicit request options argument.'); } // Copy only the validated fields. Spreading value would reintroduce undefined // transport overrides, and deleting them would mutate the caller's object. return Object.fromEntries( entries.map(([key, descriptor]) => { if ('value' in descriptor) return [key, descriptor.value]; return [key, descriptor.get ? Reflect.apply(descriptor.get, value, []) : undefined]; }), ) as { [K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query']?: RequestOptions[K]; } & { [ K in | 'method' | 'path' | 'body' | 'stream' | 'httpAgent' | 'fetchOptions' | 'defaultBaseURL' | '__metadata' | '__binaryRequest' | '__binaryResponse' | '__streamClass' | '__streamMode' | '__security' | '__synthesizeEventData' ]?: never; }; } /** * Manage conversations and conversation items. */ export class Items extends APIResource { /** * Create items in a conversation with the given ID. */ create( conversationID: string, params: ItemCreateParams, options?: RequestOptions, ): APIPromise<ConversationItemList> { const { include, ...body } = params; return this._client.post( path`/conversations/${conversationID}/items`, resolveResourceRequestOptions(options, (options) => ({ query: { include }, body, ...options, __security: { bearerAuth: true }, })), ); } /** * Get a single item from a conversation with the given IDs. */ retrieve( itemID: string, params: ItemRetrieveParams, options?: RequestOptions, ): APIPromise<ConversationItem> { const { conversation_id, ...query } = params; return this._client.get( path`/conversations/${conversation_id}/items/${itemID}`, resolveResourceRequestOptions(options, (options) => ({ query, ...options, __security: { bearerAuth: true }, })), ); } /** * List all items for a conversation with the given ID. */ list( conversationID: string, query?: | (ItemListParams & ( | { [ K in | 'method' | 'path' | 'query' | 'body' | 'headers' | 'maxRetries' | 'stream' | 'timeout' | 'httpAgent' | 'fetchOptions' | 'signal' | 'idempotencyKey' | 'defaultBaseURL' | '__metadata' | '__binaryRequest' | '__binaryResponse' | '__streamClass' | '__streamMode' | '__security' | '__synthesizeEventData' ]?: never; } | null | undefined )) | null | undefined, options?: RequestOptions, ): PagePromise<ConversationItemsPage, ConversationItem>; list( conversationID: string, options?: { [K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query']?: RequestOptions[K]; } & { [ K in | 'method' | 'path' | 'body' | 'stream' | 'httpAgent' | 'fetchOptions' | 'defaultBaseURL' | '__metadata' | '__binaryRequest' | '__binaryResponse' | '__streamClass' | '__streamMode' | '__security' | '__synthesizeEventData' ]?: never; }, ): PagePromise<ConversationItemsPage, ConversationItem>; list( conversationID: string, query: | ItemListParams | ({ [ K in 'headers' | 'maxRetries' | 'timeout' | 'signal' | 'idempotencyKey' | 'query' ]?: RequestOptions[K]; } & { [ K in | 'method' | 'path' | 'body' | 'stream' | 'httpAgent' | 'fetchOptions' | 'defaultBaseURL' | '__metadata' | '__binaryRequest' | '__binaryResponse' | '__streamClass' | '__streamMode' | '__security' | '__synthesizeEventData' ]?: never; }) | null | undefined = {}, options?: RequestOptions, ): PagePromise<ConversationItemsPage, ConversationItem> { const normalizeRequestOptionsForQueryOptions = normalizeRequestOptionsForQuery( query, ['after', 'include', 'limit', 'order'], options, ); if (normalizeRequestOptionsForQueryOptions !== undefined) { options = normalizeRequestOptionsForQueryOptions; query = {}; } query = query as ItemListParams | null | undefined; return this._client.getAPIList( path`/conversations/${conversationID}/items`, ConversationCursorPage<ConversationItem>, resolveResourceRequestOptions(options, (options) => ({ query, ...options, __security: { bearerAuth: true }, })), ); } /** * Delete an item from a conversation with the given IDs. */ delete( itemID: string, params: ItemDeleteParams, options?: RequestOptions, ): APIPromise<ConversationsAPI.Conversation> { const { conversation_id } = params; return this._client.delete( path`/conversations/${conversation_id}/items/${itemID}`, resolveResourceRequestOptions(options, (options) => ({ ...options, __security: { bearerAuth: true } })), ); } } export type ConversationItemsPage = ConversationCursorPage<ConversationItem>; /** * A single item within a conversation. The set of possible types are the same as * the `output` type of a * [Response object](https://developers.openai.com/api/reference/resources/responses#%28resource%29%20responses%20%3E%20%28model%29%20response%20%3E%20%28schema%29%20%3E%20%28property%29%20output). */ export type ConversationItem = | ConversationsAPI.Message | ResponsesAPI.ResponseFunctionToolCallItem | ResponsesAPI.ResponseFunctionToolCallOutputItem | ResponsesAPI.ResponseFileSearchToolCall | ResponsesAPI.ResponseFunctionWebSearch | ConversationItem.ImageGenerationCall | ResponsesAPI.ResponseComputerToolCall | ResponsesAPI.ResponseComputerToolCallOutputItem | ResponsesAPI.ResponseToolSearchCall | ResponsesAPI.ResponseToolSearchOutputItem | ConversationItem.AdditionalTools | ResponsesAPI.ResponseConfigurationUpdateItem | ResponsesAPI.ResponseReasoningItem | ConversationItem.Program | ConversationItem.ProgramOutput | ResponsesAPI.ResponseCompactionItem | ResponsesAPI.ResponseCodeInterpreterToolCall | ConversationItem.LocalShellCall | ConversationItem.LocalShellCallOutput | ResponsesAPI.ResponseFunctionShellToolCall | ResponsesAPI.ResponseFunctionShellToolCallOutput | ResponsesAPI.ResponseApplyPatchToolCall | ResponsesAPI.ResponseApplyPatchToolCallOutput | ConversationItem.McpListTools | ConversationItem.McpApprovalRequest | ConversationItem.McpApprovalResponse | ConversationItem.McpCall | ResponsesAPI.ResponseCustomToolCall | ResponsesAPI.ResponseCustomToolCallOutput; export namespace ConversationItem { /** * An image generation request made by the model. */ export interface ImageGenerationCall { /** * The unique ID of the image generation call. */ id: string; /** * The generated image encoded in base64. */ result: string | null; /** * The status of the image generation call. */ status: 'in_progress' | 'completed' | 'generating' | 'failed'; /** * The type of the image generation call. Always `image_generation_call`. */ type: 'image_generation_call'; /** * The action used for image generation. */ action?: 'generate' | 'edit' | 'auto' | null; /** * The background setting used for generation. */ background?: 'transparent' | 'opaque' | 'auto' | null; /** * Details of a moderation failure, when available. */ error?: ImageGenerationCall.Error; /** * The output format used for generation. */ output_format?: 'png' | 'webp' | 'jpeg' | 'gif' | 'svg' | null; /** * The quality of the image generated by the image generation tool call. One of * `low`, `medium`, `high`, `xhigh`, `max`, or `auto`. */ quality?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'auto' | null; /** * The prompt that was used after any model prompt rewriting. */ revised_prompt?: string | null; /** * The image dimensions as a `WIDTHxHEIGHT` string, for example `1536x864`. */ size?: (string & {}) | '1024x1024' | '1024x1536' | '1536x1024' | null; svg_usage?: ImageGenerationCall.SvgUsage; } export namespace ImageGenerationCall { /** * Details of a moderation failure, when available. */ export interface Error { /** * The error code. */ code: string | null; /** * A description of the error. */ message: string; /** * The related request parameter. */ param: string | null; /** * The error type. */ type: string; /** * Public details for a `moderation_blocked` error, when available. */ moderation_details?: Error.ModerationDetails; } export namespace Error { /** * Public details for a `moderation_blocked` error, when available. */ export interface ModerationDetails { /** * Public moderation categories. New category values may be added over time. */ categories: Array<string>; /** * The stage where moderation blocked the image generation call. */ moderation_stage: 'input' | 'output' | 'unknown'; } } export interface SvgUsage { input_tokens: number; model: string; output_tokens: number; reasoning_tokens: number; total_tokens: number; } } export interface AdditionalTools { /** * The unique ID of the additional tools item. */ id: string; /** * The role that provided the additional tools. */ role: 'unknown' | 'user' | 'assistant' | 'system' | 'critic' | 'discriminator' | 'developer' | 'tool'; /** * The additional tool definitions made available at this item. */ tools: Array<ResponsesAPI.Tool>; /** * The type of the item. Always `additional_tools`. */ type: 'additional_tools'; } export interface Program { /** * The unique ID of the program item. */ id: string; /** * The stable call ID of the program item. */ call_id: string; /** * The JavaScript source executed by programmatic tool calling. */ code: string; /** * Opaque program replay fingerprint that must be round-tripped. */ fingerprint: string; /** * The type of the item. Always `program`. */ type: 'program'; } export interface ProgramOutput { /** * The unique ID of the program output item. */ id: string; /** * The call ID of the program item. */ call_id: string; /** * The result produced by the program item. */ result: string; /** * The terminal status of the program output item. */ status: 'completed' | 'incomplete'; /** * The type of the item. Always `program_output`. */ type: 'program_output'; } /** * A tool call to run a command on the local shell. */ export interface LocalShellCall { /** * The unique ID of the local shell call. */ id: string; /** * Execute a shell command on the server. */ action: LocalShellCall.Action; /** * The unique ID of the local shell tool call generated by the model. */ call_id: string; /** * The status of the local shell call. */ status: 'in_progress' | 'completed' | 'incomplete'; /** * The type of the local shell call. Always `local_shell_call`. */ type: 'local_shell_call'; } export namespace LocalShellCall { /** * Execute a shell command on the server. */ export interface Action { /** * The command to run. */ command: Array<string>; /** * Environment variables to set for the command. */ env: { [key: string]: string }; /** * The type of the local shell action. Always `exec`. */ type: 'exec'; /** * Optional timeout in milliseconds for the command. */ timeout_ms?: number | null; /** * Optional user to run the command as. */ user?: string | null; /** * Optional working directory to run the command in. */ working_directory?: string | null; } } /** * The output of a local shell tool call. */ export interface LocalShellCallOutput { /** * The unique ID of the local shell tool call generated by the model. */ id: string; /** * A JSON string of the output of the local shell tool call. */ output: string; /** * The type of the local shell tool call output. Always `local_shell_call_output`. */ type: 'local_shell_call_output'; /** * The status of the item. One of `in_progress`, `completed`, or `incomplete`. */ status?: 'in_progress' | 'completed' | 'incomplete' | null; } /** * A list of tools available on an MCP server. */ export interface McpListTools { /** * The unique ID of the list. */ id: string; /** * The label of the MCP server. */ server_label: string; /** * The tools available on the server. */ tools: Array<McpListTools.Tool>; /** * The type of the item. Always `mcp_list_tools`. */ type: 'mcp_list_tools'; /** * Error message if the server could not list tools. */ error?: string | null; } export namespace McpListTools { /** * A tool available on an MCP server. */ export interface Tool { /** * The JSON schema describing the tool's input. */ input_schema: unknown; /** * The name of the tool. */ name: string; /** * Additional annotations about the tool. */ annotations?: unknown | null; /** * The description of the tool. */ description?: string | null; } } /** * A request for human approval of a tool invocation. */ export interface McpApprovalRequest { /** * The unique ID of the approval request. */ id: string; /** * A JSON string of arguments for the tool. */ arguments: string; /** * The name of the tool to run. */ name: string; /** * The label of the MCP server making the request. */ server_label: string; /** * The type of the item. Always `mcp_approval_request`. */ type: 'mcp_approval_request'; } /** * A response to an MCP approval request. */ export interface McpApprovalResponse { /** * The unique ID of the approval response */ id: string; /** * The ID of the approval request being answered. */ approval_request_id: string; /** * Whether the request was approved. */ approve: boolean; /** * The type of the item. Always `mcp_approval_response`. */ type: 'mcp_approval_response'; /** * Optional reason for the decision. */ reason?: string | null; } /** * An invocation of a tool on an MCP server. */ export interface McpCall { /** * The unique ID of the tool call. */ id: string; /** * A JSON string of the arguments passed to the tool. */ arguments: string; /** * The name of the tool that was run. */ name: string; /** * The label of the MCP server running the tool. */ server_label: string; /** * The type of the item. Always `mcp_call`. */ type: 'mcp_call'; /** * 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. */ approval_request_id?: string | null; /** * The error from the tool call, if any. */ error?: ResponsesAPI.McpToolCallError | null; /** * The output from the tool call. */ output?: string | null; /** * The status of the tool call. One of `in_progress`, `completed`, `incomplete`, * `calling`, or `failed`. */ status?: 'in_progress' | 'completed' | 'incomplete' | 'calling' | 'failed'; } } /** * A list of Conversation items. */ export interface ConversationItemList { /** * A list of conversation items. */ data: Array<ConversationItem>; /** * The ID of the first item in the list. */ first_id: string; /** * Whether there are more items available. */ has_more: boolean; /** * The ID of the last item in the list. */ last_id: string; /** * The type of object returned, must be `list`. */ object: 'list'; } export interface ItemCreateParams { /** * Body param: The items to add to the conversation. You may add up to 20 items at * a time. */ items: Array<ResponsesAPI.ResponseInputItem>; /** * Query param: Additional fields to include in the response. See the `include` * parameter for * [listing Conversation items above](https://developers.openai.com/api/reference/resources/conversations/subresources/items/methods/list#%28resource%29%20conversations.items%20%3E%20%28method%29%20list%20%3E%20%28params%29%20default%20%3E%20%28param%29%20include%20%3E%20%28schema%29) * for more information. */ include?: Array<ResponsesAPI.ResponseIncludable>; } export interface ItemRetrieveParams { /** * Path param: The ID of the conversation that contains the item. */ conversation_id: string; /** * Query param: Additional fields to include in the response. See the `include` * parameter for * [listing Conversation items above](https://developers.openai.com/api/reference/resources/conversations/subresources/items/methods/list#%28resource%29%20conversations.items%20%3E%20%28method%29%20list%20%3E%20%28params%29%20default%20%3E%20%28param%29%20include%20%3E%20%28schema%29) * for more information. */ include?: Array<ResponsesAPI.ResponseIncludable>; } export interface ItemListParams extends ConversationCursorPageParams { /** * 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). */ include?: Array<ResponsesAPI.ResponseIncludable>; /** * 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. */ order?: 'asc' | 'desc'; } export interface ItemDeleteParams { /** * The ID of the conversation that contains the item. */ conversation_id: string; } export declare namespace Items { export { type ConversationItem as ConversationItem, type ConversationItemList as ConversationItemList, type ConversationItemsPage as ConversationItemsPage, type ItemCreateParams as ItemCreateParams, type ItemRetrieveParams as ItemRetrieveParams, type ItemListParams as ItemListParams, type ItemDeleteParams as ItemDeleteParams, }; }