openai-responses-language-model.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. import {
  2. APICallError,
  3. type JSONValue,
  4. type LanguageModelV3,
  5. type LanguageModelV3CallOptions,
  6. type LanguageModelV3Content,
  7. type LanguageModelV3ProviderTool,
  8. type LanguageModelV3StreamPart,
  9. type SharedV3ProviderMetadata,
  10. type SharedV3Warning,
  11. } from "@ai-sdk/provider"
  12. import {
  13. combineHeaders,
  14. createEventSourceResponseHandler,
  15. createJsonResponseHandler,
  16. generateId,
  17. parseProviderOptions,
  18. type ParseResult,
  19. postJsonToApi,
  20. } from "@ai-sdk/provider-utils"
  21. import { z } from "zod/v4"
  22. import type { OpenAIConfig } from "./openai-config"
  23. import { openaiFailedResponseHandler } from "./openai-error"
  24. import { codeInterpreterInputSchema, codeInterpreterOutputSchema } from "./tool/code-interpreter"
  25. import { fileSearchOutputSchema } from "./tool/file-search"
  26. import { imageGenerationOutputSchema } from "./tool/image-generation"
  27. import { convertToOpenAIResponsesInput } from "./convert-to-openai-responses-input"
  28. import { mapOpenAIResponseFinishReason } from "./map-openai-responses-finish-reason"
  29. import type { OpenAIResponsesIncludeOptions, OpenAIResponsesIncludeValue } from "./openai-responses-api-types"
  30. import { prepareResponsesTools } from "./openai-responses-prepare-tools"
  31. import type { OpenAIResponsesModelId } from "./openai-responses-settings"
  32. import { localShellInputSchema } from "./tool/local-shell"
  33. const webSearchCallItem = z.object({
  34. type: z.literal("web_search_call"),
  35. id: z.string(),
  36. status: z.string(),
  37. action: z
  38. .discriminatedUnion("type", [
  39. z.object({
  40. type: z.literal("search"),
  41. query: z.string().nullish(),
  42. }),
  43. z.object({
  44. type: z.literal("open_page"),
  45. url: z.string(),
  46. }),
  47. z.object({
  48. type: z.literal("find"),
  49. url: z.string(),
  50. pattern: z.string(),
  51. }),
  52. ])
  53. .nullish(),
  54. })
  55. const fileSearchCallItem = z.object({
  56. type: z.literal("file_search_call"),
  57. id: z.string(),
  58. queries: z.array(z.string()),
  59. results: z
  60. .array(
  61. z.object({
  62. attributes: z.record(z.string(), z.unknown()),
  63. file_id: z.string(),
  64. filename: z.string(),
  65. score: z.number(),
  66. text: z.string(),
  67. }),
  68. )
  69. .nullish(),
  70. })
  71. const codeInterpreterCallItem = z.object({
  72. type: z.literal("code_interpreter_call"),
  73. id: z.string(),
  74. code: z.string().nullable(),
  75. container_id: z.string(),
  76. outputs: z
  77. .array(
  78. z.discriminatedUnion("type", [
  79. z.object({ type: z.literal("logs"), logs: z.string() }),
  80. z.object({ type: z.literal("image"), url: z.string() }),
  81. ]),
  82. )
  83. .nullable(),
  84. })
  85. const localShellCallItem = z.object({
  86. type: z.literal("local_shell_call"),
  87. id: z.string(),
  88. call_id: z.string(),
  89. action: z.object({
  90. type: z.literal("exec"),
  91. command: z.array(z.string()),
  92. timeout_ms: z.number().optional(),
  93. user: z.string().optional(),
  94. working_directory: z.string().optional(),
  95. env: z.record(z.string(), z.string()).optional(),
  96. }),
  97. })
  98. const imageGenerationCallItem = z.object({
  99. type: z.literal("image_generation_call"),
  100. id: z.string(),
  101. result: z.string(),
  102. })
  103. /**
  104. * `top_logprobs` request body argument can be set to an integer between
  105. * 0 and 20 specifying the number of most likely tokens to return at each
  106. * token position, each with an associated log probability.
  107. *
  108. * @see https://platform.openai.com/docs/api-reference/responses/create#responses_create-top_logprobs
  109. */
  110. const TOP_LOGPROBS_MAX = 20
  111. const LOGPROBS_SCHEMA = z.array(
  112. z.object({
  113. token: z.string(),
  114. logprob: z.number(),
  115. top_logprobs: z.array(
  116. z.object({
  117. token: z.string(),
  118. logprob: z.number(),
  119. }),
  120. ),
  121. }),
  122. )
  123. export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
  124. readonly specificationVersion = "v3"
  125. readonly modelId: OpenAIResponsesModelId
  126. private readonly config: OpenAIConfig
  127. constructor(modelId: OpenAIResponsesModelId, config: OpenAIConfig) {
  128. this.modelId = modelId
  129. this.config = config
  130. }
  131. readonly supportedUrls: Record<string, RegExp[]> = {
  132. "image/*": [/^https?:\/\/.*$/],
  133. "application/pdf": [/^https?:\/\/.*$/],
  134. }
  135. get provider(): string {
  136. return this.config.provider
  137. }
  138. private async getArgs({
  139. maxOutputTokens,
  140. temperature,
  141. stopSequences,
  142. topP,
  143. topK,
  144. presencePenalty,
  145. frequencyPenalty,
  146. seed,
  147. prompt,
  148. providerOptions,
  149. tools,
  150. toolChoice,
  151. responseFormat,
  152. }: LanguageModelV3CallOptions) {
  153. const warnings: SharedV3Warning[] = []
  154. const modelConfig = getResponsesModelConfig(this.modelId)
  155. if (topK != null) {
  156. warnings.push({ type: "unsupported", feature: "topK" })
  157. }
  158. if (seed != null) {
  159. warnings.push({ type: "unsupported", feature: "seed" })
  160. }
  161. if (presencePenalty != null) {
  162. warnings.push({
  163. type: "unsupported",
  164. feature: "presencePenalty",
  165. })
  166. }
  167. if (frequencyPenalty != null) {
  168. warnings.push({
  169. type: "unsupported",
  170. feature: "frequencyPenalty",
  171. })
  172. }
  173. if (stopSequences != null) {
  174. warnings.push({ type: "unsupported", feature: "stopSequences" })
  175. }
  176. const openaiOptions = await parseProviderOptions({
  177. provider: "copilot",
  178. providerOptions,
  179. schema: openaiResponsesProviderOptionsSchema,
  180. })
  181. const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
  182. prompt,
  183. systemMessageMode: modelConfig.systemMessageMode,
  184. fileIdPrefixes: this.config.fileIdPrefixes,
  185. store: openaiOptions?.store ?? true,
  186. hasLocalShellTool: hasOpenAITool("openai.local_shell"),
  187. })
  188. warnings.push(...inputWarnings)
  189. const strictJsonSchema = openaiOptions?.strictJsonSchema ?? false
  190. let include: OpenAIResponsesIncludeOptions = openaiOptions?.include
  191. function addInclude(key: OpenAIResponsesIncludeValue) {
  192. include = include != null ? [...include, key] : [key]
  193. }
  194. function hasOpenAITool(id: string) {
  195. return tools?.find((tool) => tool.type === "provider" && tool.id === id) != null
  196. }
  197. // when logprobs are requested, automatically include them:
  198. const topLogprobs =
  199. typeof openaiOptions?.logprobs === "number"
  200. ? openaiOptions?.logprobs
  201. : openaiOptions?.logprobs === true
  202. ? TOP_LOGPROBS_MAX
  203. : undefined
  204. if (topLogprobs) {
  205. addInclude("message.output_text.logprobs")
  206. }
  207. // when a web search tool is present, automatically include the sources:
  208. const webSearchToolName = (
  209. tools?.find(
  210. (tool) =>
  211. tool.type === "provider" && (tool.id === "openai.web_search" || tool.id === "openai.web_search_preview"),
  212. ) as LanguageModelV3ProviderTool | undefined
  213. )?.name
  214. if (webSearchToolName) {
  215. addInclude("web_search_call.action.sources")
  216. }
  217. // when a code interpreter tool is present, automatically include the outputs:
  218. if (hasOpenAITool("openai.code_interpreter")) {
  219. addInclude("code_interpreter_call.outputs")
  220. }
  221. const baseArgs = {
  222. model: this.modelId,
  223. input,
  224. temperature,
  225. top_p: topP,
  226. max_output_tokens: maxOutputTokens,
  227. ...((responseFormat?.type === "json" || openaiOptions?.textVerbosity) && {
  228. text: {
  229. ...(responseFormat?.type === "json" && {
  230. format:
  231. responseFormat.schema != null
  232. ? {
  233. type: "json_schema",
  234. strict: strictJsonSchema,
  235. name: responseFormat.name ?? "response",
  236. description: responseFormat.description,
  237. schema: responseFormat.schema,
  238. }
  239. : { type: "json_object" },
  240. }),
  241. ...(openaiOptions?.textVerbosity && {
  242. verbosity: openaiOptions.textVerbosity,
  243. }),
  244. },
  245. }),
  246. // provider options:
  247. max_tool_calls: openaiOptions?.maxToolCalls,
  248. metadata: openaiOptions?.metadata,
  249. parallel_tool_calls: openaiOptions?.parallelToolCalls,
  250. previous_response_id: openaiOptions?.previousResponseId,
  251. store: openaiOptions?.store,
  252. user: openaiOptions?.user,
  253. instructions: openaiOptions?.instructions,
  254. service_tier: openaiOptions?.serviceTier,
  255. include,
  256. prompt_cache_key: openaiOptions?.promptCacheKey,
  257. safety_identifier: openaiOptions?.safetyIdentifier,
  258. top_logprobs: topLogprobs,
  259. // model-specific settings:
  260. ...(modelConfig.isReasoningModel &&
  261. (openaiOptions?.reasoningEffort != null || openaiOptions?.reasoningSummary != null) && {
  262. reasoning: {
  263. ...(openaiOptions?.reasoningEffort != null && {
  264. effort: openaiOptions.reasoningEffort,
  265. }),
  266. ...(openaiOptions?.reasoningSummary != null && {
  267. summary: openaiOptions.reasoningSummary,
  268. }),
  269. },
  270. }),
  271. ...(modelConfig.requiredAutoTruncation && {
  272. truncation: "auto",
  273. }),
  274. }
  275. if (modelConfig.isReasoningModel) {
  276. // remove unsupported settings for reasoning models
  277. // see https://platform.openai.com/docs/guides/reasoning#limitations
  278. if (baseArgs.temperature != null) {
  279. baseArgs.temperature = undefined
  280. warnings.push({
  281. type: "unsupported",
  282. feature: "temperature",
  283. details: "temperature is not supported for reasoning models",
  284. })
  285. }
  286. if (baseArgs.top_p != null) {
  287. baseArgs.top_p = undefined
  288. warnings.push({
  289. type: "unsupported",
  290. feature: "topP",
  291. details: "topP is not supported for reasoning models",
  292. })
  293. }
  294. } else {
  295. if (openaiOptions?.reasoningEffort != null) {
  296. warnings.push({
  297. type: "unsupported",
  298. feature: "reasoningEffort",
  299. details: "reasoningEffort is not supported for non-reasoning models",
  300. })
  301. }
  302. if (openaiOptions?.reasoningSummary != null) {
  303. warnings.push({
  304. type: "unsupported",
  305. feature: "reasoningSummary",
  306. details: "reasoningSummary is not supported for non-reasoning models",
  307. })
  308. }
  309. }
  310. // Validate flex processing support
  311. if (openaiOptions?.serviceTier === "flex" && !modelConfig.supportsFlexProcessing) {
  312. warnings.push({
  313. type: "unsupported",
  314. feature: "serviceTier",
  315. details: "flex processing is only available for o3, o4-mini, and gpt-5 models",
  316. })
  317. // Remove from args if not supported
  318. baseArgs.service_tier = undefined
  319. }
  320. // Validate priority processing support
  321. if (openaiOptions?.serviceTier === "priority" && !modelConfig.supportsPriorityProcessing) {
  322. warnings.push({
  323. type: "unsupported",
  324. feature: "serviceTier",
  325. details:
  326. "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported",
  327. })
  328. // Remove from args if not supported
  329. baseArgs.service_tier = undefined
  330. }
  331. const {
  332. tools: openaiTools,
  333. toolChoice: openaiToolChoice,
  334. toolWarnings,
  335. } = prepareResponsesTools({
  336. tools,
  337. toolChoice,
  338. strictJsonSchema,
  339. })
  340. return {
  341. webSearchToolName,
  342. args: {
  343. ...baseArgs,
  344. tools: openaiTools,
  345. tool_choice: openaiToolChoice,
  346. },
  347. warnings: [...warnings, ...toolWarnings],
  348. }
  349. }
  350. async doGenerate(options: LanguageModelV3CallOptions) {
  351. const { args: body, warnings, webSearchToolName } = await this.getArgs(options)
  352. const url = this.config.url({
  353. path: "/responses",
  354. modelId: this.modelId,
  355. })
  356. const {
  357. responseHeaders,
  358. value: response,
  359. rawValue: rawResponse,
  360. } = await postJsonToApi({
  361. url,
  362. headers: combineHeaders(this.config.headers(), options.headers),
  363. body,
  364. failedResponseHandler: openaiFailedResponseHandler,
  365. successfulResponseHandler: createJsonResponseHandler(
  366. z.object({
  367. id: z.string(),
  368. created_at: z.number(),
  369. error: z
  370. .object({
  371. code: z.string(),
  372. message: z.string(),
  373. })
  374. .nullish(),
  375. model: z.string(),
  376. output: z.array(
  377. z.discriminatedUnion("type", [
  378. z.object({
  379. type: z.literal("message"),
  380. role: z.literal("assistant"),
  381. id: z.string(),
  382. content: z.array(
  383. z.object({
  384. type: z.literal("output_text"),
  385. text: z.string(),
  386. logprobs: LOGPROBS_SCHEMA.nullish(),
  387. annotations: z.array(
  388. z.discriminatedUnion("type", [
  389. z.object({
  390. type: z.literal("url_citation"),
  391. start_index: z.number(),
  392. end_index: z.number(),
  393. url: z.string(),
  394. title: z.string(),
  395. }),
  396. z.object({
  397. type: z.literal("file_citation"),
  398. file_id: z.string(),
  399. filename: z.string().nullish(),
  400. index: z.number().nullish(),
  401. start_index: z.number().nullish(),
  402. end_index: z.number().nullish(),
  403. quote: z.string().nullish(),
  404. }),
  405. z.object({
  406. type: z.literal("container_file_citation"),
  407. }),
  408. ]),
  409. ),
  410. }),
  411. ),
  412. }),
  413. webSearchCallItem,
  414. fileSearchCallItem,
  415. codeInterpreterCallItem,
  416. imageGenerationCallItem,
  417. localShellCallItem,
  418. z.object({
  419. type: z.literal("function_call"),
  420. call_id: z.string(),
  421. name: z.string(),
  422. arguments: z.string(),
  423. id: z.string(),
  424. }),
  425. z.object({
  426. type: z.literal("computer_call"),
  427. id: z.string(),
  428. status: z.string().optional(),
  429. }),
  430. z.object({
  431. type: z.literal("reasoning"),
  432. id: z.string(),
  433. encrypted_content: z.string().nullish(),
  434. summary: z.array(
  435. z.object({
  436. type: z.literal("summary_text"),
  437. text: z.string(),
  438. }),
  439. ),
  440. }),
  441. ]),
  442. ),
  443. service_tier: z.string().nullish(),
  444. incomplete_details: z.object({ reason: z.string() }).nullish(),
  445. usage: usageSchema,
  446. }),
  447. ),
  448. abortSignal: options.abortSignal,
  449. fetch: this.config.fetch,
  450. })
  451. if (response.error) {
  452. throw new APICallError({
  453. message: response.error.message,
  454. url,
  455. requestBodyValues: body,
  456. statusCode: 400,
  457. responseHeaders,
  458. responseBody: rawResponse as string,
  459. isRetryable: false,
  460. })
  461. }
  462. const content: Array<LanguageModelV3Content> = []
  463. const logprobs: Array<z.infer<typeof LOGPROBS_SCHEMA>> = []
  464. // flag that checks if there have been client-side tool calls (not executed by openai)
  465. let hasFunctionCall = false
  466. // map response content to content array
  467. for (const part of response.output) {
  468. switch (part.type) {
  469. case "reasoning": {
  470. // when there are no summary parts, we need to add an empty reasoning part:
  471. if (part.summary.length === 0) {
  472. part.summary.push({ type: "summary_text", text: "" })
  473. }
  474. for (const summary of part.summary) {
  475. content.push({
  476. type: "reasoning" as const,
  477. text: summary.text,
  478. providerMetadata: {
  479. openai: {
  480. itemId: part.id,
  481. reasoningEncryptedContent: part.encrypted_content ?? null,
  482. },
  483. },
  484. })
  485. }
  486. break
  487. }
  488. case "image_generation_call": {
  489. content.push({
  490. type: "tool-call",
  491. toolCallId: part.id,
  492. toolName: "image_generation",
  493. input: "{}",
  494. providerExecuted: true,
  495. })
  496. content.push({
  497. type: "tool-result",
  498. toolCallId: part.id,
  499. toolName: "image_generation",
  500. result: {
  501. result: part.result,
  502. } satisfies z.infer<typeof imageGenerationOutputSchema>,
  503. })
  504. break
  505. }
  506. case "local_shell_call": {
  507. content.push({
  508. type: "tool-call",
  509. toolCallId: part.call_id,
  510. toolName: "local_shell",
  511. input: JSON.stringify({ action: part.action } satisfies z.infer<typeof localShellInputSchema>),
  512. providerMetadata: {
  513. openai: {
  514. itemId: part.id,
  515. },
  516. },
  517. })
  518. break
  519. }
  520. case "message": {
  521. for (const contentPart of part.content) {
  522. if (options.providerOptions?.openai?.logprobs && contentPart.logprobs) {
  523. logprobs.push(contentPart.logprobs)
  524. }
  525. content.push({
  526. type: "text",
  527. text: contentPart.text,
  528. providerMetadata: {
  529. openai: {
  530. itemId: part.id,
  531. },
  532. },
  533. })
  534. for (const annotation of contentPart.annotations) {
  535. if (annotation.type === "url_citation") {
  536. content.push({
  537. type: "source",
  538. sourceType: "url",
  539. id: this.config.generateId?.() ?? generateId(),
  540. url: annotation.url,
  541. title: annotation.title,
  542. })
  543. } else if (annotation.type === "file_citation") {
  544. content.push({
  545. type: "source",
  546. sourceType: "document",
  547. id: this.config.generateId?.() ?? generateId(),
  548. mediaType: "text/plain",
  549. title: annotation.quote ?? annotation.filename ?? "Document",
  550. filename: annotation.filename ?? annotation.file_id,
  551. })
  552. }
  553. }
  554. }
  555. break
  556. }
  557. case "function_call": {
  558. hasFunctionCall = true
  559. content.push({
  560. type: "tool-call",
  561. toolCallId: part.call_id,
  562. toolName: part.name,
  563. input: part.arguments,
  564. providerMetadata: {
  565. openai: {
  566. itemId: part.id,
  567. },
  568. },
  569. })
  570. break
  571. }
  572. case "web_search_call": {
  573. content.push({
  574. type: "tool-call",
  575. toolCallId: part.id,
  576. toolName: webSearchToolName ?? "web_search",
  577. input: JSON.stringify({ action: part.action }),
  578. providerExecuted: true,
  579. })
  580. content.push({
  581. type: "tool-result",
  582. toolCallId: part.id,
  583. toolName: webSearchToolName ?? "web_search",
  584. result: { status: part.status },
  585. })
  586. break
  587. }
  588. case "computer_call": {
  589. content.push({
  590. type: "tool-call",
  591. toolCallId: part.id,
  592. toolName: "computer_use",
  593. input: "",
  594. providerExecuted: true,
  595. })
  596. content.push({
  597. type: "tool-result",
  598. toolCallId: part.id,
  599. toolName: "computer_use",
  600. result: {
  601. type: "computer_use_tool_result",
  602. status: part.status || "completed",
  603. },
  604. })
  605. break
  606. }
  607. case "file_search_call": {
  608. content.push({
  609. type: "tool-call",
  610. toolCallId: part.id,
  611. toolName: "file_search",
  612. input: "{}",
  613. providerExecuted: true,
  614. })
  615. content.push({
  616. type: "tool-result",
  617. toolCallId: part.id,
  618. toolName: "file_search",
  619. result: {
  620. queries: part.queries,
  621. results:
  622. part.results?.map((result) => ({
  623. attributes: result.attributes as Record<string, JSONValue>,
  624. fileId: result.file_id,
  625. filename: result.filename,
  626. score: result.score,
  627. text: result.text,
  628. })) ?? null,
  629. } satisfies z.infer<typeof fileSearchOutputSchema>,
  630. })
  631. break
  632. }
  633. case "code_interpreter_call": {
  634. content.push({
  635. type: "tool-call",
  636. toolCallId: part.id,
  637. toolName: "code_interpreter",
  638. input: JSON.stringify({
  639. code: part.code,
  640. containerId: part.container_id,
  641. } satisfies z.infer<typeof codeInterpreterInputSchema>),
  642. providerExecuted: true,
  643. })
  644. content.push({
  645. type: "tool-result",
  646. toolCallId: part.id,
  647. toolName: "code_interpreter",
  648. result: {
  649. outputs: part.outputs,
  650. } satisfies z.infer<typeof codeInterpreterOutputSchema>,
  651. })
  652. break
  653. }
  654. }
  655. }
  656. const providerMetadata: SharedV3ProviderMetadata = {
  657. openai: { responseId: response.id },
  658. }
  659. if (logprobs.length > 0) {
  660. providerMetadata.openai.logprobs = logprobs
  661. }
  662. if (typeof response.service_tier === "string") {
  663. providerMetadata.openai.serviceTier = response.service_tier
  664. }
  665. return {
  666. content,
  667. finishReason: {
  668. unified: mapOpenAIResponseFinishReason({
  669. finishReason: response.incomplete_details?.reason,
  670. hasFunctionCall,
  671. }),
  672. raw: response.incomplete_details?.reason,
  673. },
  674. usage: {
  675. inputTokens: {
  676. total: response.usage.input_tokens,
  677. noCache:
  678. response.usage.input_tokens_details?.cached_tokens != null
  679. ? response.usage.input_tokens - response.usage.input_tokens_details.cached_tokens
  680. : undefined,
  681. cacheRead: response.usage.input_tokens_details?.cached_tokens ?? undefined,
  682. cacheWrite: undefined,
  683. },
  684. outputTokens: {
  685. total: response.usage.output_tokens,
  686. text: undefined,
  687. reasoning: response.usage.output_tokens_details?.reasoning_tokens ?? undefined,
  688. },
  689. raw: response.usage,
  690. },
  691. request: { body },
  692. response: {
  693. id: response.id,
  694. timestamp: new Date(response.created_at * 1000),
  695. modelId: response.model,
  696. headers: responseHeaders,
  697. body: rawResponse,
  698. },
  699. providerMetadata,
  700. warnings,
  701. }
  702. }
  703. async doStream(options: LanguageModelV3CallOptions) {
  704. const { args: body, warnings, webSearchToolName } = await this.getArgs(options)
  705. const { responseHeaders, value: response } = await postJsonToApi({
  706. url: this.config.url({
  707. path: "/responses",
  708. modelId: this.modelId,
  709. }),
  710. headers: combineHeaders(this.config.headers(), options.headers),
  711. body: {
  712. ...body,
  713. stream: true,
  714. },
  715. failedResponseHandler: openaiFailedResponseHandler,
  716. successfulResponseHandler: createEventSourceResponseHandler(openaiResponsesChunkSchema),
  717. abortSignal: options.abortSignal,
  718. fetch: this.config.fetch,
  719. })
  720. // oxlint-disable-next-line no-this-alias -- needed for closure scope inside generator
  721. const self = this
  722. let finishReason: {
  723. unified: ReturnType<typeof mapOpenAIResponseFinishReason>
  724. raw: string | undefined
  725. } = {
  726. unified: "other",
  727. raw: undefined,
  728. }
  729. const usage: {
  730. inputTokens: number | undefined
  731. outputTokens: number | undefined
  732. totalTokens: number | undefined
  733. reasoningTokens: number | undefined
  734. cachedInputTokens: number | undefined
  735. } = {
  736. inputTokens: undefined,
  737. outputTokens: undefined,
  738. totalTokens: undefined,
  739. reasoningTokens: undefined,
  740. cachedInputTokens: undefined,
  741. }
  742. const logprobs: Array<z.infer<typeof LOGPROBS_SCHEMA>> = []
  743. let responseId: string | null = null
  744. const ongoingToolCalls: Record<
  745. number,
  746. | {
  747. toolName: string
  748. toolCallId: string
  749. codeInterpreter?: {
  750. containerId: string
  751. }
  752. }
  753. | undefined
  754. > = {}
  755. // flag that checks if there have been client-side tool calls (not executed by openai)
  756. let hasFunctionCall = false
  757. // Track reasoning by output_index instead of item_id
  758. // GitHub Copilot rotates encrypted item IDs on every event
  759. const activeReasoning: Record<
  760. number,
  761. {
  762. canonicalId: string // the item.id from output_item.added
  763. encryptedContent?: string | null
  764. summaryParts: number[]
  765. }
  766. > = {}
  767. // Track current active reasoning output_index for correlating summary events
  768. let currentReasoningOutputIndex: number | null = null
  769. // Track a stable text part id for the current assistant message.
  770. // Copilot may change item_id across text deltas; normalize to one id.
  771. let currentTextId: string | null = null
  772. let serviceTier: string | undefined
  773. return {
  774. stream: response.pipeThrough(
  775. new TransformStream<ParseResult<z.infer<typeof openaiResponsesChunkSchema>>, LanguageModelV3StreamPart>({
  776. start(controller) {
  777. controller.enqueue({ type: "stream-start", warnings })
  778. },
  779. transform(chunk, controller) {
  780. if (options.includeRawChunks) {
  781. controller.enqueue({ type: "raw", rawValue: chunk.rawValue })
  782. }
  783. // handle failed chunk parsing / validation:
  784. if (!chunk.success) {
  785. finishReason = {
  786. unified: "error",
  787. raw: undefined,
  788. }
  789. controller.enqueue({ type: "error", error: chunk.error })
  790. return
  791. }
  792. const value = chunk.value
  793. if (isResponseOutputItemAddedChunk(value)) {
  794. if (value.item.type === "function_call") {
  795. ongoingToolCalls[value.output_index] = {
  796. toolName: value.item.name,
  797. toolCallId: value.item.call_id,
  798. }
  799. controller.enqueue({
  800. type: "tool-input-start",
  801. id: value.item.call_id,
  802. toolName: value.item.name,
  803. })
  804. } else if (value.item.type === "web_search_call") {
  805. ongoingToolCalls[value.output_index] = {
  806. toolName: webSearchToolName ?? "web_search",
  807. toolCallId: value.item.id,
  808. }
  809. controller.enqueue({
  810. type: "tool-input-start",
  811. id: value.item.id,
  812. toolName: webSearchToolName ?? "web_search",
  813. })
  814. } else if (value.item.type === "computer_call") {
  815. ongoingToolCalls[value.output_index] = {
  816. toolName: "computer_use",
  817. toolCallId: value.item.id,
  818. }
  819. controller.enqueue({
  820. type: "tool-input-start",
  821. id: value.item.id,
  822. toolName: "computer_use",
  823. })
  824. } else if (value.item.type === "code_interpreter_call") {
  825. ongoingToolCalls[value.output_index] = {
  826. toolName: "code_interpreter",
  827. toolCallId: value.item.id,
  828. codeInterpreter: {
  829. containerId: value.item.container_id,
  830. },
  831. }
  832. controller.enqueue({
  833. type: "tool-input-start",
  834. id: value.item.id,
  835. toolName: "code_interpreter",
  836. })
  837. controller.enqueue({
  838. type: "tool-input-delta",
  839. id: value.item.id,
  840. delta: `{"containerId":"${value.item.container_id}","code":"`,
  841. })
  842. } else if (value.item.type === "file_search_call") {
  843. controller.enqueue({
  844. type: "tool-call",
  845. toolCallId: value.item.id,
  846. toolName: "file_search",
  847. input: "{}",
  848. providerExecuted: true,
  849. })
  850. } else if (value.item.type === "image_generation_call") {
  851. controller.enqueue({
  852. type: "tool-call",
  853. toolCallId: value.item.id,
  854. toolName: "image_generation",
  855. input: "{}",
  856. providerExecuted: true,
  857. })
  858. } else if (value.item.type === "message") {
  859. // Start a stable text part for this assistant message
  860. currentTextId = value.item.id
  861. controller.enqueue({
  862. type: "text-start",
  863. id: value.item.id,
  864. providerMetadata: {
  865. openai: {
  866. itemId: value.item.id,
  867. },
  868. },
  869. })
  870. } else if (isResponseOutputItemAddedReasoningChunk(value)) {
  871. activeReasoning[value.output_index] = {
  872. canonicalId: value.item.id,
  873. encryptedContent: value.item.encrypted_content,
  874. summaryParts: [0],
  875. }
  876. currentReasoningOutputIndex = value.output_index
  877. controller.enqueue({
  878. type: "reasoning-start",
  879. id: `${value.item.id}:0`,
  880. providerMetadata: {
  881. openai: {
  882. itemId: value.item.id,
  883. reasoningEncryptedContent: value.item.encrypted_content ?? null,
  884. },
  885. },
  886. })
  887. }
  888. } else if (isResponseOutputItemDoneChunk(value)) {
  889. if (value.item.type === "function_call") {
  890. ongoingToolCalls[value.output_index] = undefined
  891. hasFunctionCall = true
  892. controller.enqueue({
  893. type: "tool-input-end",
  894. id: value.item.call_id,
  895. })
  896. controller.enqueue({
  897. type: "tool-call",
  898. toolCallId: value.item.call_id,
  899. toolName: value.item.name,
  900. input: value.item.arguments,
  901. providerMetadata: {
  902. openai: {
  903. itemId: value.item.id,
  904. },
  905. },
  906. })
  907. } else if (value.item.type === "web_search_call") {
  908. ongoingToolCalls[value.output_index] = undefined
  909. controller.enqueue({
  910. type: "tool-input-end",
  911. id: value.item.id,
  912. })
  913. controller.enqueue({
  914. type: "tool-call",
  915. toolCallId: value.item.id,
  916. toolName: "web_search",
  917. input: JSON.stringify({ action: value.item.action }),
  918. providerExecuted: true,
  919. })
  920. controller.enqueue({
  921. type: "tool-result",
  922. toolCallId: value.item.id,
  923. toolName: "web_search",
  924. result: { status: value.item.status },
  925. })
  926. } else if (value.item.type === "computer_call") {
  927. ongoingToolCalls[value.output_index] = undefined
  928. controller.enqueue({
  929. type: "tool-input-end",
  930. id: value.item.id,
  931. })
  932. controller.enqueue({
  933. type: "tool-call",
  934. toolCallId: value.item.id,
  935. toolName: "computer_use",
  936. input: "",
  937. providerExecuted: true,
  938. })
  939. controller.enqueue({
  940. type: "tool-result",
  941. toolCallId: value.item.id,
  942. toolName: "computer_use",
  943. result: {
  944. type: "computer_use_tool_result",
  945. status: value.item.status || "completed",
  946. },
  947. })
  948. } else if (value.item.type === "file_search_call") {
  949. ongoingToolCalls[value.output_index] = undefined
  950. controller.enqueue({
  951. type: "tool-result",
  952. toolCallId: value.item.id,
  953. toolName: "file_search",
  954. result: {
  955. queries: value.item.queries,
  956. results:
  957. value.item.results?.map((result) => ({
  958. attributes: result.attributes as Record<string, JSONValue>,
  959. fileId: result.file_id,
  960. filename: result.filename,
  961. score: result.score,
  962. text: result.text,
  963. })) ?? null,
  964. } satisfies z.infer<typeof fileSearchOutputSchema>,
  965. })
  966. } else if (value.item.type === "code_interpreter_call") {
  967. ongoingToolCalls[value.output_index] = undefined
  968. controller.enqueue({
  969. type: "tool-result",
  970. toolCallId: value.item.id,
  971. toolName: "code_interpreter",
  972. result: {
  973. outputs: value.item.outputs,
  974. } satisfies z.infer<typeof codeInterpreterOutputSchema>,
  975. })
  976. } else if (value.item.type === "image_generation_call") {
  977. controller.enqueue({
  978. type: "tool-result",
  979. toolCallId: value.item.id,
  980. toolName: "image_generation",
  981. result: {
  982. result: value.item.result,
  983. } satisfies z.infer<typeof imageGenerationOutputSchema>,
  984. })
  985. } else if (value.item.type === "local_shell_call") {
  986. ongoingToolCalls[value.output_index] = undefined
  987. controller.enqueue({
  988. type: "tool-call",
  989. toolCallId: value.item.call_id,
  990. toolName: "local_shell",
  991. input: JSON.stringify({
  992. action: {
  993. type: "exec",
  994. command: value.item.action.command,
  995. timeoutMs: value.item.action.timeout_ms,
  996. user: value.item.action.user,
  997. workingDirectory: value.item.action.working_directory,
  998. env: value.item.action.env,
  999. },
  1000. } satisfies z.infer<typeof localShellInputSchema>),
  1001. providerMetadata: {
  1002. openai: { itemId: value.item.id },
  1003. },
  1004. })
  1005. } else if (value.item.type === "message") {
  1006. if (currentTextId) {
  1007. controller.enqueue({
  1008. type: "text-end",
  1009. id: currentTextId,
  1010. })
  1011. currentTextId = null
  1012. }
  1013. } else if (isResponseOutputItemDoneReasoningChunk(value)) {
  1014. const activeReasoningPart = activeReasoning[value.output_index]
  1015. if (activeReasoningPart) {
  1016. for (const summaryIndex of activeReasoningPart.summaryParts) {
  1017. controller.enqueue({
  1018. type: "reasoning-end",
  1019. id: `${activeReasoningPart.canonicalId}:${summaryIndex}`,
  1020. providerMetadata: {
  1021. openai: {
  1022. itemId: activeReasoningPart.canonicalId,
  1023. reasoningEncryptedContent: value.item.encrypted_content ?? null,
  1024. },
  1025. },
  1026. })
  1027. }
  1028. delete activeReasoning[value.output_index]
  1029. if (currentReasoningOutputIndex === value.output_index) {
  1030. currentReasoningOutputIndex = null
  1031. }
  1032. }
  1033. }
  1034. } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {
  1035. const toolCall = ongoingToolCalls[value.output_index]
  1036. if (toolCall != null) {
  1037. controller.enqueue({
  1038. type: "tool-input-delta",
  1039. id: toolCall.toolCallId,
  1040. delta: value.delta,
  1041. })
  1042. }
  1043. } else if (isResponseImageGenerationCallPartialImageChunk(value)) {
  1044. controller.enqueue({
  1045. type: "tool-result",
  1046. toolCallId: value.item_id,
  1047. toolName: "image_generation",
  1048. result: {
  1049. result: value.partial_image_b64,
  1050. } satisfies z.infer<typeof imageGenerationOutputSchema>,
  1051. })
  1052. } else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) {
  1053. const toolCall = ongoingToolCalls[value.output_index]
  1054. if (toolCall != null) {
  1055. controller.enqueue({
  1056. type: "tool-input-delta",
  1057. id: toolCall.toolCallId,
  1058. // The delta is code, which is embedding in a JSON string.
  1059. // To escape it, we use JSON.stringify and slice to remove the outer quotes.
  1060. delta: JSON.stringify(value.delta).slice(1, -1),
  1061. })
  1062. }
  1063. } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) {
  1064. const toolCall = ongoingToolCalls[value.output_index]
  1065. if (toolCall != null) {
  1066. controller.enqueue({
  1067. type: "tool-input-delta",
  1068. id: toolCall.toolCallId,
  1069. delta: '"}',
  1070. })
  1071. controller.enqueue({
  1072. type: "tool-input-end",
  1073. id: toolCall.toolCallId,
  1074. })
  1075. // immediately send the tool call after the input end:
  1076. controller.enqueue({
  1077. type: "tool-call",
  1078. toolCallId: toolCall.toolCallId,
  1079. toolName: "code_interpreter",
  1080. input: JSON.stringify({
  1081. code: value.code,
  1082. containerId: toolCall.codeInterpreter!.containerId,
  1083. } satisfies z.infer<typeof codeInterpreterInputSchema>),
  1084. providerExecuted: true,
  1085. })
  1086. }
  1087. } else if (isResponseCreatedChunk(value)) {
  1088. responseId = value.response.id
  1089. controller.enqueue({
  1090. type: "response-metadata",
  1091. id: value.response.id,
  1092. timestamp: new Date(value.response.created_at * 1000),
  1093. modelId: value.response.model,
  1094. })
  1095. } else if (isTextDeltaChunk(value)) {
  1096. // Ensure a text-start exists, and normalize deltas to a stable id
  1097. if (!currentTextId) {
  1098. currentTextId = value.item_id
  1099. controller.enqueue({
  1100. type: "text-start",
  1101. id: currentTextId,
  1102. providerMetadata: {
  1103. openai: { itemId: value.item_id },
  1104. },
  1105. })
  1106. }
  1107. controller.enqueue({
  1108. type: "text-delta",
  1109. id: currentTextId,
  1110. delta: value.delta,
  1111. })
  1112. if (options.providerOptions?.openai?.logprobs && value.logprobs) {
  1113. logprobs.push(value.logprobs)
  1114. }
  1115. } else if (isResponseReasoningSummaryPartAddedChunk(value)) {
  1116. const activeItem =
  1117. currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
  1118. // the first reasoning start is pushed in isResponseOutputItemAddedReasoningChunk.
  1119. if (activeItem && value.summary_index > 0) {
  1120. activeItem.summaryParts.push(value.summary_index)
  1121. controller.enqueue({
  1122. type: "reasoning-start",
  1123. id: `${activeItem.canonicalId}:${value.summary_index}`,
  1124. providerMetadata: {
  1125. openai: {
  1126. itemId: activeItem.canonicalId,
  1127. reasoningEncryptedContent: activeItem.encryptedContent ?? null,
  1128. },
  1129. },
  1130. })
  1131. }
  1132. } else if (isResponseReasoningSummaryTextDeltaChunk(value)) {
  1133. const activeItem =
  1134. currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
  1135. if (activeItem) {
  1136. controller.enqueue({
  1137. type: "reasoning-delta",
  1138. id: `${activeItem.canonicalId}:${value.summary_index}`,
  1139. delta: value.delta,
  1140. providerMetadata: {
  1141. openai: {
  1142. itemId: activeItem.canonicalId,
  1143. },
  1144. },
  1145. })
  1146. }
  1147. } else if (isResponseFinishedChunk(value)) {
  1148. finishReason = {
  1149. unified: mapOpenAIResponseFinishReason({
  1150. finishReason: value.response.incomplete_details?.reason,
  1151. hasFunctionCall,
  1152. }),
  1153. raw: value.response.incomplete_details?.reason ?? undefined,
  1154. }
  1155. usage.inputTokens = value.response.usage.input_tokens
  1156. usage.outputTokens = value.response.usage.output_tokens
  1157. usage.totalTokens = value.response.usage.input_tokens + value.response.usage.output_tokens
  1158. usage.reasoningTokens = value.response.usage.output_tokens_details?.reasoning_tokens ?? undefined
  1159. usage.cachedInputTokens = value.response.usage.input_tokens_details?.cached_tokens ?? undefined
  1160. if (typeof value.response.service_tier === "string") {
  1161. serviceTier = value.response.service_tier
  1162. }
  1163. } else if (isResponseAnnotationAddedChunk(value)) {
  1164. if (value.annotation.type === "url_citation") {
  1165. controller.enqueue({
  1166. type: "source",
  1167. sourceType: "url",
  1168. id: self.config.generateId?.() ?? generateId(),
  1169. url: value.annotation.url,
  1170. title: value.annotation.title,
  1171. })
  1172. } else if (value.annotation.type === "file_citation") {
  1173. controller.enqueue({
  1174. type: "source",
  1175. sourceType: "document",
  1176. id: self.config.generateId?.() ?? generateId(),
  1177. mediaType: "text/plain",
  1178. title: value.annotation.quote ?? value.annotation.filename ?? "Document",
  1179. filename: value.annotation.filename ?? value.annotation.file_id,
  1180. })
  1181. }
  1182. } else if (isErrorChunk(value)) {
  1183. controller.enqueue({ type: "error", error: value })
  1184. }
  1185. },
  1186. flush(controller) {
  1187. // Close any dangling text part
  1188. if (currentTextId) {
  1189. controller.enqueue({ type: "text-end", id: currentTextId })
  1190. currentTextId = null
  1191. }
  1192. const providerMetadata: SharedV3ProviderMetadata = {
  1193. openai: {
  1194. responseId,
  1195. },
  1196. }
  1197. if (logprobs.length > 0) {
  1198. providerMetadata.openai.logprobs = logprobs
  1199. }
  1200. if (serviceTier !== undefined) {
  1201. providerMetadata.openai.serviceTier = serviceTier
  1202. }
  1203. controller.enqueue({
  1204. type: "finish",
  1205. finishReason,
  1206. usage: {
  1207. inputTokens: {
  1208. total: usage.inputTokens,
  1209. noCache:
  1210. usage.inputTokens != null && usage.cachedInputTokens != null
  1211. ? usage.inputTokens - usage.cachedInputTokens
  1212. : undefined,
  1213. cacheRead: usage.cachedInputTokens,
  1214. cacheWrite: undefined,
  1215. },
  1216. outputTokens: {
  1217. total: usage.outputTokens,
  1218. text: undefined,
  1219. reasoning: usage.reasoningTokens,
  1220. },
  1221. raw: {
  1222. input_tokens: usage.inputTokens,
  1223. output_tokens: usage.outputTokens,
  1224. total_tokens: usage.totalTokens,
  1225. },
  1226. },
  1227. providerMetadata,
  1228. })
  1229. },
  1230. }),
  1231. ),
  1232. request: { body },
  1233. response: { headers: responseHeaders },
  1234. }
  1235. }
  1236. }
  1237. const usageSchema = z.object({
  1238. input_tokens: z.number(),
  1239. input_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
  1240. output_tokens: z.number(),
  1241. output_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish(),
  1242. })
  1243. const textDeltaChunkSchema = z.object({
  1244. type: z.literal("response.output_text.delta"),
  1245. item_id: z.string(),
  1246. delta: z.string(),
  1247. logprobs: LOGPROBS_SCHEMA.nullish(),
  1248. })
  1249. const errorChunkSchema = z.object({
  1250. type: z.literal("error"),
  1251. code: z.string(),
  1252. message: z.string(),
  1253. param: z.string().nullish(),
  1254. sequence_number: z.number(),
  1255. })
  1256. const responseFinishedChunkSchema = z.object({
  1257. type: z.enum(["response.completed", "response.incomplete"]),
  1258. response: z.object({
  1259. incomplete_details: z.object({ reason: z.string() }).nullish(),
  1260. usage: usageSchema,
  1261. service_tier: z.string().nullish(),
  1262. }),
  1263. })
  1264. const responseCreatedChunkSchema = z.object({
  1265. type: z.literal("response.created"),
  1266. response: z.object({
  1267. id: z.string(),
  1268. created_at: z.number(),
  1269. model: z.string(),
  1270. service_tier: z.string().nullish(),
  1271. }),
  1272. })
  1273. const responseOutputItemAddedSchema = z.object({
  1274. type: z.literal("response.output_item.added"),
  1275. output_index: z.number(),
  1276. item: z.discriminatedUnion("type", [
  1277. z.object({
  1278. type: z.literal("message"),
  1279. id: z.string(),
  1280. }),
  1281. z.object({
  1282. type: z.literal("reasoning"),
  1283. id: z.string(),
  1284. encrypted_content: z.string().nullish(),
  1285. }),
  1286. z.object({
  1287. type: z.literal("function_call"),
  1288. id: z.string(),
  1289. call_id: z.string(),
  1290. name: z.string(),
  1291. arguments: z.string(),
  1292. }),
  1293. z.object({
  1294. type: z.literal("web_search_call"),
  1295. id: z.string(),
  1296. status: z.string(),
  1297. action: z
  1298. .object({
  1299. type: z.literal("search"),
  1300. query: z.string().optional(),
  1301. })
  1302. .nullish(),
  1303. }),
  1304. z.object({
  1305. type: z.literal("computer_call"),
  1306. id: z.string(),
  1307. status: z.string(),
  1308. }),
  1309. z.object({
  1310. type: z.literal("file_search_call"),
  1311. id: z.string(),
  1312. }),
  1313. z.object({
  1314. type: z.literal("image_generation_call"),
  1315. id: z.string(),
  1316. }),
  1317. z.object({
  1318. type: z.literal("code_interpreter_call"),
  1319. id: z.string(),
  1320. container_id: z.string(),
  1321. code: z.string().nullable(),
  1322. outputs: z
  1323. .array(
  1324. z.discriminatedUnion("type", [
  1325. z.object({ type: z.literal("logs"), logs: z.string() }),
  1326. z.object({ type: z.literal("image"), url: z.string() }),
  1327. ]),
  1328. )
  1329. .nullable(),
  1330. status: z.string(),
  1331. }),
  1332. ]),
  1333. })
  1334. const responseOutputItemDoneSchema = z.object({
  1335. type: z.literal("response.output_item.done"),
  1336. output_index: z.number(),
  1337. item: z.discriminatedUnion("type", [
  1338. z.object({
  1339. type: z.literal("message"),
  1340. id: z.string(),
  1341. }),
  1342. z.object({
  1343. type: z.literal("reasoning"),
  1344. id: z.string(),
  1345. encrypted_content: z.string().nullish(),
  1346. }),
  1347. z.object({
  1348. type: z.literal("function_call"),
  1349. id: z.string(),
  1350. call_id: z.string(),
  1351. name: z.string(),
  1352. arguments: z.string(),
  1353. status: z.literal("completed"),
  1354. }),
  1355. codeInterpreterCallItem,
  1356. imageGenerationCallItem,
  1357. webSearchCallItem,
  1358. fileSearchCallItem,
  1359. localShellCallItem,
  1360. z.object({
  1361. type: z.literal("computer_call"),
  1362. id: z.string(),
  1363. status: z.literal("completed"),
  1364. }),
  1365. ]),
  1366. })
  1367. const responseFunctionCallArgumentsDeltaSchema = z.object({
  1368. type: z.literal("response.function_call_arguments.delta"),
  1369. item_id: z.string(),
  1370. output_index: z.number(),
  1371. delta: z.string(),
  1372. })
  1373. const responseImageGenerationCallPartialImageSchema = z.object({
  1374. type: z.literal("response.image_generation_call.partial_image"),
  1375. item_id: z.string(),
  1376. output_index: z.number(),
  1377. partial_image_b64: z.string(),
  1378. })
  1379. const responseCodeInterpreterCallCodeDeltaSchema = z.object({
  1380. type: z.literal("response.code_interpreter_call_code.delta"),
  1381. item_id: z.string(),
  1382. output_index: z.number(),
  1383. delta: z.string(),
  1384. })
  1385. const responseCodeInterpreterCallCodeDoneSchema = z.object({
  1386. type: z.literal("response.code_interpreter_call_code.done"),
  1387. item_id: z.string(),
  1388. output_index: z.number(),
  1389. code: z.string(),
  1390. })
  1391. const responseAnnotationAddedSchema = z.object({
  1392. type: z.literal("response.output_text.annotation.added"),
  1393. annotation: z.discriminatedUnion("type", [
  1394. z.object({
  1395. type: z.literal("url_citation"),
  1396. url: z.string(),
  1397. title: z.string(),
  1398. }),
  1399. z.object({
  1400. type: z.literal("file_citation"),
  1401. file_id: z.string(),
  1402. filename: z.string().nullish(),
  1403. index: z.number().nullish(),
  1404. start_index: z.number().nullish(),
  1405. end_index: z.number().nullish(),
  1406. quote: z.string().nullish(),
  1407. }),
  1408. ]),
  1409. })
  1410. const responseReasoningSummaryPartAddedSchema = z.object({
  1411. type: z.literal("response.reasoning_summary_part.added"),
  1412. item_id: z.string(),
  1413. summary_index: z.number(),
  1414. })
  1415. const responseReasoningSummaryTextDeltaSchema = z.object({
  1416. type: z.literal("response.reasoning_summary_text.delta"),
  1417. item_id: z.string(),
  1418. summary_index: z.number(),
  1419. delta: z.string(),
  1420. })
  1421. const openaiResponsesChunkSchema = z.union([
  1422. textDeltaChunkSchema,
  1423. responseFinishedChunkSchema,
  1424. responseCreatedChunkSchema,
  1425. responseOutputItemAddedSchema,
  1426. responseOutputItemDoneSchema,
  1427. responseFunctionCallArgumentsDeltaSchema,
  1428. responseImageGenerationCallPartialImageSchema,
  1429. responseCodeInterpreterCallCodeDeltaSchema,
  1430. responseCodeInterpreterCallCodeDoneSchema,
  1431. responseAnnotationAddedSchema,
  1432. responseReasoningSummaryPartAddedSchema,
  1433. responseReasoningSummaryTextDeltaSchema,
  1434. errorChunkSchema,
  1435. z.object({ type: z.string() }).loose(), // fallback for unknown chunks
  1436. ])
  1437. type ExtractByType<T, K extends T extends { type: infer U } ? U : never> = T extends { type: K } ? T : never
  1438. function isTextDeltaChunk(
  1439. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1440. ): chunk is z.infer<typeof textDeltaChunkSchema> {
  1441. return chunk.type === "response.output_text.delta"
  1442. }
  1443. function isResponseOutputItemDoneChunk(
  1444. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1445. ): chunk is z.infer<typeof responseOutputItemDoneSchema> {
  1446. return chunk.type === "response.output_item.done"
  1447. }
  1448. function isResponseOutputItemDoneReasoningChunk(chunk: z.infer<typeof openaiResponsesChunkSchema>): chunk is z.infer<
  1449. typeof responseOutputItemDoneSchema
  1450. > & {
  1451. item: ExtractByType<z.infer<typeof responseOutputItemDoneSchema>["item"], "reasoning">
  1452. } {
  1453. return isResponseOutputItemDoneChunk(chunk) && chunk.item.type === "reasoning"
  1454. }
  1455. function isResponseFinishedChunk(
  1456. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1457. ): chunk is z.infer<typeof responseFinishedChunkSchema> {
  1458. return chunk.type === "response.completed" || chunk.type === "response.incomplete"
  1459. }
  1460. function isResponseCreatedChunk(
  1461. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1462. ): chunk is z.infer<typeof responseCreatedChunkSchema> {
  1463. return chunk.type === "response.created"
  1464. }
  1465. function isResponseFunctionCallArgumentsDeltaChunk(
  1466. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1467. ): chunk is z.infer<typeof responseFunctionCallArgumentsDeltaSchema> {
  1468. return chunk.type === "response.function_call_arguments.delta"
  1469. }
  1470. function isResponseImageGenerationCallPartialImageChunk(
  1471. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1472. ): chunk is z.infer<typeof responseImageGenerationCallPartialImageSchema> {
  1473. return chunk.type === "response.image_generation_call.partial_image"
  1474. }
  1475. function isResponseCodeInterpreterCallCodeDeltaChunk(
  1476. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1477. ): chunk is z.infer<typeof responseCodeInterpreterCallCodeDeltaSchema> {
  1478. return chunk.type === "response.code_interpreter_call_code.delta"
  1479. }
  1480. function isResponseCodeInterpreterCallCodeDoneChunk(
  1481. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1482. ): chunk is z.infer<typeof responseCodeInterpreterCallCodeDoneSchema> {
  1483. return chunk.type === "response.code_interpreter_call_code.done"
  1484. }
  1485. function isResponseOutputItemAddedChunk(
  1486. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1487. ): chunk is z.infer<typeof responseOutputItemAddedSchema> {
  1488. return chunk.type === "response.output_item.added"
  1489. }
  1490. function isResponseOutputItemAddedReasoningChunk(chunk: z.infer<typeof openaiResponsesChunkSchema>): chunk is z.infer<
  1491. typeof responseOutputItemAddedSchema
  1492. > & {
  1493. item: ExtractByType<z.infer<typeof responseOutputItemAddedSchema>["item"], "reasoning">
  1494. } {
  1495. return isResponseOutputItemAddedChunk(chunk) && chunk.item.type === "reasoning"
  1496. }
  1497. function isResponseAnnotationAddedChunk(
  1498. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1499. ): chunk is z.infer<typeof responseAnnotationAddedSchema> {
  1500. return chunk.type === "response.output_text.annotation.added"
  1501. }
  1502. function isResponseReasoningSummaryPartAddedChunk(
  1503. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1504. ): chunk is z.infer<typeof responseReasoningSummaryPartAddedSchema> {
  1505. return chunk.type === "response.reasoning_summary_part.added"
  1506. }
  1507. function isResponseReasoningSummaryTextDeltaChunk(
  1508. chunk: z.infer<typeof openaiResponsesChunkSchema>,
  1509. ): chunk is z.infer<typeof responseReasoningSummaryTextDeltaSchema> {
  1510. return chunk.type === "response.reasoning_summary_text.delta"
  1511. }
  1512. function isErrorChunk(chunk: z.infer<typeof openaiResponsesChunkSchema>): chunk is z.infer<typeof errorChunkSchema> {
  1513. return chunk.type === "error"
  1514. }
  1515. type ResponsesModelConfig = {
  1516. isReasoningModel: boolean
  1517. systemMessageMode: "remove" | "system" | "developer"
  1518. requiredAutoTruncation: boolean
  1519. supportsFlexProcessing: boolean
  1520. supportsPriorityProcessing: boolean
  1521. }
  1522. function getResponsesModelConfig(modelId: string): ResponsesModelConfig {
  1523. const supportsFlexProcessing =
  1524. modelId.startsWith("o3") ||
  1525. modelId.startsWith("o4-mini") ||
  1526. (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"))
  1527. const supportsPriorityProcessing =
  1528. modelId.startsWith("gpt-4") ||
  1529. modelId.startsWith("gpt-5-mini") ||
  1530. (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat")) ||
  1531. modelId.startsWith("o3") ||
  1532. modelId.startsWith("o4-mini")
  1533. const defaults = {
  1534. requiredAutoTruncation: false,
  1535. systemMessageMode: "system" as const,
  1536. supportsFlexProcessing,
  1537. supportsPriorityProcessing,
  1538. }
  1539. // gpt-5-chat models are non-reasoning
  1540. if (modelId.startsWith("gpt-5-chat")) {
  1541. return {
  1542. ...defaults,
  1543. isReasoningModel: false,
  1544. }
  1545. }
  1546. // o series reasoning models:
  1547. if (
  1548. modelId.startsWith("o") ||
  1549. modelId.startsWith("gpt-5") ||
  1550. modelId.startsWith("codex-") ||
  1551. modelId.startsWith("computer-use")
  1552. ) {
  1553. if (modelId.startsWith("o1-mini") || modelId.startsWith("o1-preview")) {
  1554. return {
  1555. ...defaults,
  1556. isReasoningModel: true,
  1557. systemMessageMode: "remove",
  1558. }
  1559. }
  1560. return {
  1561. ...defaults,
  1562. isReasoningModel: true,
  1563. systemMessageMode: "developer",
  1564. }
  1565. }
  1566. // gpt models:
  1567. return {
  1568. ...defaults,
  1569. isReasoningModel: false,
  1570. }
  1571. }
  1572. // TODO AI SDK 6: use optional here instead of nullish
  1573. const openaiResponsesProviderOptionsSchema = z.object({
  1574. include: z
  1575. .array(z.enum(["reasoning.encrypted_content", "file_search_call.results", "message.output_text.logprobs"]))
  1576. .nullish(),
  1577. instructions: z.string().nullish(),
  1578. /**
  1579. * Return the log probabilities of the tokens.
  1580. *
  1581. * Setting to true will return the log probabilities of the tokens that
  1582. * were generated.
  1583. *
  1584. * Setting to a number will return the log probabilities of the top n
  1585. * tokens that were generated.
  1586. *
  1587. * @see https://platform.openai.com/docs/api-reference/responses/create
  1588. * @see https://cookbook.openai.com/examples/using_logprobs
  1589. */
  1590. logprobs: z.union([z.boolean(), z.number().min(1).max(TOP_LOGPROBS_MAX)]).optional(),
  1591. /**
  1592. * The maximum number of total calls to built-in tools that can be processed in a response.
  1593. * This maximum number applies across all built-in tool calls, not per individual tool.
  1594. * Any further attempts to call a tool by the model will be ignored.
  1595. */
  1596. maxToolCalls: z.number().nullish(),
  1597. metadata: z.any().nullish(),
  1598. parallelToolCalls: z.boolean().nullish(),
  1599. previousResponseId: z.string().nullish(),
  1600. promptCacheKey: z.string().nullish(),
  1601. reasoningEffort: z.string().nullish(),
  1602. reasoningSummary: z.string().nullish(),
  1603. safetyIdentifier: z.string().nullish(),
  1604. serviceTier: z.enum(["auto", "flex", "priority"]).nullish(),
  1605. store: z.boolean().nullish(),
  1606. strictJsonSchema: z.boolean().nullish(),
  1607. textVerbosity: z.enum(["low", "medium", "high"]).nullish(),
  1608. user: z.string().nullish(),
  1609. })
  1610. export type OpenAIResponsesProviderOptions = z.infer<typeof openaiResponsesProviderOptionsSchema>