1/**
2 * The `OpenAiSchema` module defines the request, response, streaming, and
3 * embedding schemas used by the handwritten OpenAI client. These schemas are
4 * the transport boundary for JSON sent to and decoded from the Responses and
5 * embeddings endpoints.
6 *
7 * @stability unstable
8 * @since 4.0.0
9 */
10import * as Effect from "effect/Effect"
11import * as Predicate from "effect/Predicate"
12import * as Schema from "effect/Schema"
13import * as SchemaTransformation from "effect/SchemaTransformation"
14
15const UnknownRecord = Schema.Record(Schema.String, Schema.Unknown)
16
17const JsonObject = Schema.Record(Schema.String, Schema.Unknown)
18
19const MessageRole = Schema.Literals(["system", "developer", "user", "assistant"])
20
21const ImageDetail = Schema.Literals(["low", "high", "auto"])
22
23const PromptCacheBreakpoint = Schema.Struct({
24 mode: Schema.Literal("explicit")
25})
26
27/**
28 * Schema for optional `include` values supported by the local handwritten
29 * Responses client schema.
30 *
31 * **Details**
32 *
33 * These values request additional response fields such as image URLs, encrypted
34 * reasoning content, output logprobs, code interpreter outputs, or web search
35 * sources. This schema enumerates the include values supported by this client
36 * path.
37 *
38 * @stability unstable
39 * @category schemas
40 * @since 4.0.0
41 */
42export const IncludeEnum = Schema.Literals([
43 "message.input_image.image_url",
44 "reasoning.encrypted_content",
45 "message.output_text.logprobs",
46 "code_interpreter_call.outputs",
47 "web_search_call.action.sources"
48])
49
50/**
51 * Type of optional `include` values accepted by OpenAI Responses requests.
52 *
53 * @stability unstable
54 * @category models
55 * @since 4.0.0
56 */
57export type IncludeEnum = typeof IncludeEnum.Type
58
59/**
60 * Schema for lifecycle statuses shared by messages, reasoning items, and tool calls.
61 *
62 * **Details**
63 *
64 * Accepted values are `"in_progress"`, `"completed"`, and `"incomplete"`.
65 * This item-level status is used by message, reasoning, and tool-call shapes.
66 *
67 * @stability unstable
68 * @category schemas
69 * @since 4.0.0
70 */
71export const MessageStatus = Schema.Literals(["in_progress", "completed", "incomplete"])
72
73/**
74 * Lifecycle status shared by messages, reasoning items, and tool calls.
75 *
76 * **Details**
77 *
78 * Accepted values are `"in_progress"`, `"completed"`, and `"incomplete"`.
79 *
80 * @stability unstable
81 * @category models
82 * @since 4.0.0
83 */
84export type MessageStatus = typeof MessageStatus.Type
85
86const InputTextContent = Schema.Struct({
87 type: Schema.Literal("input_text"),
88 text: Schema.String,
89 prompt_cache_breakpoint: Schema.optional(PromptCacheBreakpoint)
90})
91
92const InputImageContent = Schema.Struct({
93 type: Schema.Literal("input_image"),
94 image_url: Schema.optionalKey(Schema.NullOr(Schema.String)),
95 file_id: Schema.optionalKey(Schema.NullOr(Schema.String)),
96 detail: Schema.optionalKey(Schema.NullOr(ImageDetail))
97})
98
99const InputFileContent = Schema.Struct({
100 type: Schema.Literal("input_file"),
101 file_id: Schema.optionalKey(Schema.NullOr(Schema.String)),
102 filename: Schema.optionalKey(Schema.String),
103 file_url: Schema.optionalKey(Schema.String),
104 file_data: Schema.optionalKey(Schema.String)
105})
106
107/**
108 * Schema for content blocks accepted in OpenAI Responses input messages.
109 *
110 * **Details**
111 *
112 * Accepted block variants are `input_text`, `input_image`, and `input_file`.
113 *
114 * @see {@link InputItem} for request input item shapes that can contain these content blocks
115 *
116 * @stability unstable
117 * @category schemas
118 * @since 4.0.0
119 */
120export const InputContent = Schema.Union([
121 InputTextContent,
122 InputImageContent,
123 InputFileContent
124])
125
126/**
127 * Content block accepted in OpenAI Responses input messages.
128 *
129 * **Details**
130 *
131 * Accepted block variants are `input_text`, `input_image`, and `input_file`.
132 *
133 * @stability unstable
134 * @category models
135 * @since 4.0.0
136 */
137export type InputContent = typeof InputContent.Type
138
139/**
140 * Schema for a text block containing a model-provided reasoning summary.
141 *
142 * **Details**
143 *
144 * The decoded shape is `type: "summary_text"` plus `text` containing the
145 * reasoning summary text.
146 *
147 * @see {@link ReasoningItem} for reasoning output items that contain summary text blocks
148 *
149 * @stability unstable
150 * @category schemas
151 * @since 4.0.0
152 */
153export const SummaryTextContent = Schema.Struct({
154 type: Schema.Literal("summary_text"),
155 text: Schema.String
156})
157
158/**
159 * Text content block used for model-provided reasoning summaries.
160 *
161 * @stability unstable
162 * @category models
163 * @since 4.0.0
164 */
165export type SummaryTextContent = typeof SummaryTextContent.Type
166
167const ReasoningTextContent = Schema.Struct({
168 type: Schema.Literal("reasoning_text"),
169 text: Schema.String
170})
171
172const RefusalContent = Schema.Struct({
173 type: Schema.Literal("refusal"),
174 refusal: Schema.String
175})
176
177const TextContent = Schema.Struct({
178 type: Schema.Literal("text"),
179 text: Schema.String
180})
181
182const ComputerScreenshotContent = Schema.Struct({
183 type: Schema.Literal("computer_screenshot"),
184 image_url: Schema.NullOr(Schema.String),
185 file_id: Schema.NullOr(Schema.String)
186})
187
188const FileCitationAnnotation = Schema.Struct({
189 type: Schema.Literal("file_citation"),
190 file_id: Schema.String,
191 index: Schema.Int,
192 filename: Schema.String
193})
194
195const UrlCitationAnnotation = Schema.Struct({
196 type: Schema.Literal("url_citation"),
197 url: Schema.String,
198 start_index: Schema.Int,
199 end_index: Schema.Int,
200 title: Schema.String
201})
202
203const ContainerFileCitationAnnotation = Schema.Struct({
204 type: Schema.Literal("container_file_citation"),
205 container_id: Schema.String,
206 file_id: Schema.String,
207 start_index: Schema.Int,
208 end_index: Schema.Int,
209 filename: Schema.String
210})
211
212const FilePathAnnotation = Schema.Struct({
213 type: Schema.Literal("file_path"),
214 file_id: Schema.String,
215 index: Schema.Int
216})
217
218/**
219 * Schema for citation and file-path annotations attached to output text content.
220 *
221 * **Details**
222 *
223 * Accepts annotation objects discriminated by `type`: `file_citation`,
224 * `url_citation`, `container_file_citation`, or `file_path`.
225 *
226 * @stability unstable
227 * @category schemas
228 * @since 4.0.0
229 */
230export const Annotation = Schema.Union([
231 FileCitationAnnotation,
232 UrlCitationAnnotation,
233 ContainerFileCitationAnnotation,
234 FilePathAnnotation
235])
236
237/**
238 * Citation or file-path annotation attached to output text content.
239 *
240 * **Details**
241 *
242 * Accepted annotation variants are `file_citation`, `url_citation`,
243 * `container_file_citation`, and `file_path`.
244 *
245 * @stability unstable
246 * @category models
247 * @since 4.0.0
248 */
249export type Annotation = typeof Annotation.Type
250
251const OutputTextContent = Schema.Struct({
252 type: Schema.Literal("output_text"),
253 text: Schema.String,
254 annotations: Schema.Array(Annotation),
255 logprobs: Schema.optionalKey(Schema.Array(Schema.Unknown))
256})
257
258const OutputMessageContent = Schema.Union([
259 InputTextContent,
260 OutputTextContent,
261 TextContent,
262 SummaryTextContent,
263 ReasoningTextContent,
264 RefusalContent,
265 InputImageContent,
266 ComputerScreenshotContent,
267 InputFileContent
268])
269
270const OutputMessage = Schema.Struct({
271 id: Schema.String,
272 type: Schema.Literal("message"),
273 role: Schema.Literal("assistant"),
274 content: Schema.Array(OutputMessageContent),
275 status: MessageStatus
276})
277
278/**
279 * Schema for a reasoning output item containing encrypted content, summaries, and optional reasoning text.
280 *
281 * **When to use**
282 *
283 * Use when decoding or encoding OpenAI Responses reasoning items that may be
284 * carried into later request input.
285 *
286 * **Details**
287 *
288 * Reasoning items represent model reasoning content. `summary` is required,
289 * while `content` and `status` are optional.
290 *
291 * **Gotchas**
292 *
293 * `encrypted_content` is populated only when `reasoning.encrypted_content` is
294 * requested through `include`.
295 *
296 * @see {@link InputItem} for request input items that can carry reasoning items
297 * @see {@link IncludeEnum} for requesting encrypted reasoning content
298 *
299 * @stability unstable
300 * @category schemas
301 * @since 4.0.0
302 */
303export const ReasoningItem = Schema.Struct({
304 type: Schema.Literal("reasoning"),
305 id: Schema.String,
306 encrypted_content: Schema.optionalKey(Schema.NullOr(Schema.String)),
307 summary: Schema.Array(SummaryTextContent),
308 content: Schema.optionalKey(Schema.Array(ReasoningTextContent)),
309 status: Schema.optionalKey(MessageStatus)
310})
311
312/**
313 * Reasoning output item containing encrypted content, summaries, and optional reasoning text.
314 *
315 * **When to use**
316 *
317 * Use when typing OpenAI Responses reasoning items that may be carried into
318 * later request input.
319 *
320 * **Details**
321 *
322 * Reasoning items represent model reasoning content. `summary` is required,
323 * while `content` and `status` are optional.
324 *
325 * **Gotchas**
326 *
327 * `encrypted_content` is populated only when `reasoning.encrypted_content` is
328 * requested through `include`.
329 *
330 * @stability unstable
331 * @category models
332 * @since 4.0.0
333 */
334export type ReasoningItem = typeof ReasoningItem.Type
335
336const FunctionCall = Schema.Struct({
337 id: Schema.optionalKey(Schema.String),
338 type: Schema.Literal("function_call"),
339 call_id: Schema.String,
340 name: Schema.String,
341 arguments: Schema.String,
342 status: Schema.optionalKey(MessageStatus)
343})
344
345const FunctionCallOutput = Schema.Struct({
346 id: Schema.optionalKey(Schema.NullOr(Schema.String)),
347 type: Schema.Literal("function_call_output"),
348 call_id: Schema.String,
349 output: Schema.Union([
350 Schema.String,
351 Schema.Array(InputContent)
352 ]),
353 status: Schema.optionalKey(Schema.NullOr(MessageStatus))
354})
355
356const ItemReference = Schema.Struct({
357 type: Schema.Literal("item_reference"),
358 id: Schema.String
359})
360
361const LocalShellCall = Schema.Struct({
362 id: Schema.optionalKey(Schema.String),
363 type: Schema.Literal("local_shell_call"),
364 call_id: Schema.String,
365 action: Schema.Unknown,
366 status: Schema.optionalKey(MessageStatus)
367})
368
369const LocalShellCallOutput = Schema.Struct({
370 id: Schema.optionalKey(Schema.String),
371 type: Schema.Literal("local_shell_call_output"),
372 call_id: Schema.String,
373 output: Schema.Unknown,
374 status: Schema.optionalKey(MessageStatus)
375})
376
377const ShellCall = Schema.Struct({
378 id: Schema.optionalKey(Schema.String),
379 type: Schema.Literal("shell_call"),
380 call_id: Schema.String,
381 action: Schema.Unknown,
382 status: Schema.optionalKey(MessageStatus)
383})
384
385const ShellCallOutput = Schema.Struct({
386 id: Schema.optionalKey(Schema.String),
387 type: Schema.Literal("shell_call_output"),
388 call_id: Schema.String,
389 output: Schema.Unknown,
390 status: Schema.optionalKey(MessageStatus)
391})
392
393const ApplyPatchCallOutput = Schema.Struct({
394 id: Schema.optionalKey(Schema.String),
395 type: Schema.Literal("apply_patch_call_output"),
396 call_id: Schema.String,
397 status: Schema.optionalKey(MessageStatus),
398 output: Schema.optionalKey(Schema.Unknown)
399})
400
401const McpApprovalResponse = Schema.Struct({
402 type: Schema.Literal("mcp_approval_response"),
403 approval_request_id: Schema.String,
404 approve: Schema.Boolean
405})
406
407const RequestMessageItem = Schema.Struct({
408 type: Schema.optionalKey(Schema.Literal("message")),
409 role: MessageRole,
410 status: Schema.optionalKey(MessageStatus),
411 content: Schema.Union([
412 Schema.String,
413 Schema.Array(InputContent)
414 ])
415})
416
417const InputCodeInterpreterCall = Schema.Struct({
418 id: Schema.String,
419 type: Schema.Literal("code_interpreter_call"),
420 code: Schema.optionalKey(Schema.NullOr(Schema.String)),
421 container_id: Schema.String,
422 outputs: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.Unknown))),
423 status: Schema.optionalKey(
424 Schema.Literals(["in_progress", "completed", "incomplete", "interpreting", "failed"])
425 )
426})
427
428const InputFileSearchCall = Schema.Struct({
429 id: Schema.String,
430 type: Schema.Literal("file_search_call"),
431 status: Schema.optionalKey(Schema.String),
432 queries: Schema.optionalKey(Schema.Array(Schema.String)),
433 results: Schema.optionalKey(Schema.NullOr(Schema.Unknown))
434})
435
436const InputImageGenerationCall = Schema.Struct({
437 id: Schema.String,
438 type: Schema.Literal("image_generation_call"),
439 result: Schema.optionalKey(Schema.NullOr(Schema.String)),
440 status: Schema.optionalKey(Schema.Literals(["in_progress", "completed", "generating", "failed"]))
441})
442
443const InputWebSearchCall = Schema.Struct({
444 id: Schema.String,
445 type: Schema.Literal("web_search_call"),
446 action: Schema.optionalKey(Schema.Unknown),
447 status: Schema.optionalKey(Schema.String)
448})
449
450/**
451 * Schema for item shapes accepted by an OpenAI Responses request `input` field.
452 *
453 * **When to use**
454 *
455 * Use when validating structured `CreateResponse.input` array items.
456 *
457 * **Details**
458 *
459 * Accepted item families include request/output messages, function call and
460 * function call output, reasoning items, item references, shell and local shell
461 * calls and outputs, apply-patch output, and MCP approval responses.
462 *
463 * @see {@link CreateResponse} for the request schema that consumes input items
464 * @see {@link InputContent} for content blocks inside message items
465 *
466 * @stability unstable
467 * @category schemas
468 * @since 4.0.0
469 */
470export const InputItem = Schema.Union([
471 RequestMessageItem,
472 OutputMessage,
473 FunctionCall,
474 FunctionCallOutput,
475 ReasoningItem,
476 ItemReference,
477 LocalShellCall,
478 LocalShellCallOutput,
479 ShellCall,
480 ShellCallOutput,
481 ApplyPatchCallOutput,
482 McpApprovalResponse,
483 InputCodeInterpreterCall,
484 InputFileSearchCall,
485 InputImageGenerationCall,
486 InputWebSearchCall
487])
488
489/**
490 * Item shape accepted by an OpenAI Responses request `input` field.
491 *
492 * **When to use**
493 *
494 * Use when typing structured `CreateResponse.input` array items.
495 *
496 * **Details**
497 *
498 * Accepted item families include request/output messages, function call and
499 * function call output, reasoning items, item references, shell and local shell
500 * calls and outputs, apply-patch output, and MCP approval responses.
501 *
502 * @stability unstable
503 * @category models
504 * @since 4.0.0
505 */
506export type InputItem = typeof InputItem.Type
507
508const FunctionTool = Schema.Struct({
509 type: Schema.Literal("function"),
510 name: Schema.String,
511 description: Schema.optionalKey(Schema.NullOr(Schema.String)),
512 parameters: Schema.optionalKey(Schema.NullOr(JsonObject)),
513 strict: Schema.optionalKey(Schema.NullOr(Schema.Boolean))
514})
515
516const CustomTool = Schema.Struct({
517 type: Schema.Literal("custom"),
518 name: Schema.String,
519 description: Schema.optionalKey(Schema.String),
520 format: Schema.optionalKey(Schema.Unknown)
521})
522
523const ProviderDefinedTool = Schema.StructWithRest(
524 Schema.Struct({
525 type: Schema.Literals([
526 "apply_patch",
527 "code_interpreter",
528 "file_search",
529 "image_generation",
530 "local_shell",
531 "mcp",
532 "shell",
533 "web_search",
534 "web_search_preview"
535 ])
536 }),
537 [UnknownRecord]
538)
539
540/**
541 * Schema for tool definitions that can be supplied to an OpenAI Responses request.
542 *
543 * **When to use**
544 *
545 * Use when validating or encoding the `tools` array for a Responses request,
546 * including provider-defined tool records with provider-specific fields.
547 *
548 * **Details**
549 *
550 * Accepted variants are function tools, custom tools, and provider-defined
551 * OpenAI tools. Provider-defined `type` literals include `apply_patch`,
552 * `code_interpreter`, `file_search`, `image_generation`, `local_shell`, `mcp`,
553 * `shell`, `web_search`, and `web_search_preview`.
554 *
555 * **Gotchas**
556 *
557 * Provider-defined tools use `Schema.StructWithRest`, so this schema checks the
558 * provider tool `type` and permits additional provider fields rather than fully
559 * validating every provider-specific tool payload.
560 *
561 * @see {@link ToolChoice} for selecting whether and which tools the model may call
562 * @see {@link CreateResponse} for the request schema that consumes tools
563 *
564 * @stability unstable
565 * @category schemas
566 * @since 4.0.0
567 */
568export const Tool = Schema.Union([
569 FunctionTool,
570 CustomTool,
571 ProviderDefinedTool
572])
573
574/**
575 * Tool definition that can be supplied to an OpenAI Responses request.
576 *
577 * @stability unstable
578 * @category models
579 * @since 4.0.0
580 */
581export type Tool = typeof Tool.Type
582
583/**
584 * Schema for selecting whether and which tools the model may call in a Responses request.
585 *
586 * **When to use**
587 *
588 * Use when validating or encoding the `tool_choice` field that constrains model
589 * tool use separately from the tool definitions themselves.
590 *
591 * **Details**
592 *
593 * Accepted forms are `"none"`, `"auto"`, `"required"`, an allowed-tools set,
594 * a named function or custom tool, or a provider-defined tool choice.
595 *
596 * @see {@link Tool} for tool definitions referenced by tool choices
597 * @see {@link CreateResponse} for the request schema that consumes `tool_choice`
598 *
599 * @stability unstable
600 * @category schemas
601 * @since 4.0.0
602 */
603export const ToolChoice = Schema.Union([
604 Schema.Literals(["none", "auto", "required"]),
605 Schema.Struct({
606 type: Schema.Literal("allowed_tools"),
607 mode: Schema.Literals(["auto", "required"]),
608 tools: Schema.Array(JsonObject)
609 }),
610 Schema.Struct({
611 type: Schema.Literal("function"),
612 name: Schema.String
613 }),
614 Schema.Struct({
615 type: Schema.Literal("custom"),
616 name: Schema.String
617 }),
618 Schema.StructWithRest(
619 Schema.Struct({
620 type: Schema.Literals([
621 "apply_patch",
622 "code_interpreter",
623 "file_search",
624 "image_generation",
625 "local_shell",
626 "mcp",
627 "shell",
628 "web_search",
629 "web_search_preview"
630 ])
631 }),
632 [UnknownRecord]
633 )
634])
635
636/**
637 * Tool selection mode or named tool choice for a Responses request.
638 *
639 * **Details**
640 *
641 * Accepted forms are `"none"`, `"auto"`, `"required"`, an allowed-tools set,
642 * a named function or custom tool, or a provider-defined tool choice.
643 *
644 * @stability unstable
645 * @category models
646 * @since 4.0.0
647 */
648export type ToolChoice = typeof ToolChoice.Type
649
650/**
651 * Schema for text output format configuration, including plain text, JSON object, and JSON Schema responses.
652 *
653 * **When to use**
654 *
655 * Use when validating or encoding the `text.format` setting for a Responses
656 * request, especially when choosing structured JSON Schema output.
657 *
658 * **Details**
659 *
660 * Accepted variants are `text`, `json_schema`, and `json_object`.
661 *
662 * **Gotchas**
663 *
664 * `json_object` is the older JSON mode. Prefer `json_schema` for models that
665 * support it.
666 *
667 * @see {@link CreateResponse} for the request schema that consumes text format configuration
668 *
669 * @stability unstable
670 * @category schemas
671 * @since 4.0.0
672 */
673export const TextResponseFormatConfiguration = Schema.Union([
674 Schema.Struct({ type: Schema.Literal("text") }),
675 Schema.Struct({
676 type: Schema.Literal("json_schema"),
677 description: Schema.optionalKey(Schema.String),
678 name: Schema.String,
679 schema: JsonObject,
680 strict: Schema.optionalKey(Schema.NullOr(Schema.Boolean))
681 }),
682 Schema.Struct({ type: Schema.Literal("json_object") })
683])
684
685/**
686 * Text output format configuration for plain text, JSON object, or JSON Schema responses.
687 *
688 * @stability unstable
689 * @category models
690 * @since 4.0.0
691 */
692export type TextResponseFormatConfiguration = typeof TextResponseFormatConfiguration.Type
693
694/**
695 * Schema for request options used to create an OpenAI Responses API response.
696 *
697 * **When to use**
698 *
699 * Use to validate or encode payloads sent to the OpenAI Responses API.
700 *
701 * **Details**
702 *
703 * Validates the Responses API request payload, including input content, model
704 * selection, instructions, reasoning options, text output format, tools,
705 * `tool_choice`, streaming, storage, response continuation, sampling options,
706 * prompt caching, and optional response fields requested through `include`.
707 *
708 * **Gotchas**
709 *
710 * When `stream` is `true`, the API returns stream events instead of a single
711 * response object.
712 *
713 * @see {@link Response} for decoded non-streaming response objects
714 * @see {@link ResponseStreamEvent} for decoded streaming event objects
715 *
716 * @stability unstable
717 * @category schemas
718 * @since 4.0.0
719 */
720export const CreateResponse = Schema.Struct({
721 metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
722 top_logprobs: Schema.optional(Schema.Int),
723 temperature: Schema.optional(Schema.Finite),
724 top_p: Schema.optional(Schema.Finite),
725 user: Schema.optional(Schema.String),
726 prompt_cache_key: Schema.optional(Schema.String),
727 prompt_cache_options: Schema.optional(Schema.Struct({
728 mode: Schema.optional(Schema.Literals(["implicit", "explicit"])),
729 ttl: Schema.optional(Schema.Literal("30m")),
730 comparison_response_id: Schema.optional(Schema.NullOr(Schema.String))
731 })),
732 service_tier: Schema.optional(Schema.String),
733 previous_response_id: Schema.optional(Schema.String),
734 model: Schema.optional(Schema.String),
735 reasoning: Schema.optional(Schema.Struct({
736 effort: Schema.optional(Schema.Literals(["none", "minimal", "low", "medium", "high", "xhigh", "max"])),
737
738 summary: Schema.optional(Schema.Literals(["auto", "concise", "detailed"])),
739 generate_summary: Schema.optional(Schema.Literals(["auto", "concise", "detailed"]))
740 })),
741 background: Schema.optional(Schema.Boolean),
742 max_output_tokens: Schema.optional(Schema.Int),
743 max_tool_calls: Schema.optional(Schema.Int),
744 text: Schema.optional(
745 Schema.Struct({
746 format: Schema.optional(TextResponseFormatConfiguration),
747 verbosity: Schema.optional(Schema.Literals(["low", "medium", "high"]))
748 })
749 ),
750 tools: Schema.optional(Schema.Array(Tool)),
751 tool_choice: Schema.optional(ToolChoice),
752 truncation: Schema.optional(Schema.Literals(["auto", "disabled"])),
753 input: Schema.optional(
754 Schema.Union([
755 Schema.String,
756 Schema.Array(InputItem)
757 ])
758 ),
759 include: Schema.optional(Schema.Array(IncludeEnum)),
760 store: Schema.optional(Schema.Boolean),
761 instructions: Schema.optional(Schema.String),
762 stream: Schema.optional(Schema.Boolean),
763 conversation: Schema.optional(Schema.String),
764 modalities: Schema.optional(Schema.Array(Schema.Literals(["text", "audio"]))),
765 seed: Schema.optional(Schema.Int)
766})
767
768/**
769 * Request options used to create an OpenAI Responses API response.
770 *
771 * @stability unstable
772 * @category options
773 * @since 4.0.0
774 */
775export type CreateResponse = typeof CreateResponse.Type
776
777/**
778 * Schema for token accounting reported on OpenAI Responses API response objects.
779 *
780 * **Details**
781 *
782 * The required counters are `input_tokens`, `output_tokens`, and
783 * `total_tokens`. Provider-specific token detail objects are preserved through
784 * `input_tokens_details`, `output_tokens_details`, and additional fields.
785 *
786 * @stability unstable
787 * @category schemas
788 * @since 4.0.0
789 */
790export const ResponseUsage = Schema.StructWithRest(
791 Schema.Struct({
792 input_tokens: Schema.Int,
793 output_tokens: Schema.Int,
794 total_tokens: Schema.Int,
795 input_tokens_details: Schema.optionalKey(Schema.Unknown),
796 output_tokens_details: Schema.optionalKey(Schema.Unknown)
797 }),
798 [UnknownRecord]
799)
800
801/**
802 * Token accounting reported on OpenAI Responses API response objects.
803 *
804 * **Details**
805 *
806 * Includes total input, output, and combined token counts, with provider-specific
807 * token detail fields preserved when present.
808 *
809 * @stability unstable
810 * @category models
811 * @since 4.0.0
812 */
813export type ResponseUsage = typeof ResponseUsage.Type
814
815const ApplyPatchOperation = Schema.Struct({
816 type: Schema.String,
817 path: Schema.String,
818 diff: Schema.optionalKey(Schema.String)
819})
820
821const ApplyPatchCall = Schema.Struct({
822 id: Schema.String,
823 type: Schema.Literal("apply_patch_call"),
824 call_id: Schema.String,
825 operation: ApplyPatchOperation,
826 status: Schema.optionalKey(MessageStatus)
827})
828
829const CodeInterpreterCall = Schema.Struct({
830 id: Schema.String,
831 type: Schema.Literal("code_interpreter_call"),
832 code: Schema.optionalKey(Schema.NullOr(Schema.String)),
833 container_id: Schema.String,
834 outputs: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.Unknown))),
835 status: Schema.optionalKey(
836 Schema.Literals(["in_progress", "completed", "incomplete", "interpreting", "failed"])
837 )
838})
839
840const ComputerCall = Schema.Struct({
841 id: Schema.String,
842 type: Schema.Literal("computer_call"),
843 status: Schema.optionalKey(MessageStatus)
844})
845
846const FileSearchCall = Schema.Struct({
847 id: Schema.String,
848 type: Schema.Literal("file_search_call"),
849 status: Schema.optionalKey(Schema.String),
850 queries: Schema.optionalKey(Schema.Array(Schema.String)),
851 results: Schema.optionalKey(Schema.NullOr(Schema.Unknown))
852})
853
854const ImageGenerationCall = Schema.Struct({
855 id: Schema.String,
856 type: Schema.Literal("image_generation_call"),
857 result: Schema.optionalKey(Schema.NullOr(Schema.String)),
858 status: Schema.optionalKey(Schema.Literals(["in_progress", "completed", "generating", "failed"]))
859})
860
861const McpCall = Schema.Struct({
862 id: Schema.String,
863 type: Schema.Literal("mcp_call"),
864 approval_request_id: Schema.optionalKey(Schema.NullOr(Schema.String)),
865 name: Schema.String,
866 arguments: Schema.Unknown,
867 output: Schema.optionalKey(Schema.Unknown),
868 error: Schema.optionalKey(Schema.Unknown),
869 server_label: Schema.optionalKey(Schema.NullOr(Schema.String))
870})
871
872const McpListTools = Schema.Struct({
873 id: Schema.String,
874 type: Schema.Literal("mcp_list_tools")
875})
876
877const McpApprovalRequest = Schema.Struct({
878 id: Schema.String,
879 type: Schema.Literal("mcp_approval_request"),
880 approval_request_id: Schema.optionalKey(Schema.String),
881 name: Schema.String,
882 arguments: Schema.Unknown
883})
884
885const WebSearchCall = Schema.Struct({
886 id: Schema.String,
887 type: Schema.Literal("web_search_call"),
888 action: Schema.optionalKey(Schema.Unknown),
889 status: Schema.optionalKey(Schema.String)
890})
891
892const OutputItem = Schema.Union([
893 ApplyPatchCall,
894 CodeInterpreterCall,
895 ComputerCall,
896 FileSearchCall,
897 FunctionCall,
898 ImageGenerationCall,
899 LocalShellCall,
900 McpCall,
901 McpListTools,
902 McpApprovalRequest,
903 OutputMessage,
904 ReasoningItem,
905 ShellCall,
906 WebSearchCall
907])
908
909const ResponseError = Schema.Struct({
910 code: Schema.String,
911 message: Schema.String
912})
913
914/**
915 * Schema for prompt cache diagnostics comparing two responses.
916 *
917 * **Details**
918 *
919 * Cache misses report a reason and token estimates, separate from response usage.
920 *
921 * @category schemas
922 * @since 4.0.0
923 */
924export const PromptCacheDiagnostics = Schema.Union([
925 Schema.Struct({
926 type: Schema.Literal("cache_miss"),
927 reason: Schema.Literals([
928 "model_changed",
929 "prompt_cache_key_changed",
930 "tools_changed",
931 "text_format_changed",
932 "reasoning_effort_changed",
933 "verbosity_changed",
934 "context_compacted",
935 "input_changed",
936 "service_tier_changed"
937 ]),
938 cache_missed_tokens: Schema.Int,
939 comparison_reusable_tokens: Schema.optionalKey(Schema.Int)
940 }),
941 Schema.Struct({ type: Schema.Literal("cache_hit") }),
942 Schema.Struct({ type: Schema.Literal("comparison_response_not_found") }),
943 Schema.Struct({ type: Schema.Literal("unavailable") })
944])
945
946/**
947 * Prompt cache comparison result reported by the OpenAI Responses API.
948 *
949 * @category models
950 * @since 4.0.0
951 */
952export type PromptCacheDiagnostics = typeof PromptCacheDiagnostics.Type
953
954/**
955 * Schema for an OpenAI Responses API response object.
956 *
957 * **When to use**
958 *
959 * Use to decode non-streaming OpenAI Responses API responses.
960 *
961 * **Details**
962 *
963 * Response objects include the response id, model, creation time, output items,
964 * optional token usage, optional incomplete details, optional service tier, and
965 * optional prompt cache diagnostics.
966 *
967 * @see {@link CreateResponse} for the request schema that creates responses
968 * @see {@link ResponseUsage} for token accounting on responses
969 * @see {@link ResponseStreamEvent} for streaming response events
970 *
971 * @stability unstable
972 * @category schemas
973 * @since 4.0.0
974 */
975export const Response = Schema.Struct({
976 id: Schema.String,
977 object: Schema.optionalKey(Schema.Literal("response")),
978 model: Schema.String,
979 created_at: Schema.Int,
980 output: Schema.Array(OutputItem).pipe(
981 Schema.withDecodingDefault(Effect.succeed([]))
982 ),
983 usage: Schema.optionalKey(Schema.NullOr(ResponseUsage)),
984 error: Schema.optionalKey(Schema.NullOr(ResponseError)),
985 incomplete_details: Schema.optionalKey(
986 Schema.NullOr(
987 Schema.Struct({
988 reason: Schema.optionalKey(Schema.Literals(["max_output_tokens", "content_filter"]))
989 })
990 )
991 ),
992 service_tier: Schema.optionalKey(Schema.String),
993 prompt_cache_diagnostics: Schema.optionalKey(PromptCacheDiagnostics)
994})
995
996/**
997 * OpenAI Responses API response object.
998 *
999 * **When to use**
1000 *
1001 * Use when typing non-streaming OpenAI Responses API responses.
1002 *
1003 * **Details**
1004 *
1005 * Response objects include metadata, output items, optional token usage, and
1006 * optional incomplete details.
1007 *
1008 * @stability unstable
1009 * @category models
1010 * @since 4.0.0
1011 */
1012export type Response = typeof Response.Type
1013
1014const ResponseCreatedEvent = Schema.Struct({
1015 type: Schema.Literal("response.created"),
1016 response: Response,
1017 sequence_number: Schema.optionalKey(Schema.Int)
1018})
1019
1020const ResponseCompletedEvent = Schema.Struct({
1021 type: Schema.Literal("response.completed"),
1022 response: Response,
1023 sequence_number: Schema.optionalKey(Schema.Int)
1024})
1025
1026const ResponseIncompleteEvent = Schema.Struct({
1027 type: Schema.Literal("response.incomplete"),
1028 response: Response,
1029 sequence_number: Schema.optionalKey(Schema.Int)
1030})
1031
1032const ResponseFailedEvent = Schema.Struct({
1033 type: Schema.Literal("response.failed"),
1034 response: Response,
1035 sequence_number: Schema.optionalKey(Schema.Int)
1036})
1037
1038const ResponseOutputItemAddedEvent = Schema.Struct({
1039 type: Schema.Literal("response.output_item.added"),
1040 output_index: Schema.Int,
1041 sequence_number: Schema.optionalKey(Schema.Int),
1042 item: OutputItem
1043})
1044
1045const ResponseOutputItemDoneEvent = Schema.Struct({
1046 type: Schema.Literal("response.output_item.done"),
1047 output_index: Schema.Int,
1048 sequence_number: Schema.optionalKey(Schema.Int),
1049 item: OutputItem
1050})
1051
1052const ResponseOutputTextDeltaEvent = Schema.Struct({
1053 type: Schema.Literal("response.output_text.delta"),
1054 item_id: Schema.String,
1055 output_index: Schema.Int,
1056 content_index: Schema.Int,
1057 delta: Schema.String,
1058 sequence_number: Schema.optionalKey(Schema.Int),
1059 logprobs: Schema.optionalKey(Schema.Array(Schema.Unknown))
1060})
1061
1062const ResponseOutputTextAnnotationAddedEvent = Schema.Struct({
1063 type: Schema.Literal("response.output_text.annotation.added"),
1064 item_id: Schema.String,
1065 output_index: Schema.Int,
1066 content_index: Schema.Int,
1067 annotation_index: Schema.Int,
1068 sequence_number: Schema.optionalKey(Schema.Int),
1069 annotation: Annotation
1070})
1071
1072const ResponseReasoningSummaryPartAddedEvent = Schema.Struct({
1073 type: Schema.Literal("response.reasoning_summary_part.added"),
1074 item_id: Schema.String,
1075 output_index: Schema.Int,
1076 summary_index: Schema.Int,
1077 sequence_number: Schema.optionalKey(Schema.Int),
1078 part: SummaryTextContent
1079})
1080
1081const ResponseReasoningSummaryPartDoneEvent = Schema.Struct({
1082 type: Schema.Literal("response.reasoning_summary_part.done"),
1083 item_id: Schema.String,
1084 output_index: Schema.Int,
1085 summary_index: Schema.Int,
1086 sequence_number: Schema.optionalKey(Schema.Int),
1087 part: SummaryTextContent
1088})
1089
1090const ResponseReasoningSummaryTextDeltaEvent = Schema.Struct({
1091 type: Schema.Literal("response.reasoning_summary_text.delta"),
1092 item_id: Schema.String,
1093 output_index: Schema.Int,
1094 summary_index: Schema.Int,
1095 delta: Schema.String,
1096 sequence_number: Schema.optionalKey(Schema.Int)
1097})
1098
1099const ResponseFunctionCallArgumentsDeltaEvent = Schema.Struct({
1100 type: Schema.Literal("response.function_call_arguments.delta"),
1101 item_id: Schema.String,
1102 output_index: Schema.Int,
1103 sequence_number: Schema.optionalKey(Schema.Int),
1104 delta: Schema.String
1105})
1106
1107const ResponseFunctionCallArgumentsDoneEvent = Schema.Struct({
1108 type: Schema.Literal("response.function_call_arguments.done"),
1109 item_id: Schema.String,
1110 output_index: Schema.Int,
1111 sequence_number: Schema.optionalKey(Schema.Int),
1112 arguments: Schema.String
1113})
1114
1115const ResponseCodeInterpreterCallCodeDeltaEvent = Schema.Struct({
1116 type: Schema.Literal("response.code_interpreter_call_code.delta"),
1117 item_id: Schema.String,
1118 output_index: Schema.Int,
1119 sequence_number: Schema.optionalKey(Schema.Int),
1120 delta: Schema.String
1121})
1122
1123const ResponseCodeInterpreterCallCodeDoneEvent = Schema.Struct({
1124 type: Schema.Literal("response.code_interpreter_call_code.done"),
1125 item_id: Schema.String,
1126 output_index: Schema.Int,
1127 sequence_number: Schema.optionalKey(Schema.Int),
1128 code: Schema.String
1129})
1130
1131const ResponseApplyPatchCallOperationDiffDeltaEvent = Schema.Struct({
1132 type: Schema.Literal("response.apply_patch_call_operation_diff.delta"),
1133 item_id: Schema.String,
1134 output_index: Schema.Int,
1135 sequence_number: Schema.optionalKey(Schema.Int),
1136 delta: Schema.String
1137})
1138
1139const ResponseApplyPatchCallOperationDiffDoneEvent = Schema.Struct({
1140 type: Schema.Literal("response.apply_patch_call_operation_diff.done"),
1141 item_id: Schema.String,
1142 output_index: Schema.Int,
1143 sequence_number: Schema.optionalKey(Schema.Int),
1144 delta: Schema.optionalKey(Schema.String)
1145})
1146
1147const ResponseImageGenerationCallPartialImageEvent = Schema.Struct({
1148 type: Schema.Literal("response.image_generation_call.partial_image"),
1149 item_id: Schema.String,
1150 output_index: Schema.Int,
1151 sequence_number: Schema.optionalKey(Schema.Int),
1152 partial_image_b64: Schema.String
1153})
1154
1155const ResponseErrorEvent = Schema.Struct({
1156 type: Schema.Literal("error"),
1157 code: Schema.NullOr(Schema.String),
1158 message: Schema.String,
1159 param: Schema.NullOr(Schema.String),
1160 sequence_number: Schema.optionalKey(Schema.Int),
1161 status: Schema.optionalKey(Schema.Int)
1162})
1163
1164// OpenAI can nest stream error details under `error`.
1165const NestedResponseErrorEvent = Schema.Struct({
1166 type: Schema.Literal("error"),
1167 error: Schema.Struct({
1168 code: Schema.NullOr(Schema.String),
1169 message: Schema.String,
1170 param: Schema.NullOr(Schema.String)
1171 }),
1172 sequence_number: Schema.optionalKey(Schema.Int),
1173 status: Schema.optionalKey(Schema.Int)
1174}).pipe(
1175 Schema.decodeTo(
1176 ResponseErrorEvent,
1177 SchemaTransformation.transform({
1178 decode: ({ error, ...rest }) => ({ ...rest, ...error }),
1179 encode: ({ code, message, param, ...rest }) => ({ ...rest, error: { code, message, param } })
1180 })
1181 )
1182)
1183
1184const knownResponseStreamEventTypes = new Set([
1185 "response.created",
1186 "response.completed",
1187 "response.incomplete",
1188 "response.failed",
1189 "response.output_item.added",
1190 "response.output_item.done",
1191 "response.output_text.delta",
1192 "response.output_text.annotation.added",
1193 "response.reasoning_summary_part.added",
1194 "response.reasoning_summary_part.done",
1195 "response.reasoning_summary_text.delta",
1196 "response.function_call_arguments.delta",
1197 "response.function_call_arguments.done",
1198 "response.code_interpreter_call_code.delta",
1199 "response.code_interpreter_call_code.done",
1200 "response.apply_patch_call_operation_diff.delta",
1201 "response.apply_patch_call_operation_diff.done",
1202 "response.image_generation_call.partial_image",
1203 "error"
1204])
1205
1206/**
1207 * Fallback event shape for future or provider-specific response stream events.
1208 *
1209 * @stability unstable
1210 * @category models
1211 * @since 4.0.0
1212 */
1213export type UnknownResponseStreamEvent = {
1214 readonly type: string
1215 readonly [key: string]: unknown
1216}
1217
1218const UnknownResponseStreamEvent = Schema.declare<UnknownResponseStreamEvent>(
1219 (value): value is UnknownResponseStreamEvent =>
1220 Predicate.hasProperty(value, "type") &&
1221 typeof value.type === "string" &&
1222 !knownResponseStreamEventTypes.has(value.type),
1223 {
1224 identifier: "UnknownResponseStreamEvent",
1225 description: "Fallback for unknown future stream events"
1226 }
1227)
1228
1229/**
1230 * Schema for server-sent event shapes emitted by OpenAI Responses API streams.
1231 *
1232 * **When to use**
1233 *
1234 * Use to decode events from a streaming OpenAI Responses API request.
1235 *
1236 * **Details**
1237 *
1238 * Known event variants include response lifecycle events, output item events,
1239 * text and reasoning deltas, tool-call deltas, partial image events, and error
1240 * events.
1241 *
1242 * **Gotchas**
1243 *
1244 * Future event types decode through the fallback only when their `type` is not
1245 * one of the known event types. Malformed known events still fail to decode.
1246 *
1247 * @see {@link Response} for complete response objects carried by lifecycle events
1248 * @see {@link UnknownResponseStreamEvent} for the fallback shape for future event types
1249 *
1250 * @stability unstable
1251 * @category schemas
1252 * @since 4.0.0
1253 */
1254export const ResponseStreamEvent = Schema.Union([
1255 ResponseCreatedEvent,
1256 ResponseCompletedEvent,
1257 ResponseIncompleteEvent,
1258 ResponseFailedEvent,
1259 ResponseOutputItemAddedEvent,
1260 ResponseOutputItemDoneEvent,
1261 ResponseOutputTextDeltaEvent,
1262 ResponseOutputTextAnnotationAddedEvent,
1263 ResponseReasoningSummaryPartAddedEvent,
1264 ResponseReasoningSummaryPartDoneEvent,
1265 ResponseReasoningSummaryTextDeltaEvent,
1266 ResponseFunctionCallArgumentsDeltaEvent,
1267 ResponseFunctionCallArgumentsDoneEvent,
1268 ResponseCodeInterpreterCallCodeDeltaEvent,
1269 ResponseCodeInterpreterCallCodeDoneEvent,
1270 ResponseApplyPatchCallOperationDiffDeltaEvent,
1271 ResponseApplyPatchCallOperationDiffDoneEvent,
1272 ResponseImageGenerationCallPartialImageEvent,
1273 ResponseErrorEvent,
1274 NestedResponseErrorEvent,
1275 UnknownResponseStreamEvent
1276])
1277
1278/**
1279 * Server-sent event shape emitted by OpenAI Responses API streams.
1280 *
1281 * **When to use**
1282 *
1283 * Use when typing events from a streaming OpenAI Responses API request.
1284 *
1285 * **Details**
1286 *
1287 * Includes known response stream events plus a fallback shape for unknown future
1288 * event types.
1289 *
1290 * @stability unstable
1291 * @category models
1292 * @since 4.0.0
1293 */
1294export type ResponseStreamEvent = typeof ResponseStreamEvent.Type
1295
1296/**
1297 * Schema for one embedding item returned by the OpenAI embeddings API.
1298 *
1299 * **When to use**
1300 *
1301 * Use when validating individual embedding entries at the OpenAI client boundary
1302 * before assuming the embedding payload is a numeric vector.
1303 *
1304 * **Details**
1305 *
1306 * An embedding item contains its `index`, optional `object` marker, and an
1307 * `embedding` represented either as a numeric vector or as a string.
1308 *
1309 * **Gotchas**
1310 *
1311 * Callers that need numeric vectors must account for string embeddings, such as
1312 * base64-encoded embeddings returned for string encoding formats.
1313 *
1314 * @stability unstable
1315 * @category schemas
1316 * @since 4.0.0
1317 */
1318export const Embedding = Schema.Struct({
1319 embedding: Schema.Union([
1320 Schema.Array(Schema.Finite),
1321 Schema.String
1322 ]),
1323 index: Schema.Int,
1324 object: Schema.optionalKey(Schema.String)
1325})
1326
1327/**
1328 * One embedding item returned by the OpenAI embeddings API.
1329 *
1330 * **Details**
1331 *
1332 * Contains the item index and embedding payload. The embedding payload may be a
1333 * numeric vector or a string.
1334 *
1335 * @stability unstable
1336 * @category models
1337 * @since 4.0.0
1338 */
1339export type Embedding = typeof Embedding.Type
1340
1341/**
1342 * Schema for the request payload sent to the OpenAI embeddings endpoint.
1343 *
1344 * **When to use**
1345 *
1346 * Use when validating or encoding embeddings requests before sending them to
1347 * OpenAI, while leaving model-specific limits to the provider.
1348 *
1349 * **Details**
1350 *
1351 * Requires `input` and `model`. `input` may be a string, an array of strings,
1352 * a token array, or an array of token arrays. Optional fields configure the
1353 * embedding encoding format, requested dimensions, and user identifier.
1354 *
1355 * **Gotchas**
1356 *
1357 * This schema validates the transport shape, but OpenAI still enforces
1358 * provider-side constraints such as non-empty input, integer token ids, input
1359 * size limits, positive dimensions, and model-specific dimension support.
1360 *
1361 * @stability unstable
1362 * @category schemas
1363 * @since 4.0.0
1364 */
1365export const CreateEmbeddingRequest = Schema.Struct({
1366 input: Schema.Union([
1367 Schema.String,
1368 Schema.Array(Schema.String),
1369 Schema.Array(Schema.Int),
1370 Schema.Array(Schema.Array(Schema.Int))
1371 ]),
1372 model: Schema.String,
1373 encoding_format: Schema.optionalKey(Schema.Literals(["float", "base64"])),
1374 dimensions: Schema.optionalKey(Schema.Int),
1375 user: Schema.optionalKey(Schema.String)
1376})
1377
1378/**
1379 * Request payload sent to the OpenAI embeddings endpoint.
1380 *
1381 * @stability unstable
1382 * @category models
1383 * @since 4.0.0
1384 */
1385export type CreateEmbeddingRequest = typeof CreateEmbeddingRequest.Type
1386
1387/**
1388 * Schema for a successful response payload returned by the OpenAI embeddings endpoint.
1389 *
1390 * **When to use**
1391 *
1392 * Use when you need to validate embeddings responses at an OpenAI client
1393 * boundary before trusting item shapes, especially when numeric and string
1394 * embeddings are both allowed.
1395 *
1396 * **Details**
1397 *
1398 * The response contains an array of `Embedding` items, the model name, an
1399 * optional `object: "list"` marker, and optional token usage counts for prompt
1400 * and total tokens.
1401 *
1402 * **Gotchas**
1403 *
1404 * Each `Embedding` may contain either a numeric vector or a string embedding.
1405 * Callers that require numeric vectors must account for string embeddings.
1406 *
1407 * @see {@link CreateEmbeddingRequest} for the request schema sent to the embeddings endpoint
1408 * @see {@link Embedding} for individual embedding items in the response
1409 *
1410 * @stability unstable
1411 * @category schemas
1412 * @since 4.0.0
1413 */
1414export const CreateEmbeddingResponse = Schema.Struct({
1415 data: Schema.Array(Embedding),
1416 model: Schema.String,
1417 object: Schema.optionalKey(Schema.Literal("list")),
1418 usage: Schema.optionalKey(
1419 Schema.Struct({
1420 prompt_tokens: Schema.Int,
1421 total_tokens: Schema.Int
1422 })
1423 )
1424})
1425
1426/**
1427 * Successful response payload returned by the OpenAI embeddings endpoint.
1428 *
1429 * **When to use**
1430 *
1431 * Use when typing successful OpenAI embeddings responses.
1432 *
1433 * **Details**
1434 *
1435 * Contains embedding items, the model name, optional list marker, and optional
1436 * token usage counts.
1437 *
1438 * @stability unstable
1439 * @category models
1440 * @since 4.0.0
1441 */
1442export type CreateEmbeddingResponse = typeof CreateEmbeddingResponse.Type