@mastra/core 1.0.0-beta.11 → 1.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (394) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7549 -0
  3. package/dist/_types/@internal_ai-sdk-v4/dist/test.d.ts +65 -0
  4. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +8396 -0
  5. package/dist/_types/@internal_ai-sdk-v5/dist/test.d.ts +1708 -0
  6. package/dist/_types/@internal_external-types/dist/index.d.ts +858 -0
  7. package/dist/agent/agent-legacy.d.ts +1 -1
  8. package/dist/agent/agent.d.ts +1 -1
  9. package/dist/agent/agent.d.ts.map +1 -1
  10. package/dist/agent/agent.types.d.ts +5 -1
  11. package/dist/agent/agent.types.d.ts.map +1 -1
  12. package/dist/agent/index.cjs +9 -9
  13. package/dist/agent/index.js +2 -2
  14. package/dist/agent/message-list/index.cjs +3 -3
  15. package/dist/agent/message-list/index.d.ts +4 -3
  16. package/dist/agent/message-list/index.d.ts.map +1 -1
  17. package/dist/agent/message-list/index.js +1 -1
  18. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  19. package/dist/agent/message-list/prompt/invalid-content-error.d.ts +1 -1
  20. package/dist/agent/message-list/types.d.ts +3 -3
  21. package/dist/agent/message-list/types.d.ts.map +1 -1
  22. package/dist/agent/message-list/utils/ai-v4-v5/core-model-message.d.ts +1 -1
  23. package/dist/agent/message-list/utils/ai-v4-v5/ui-message.d.ts +1 -1
  24. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts +2 -2
  25. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts.map +1 -1
  26. package/dist/agent/message-list/utils/convert-messages.d.ts +2 -2
  27. package/dist/agent/message-list/utils/convert-messages.d.ts.map +1 -1
  28. package/dist/agent/types.d.ts +3 -3
  29. package/dist/agent/utils.d.ts +3 -3
  30. package/dist/agent/utils.d.ts.map +1 -1
  31. package/dist/agent/workflows/prepare-stream/index.d.ts +2 -1
  32. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  33. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  34. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +3 -1
  35. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  36. package/dist/bundler/types.d.ts +14 -1
  37. package/dist/bundler/types.d.ts.map +1 -1
  38. package/dist/{chunk-U3XOLEPX.js → chunk-2IU4RGU5.js} +6 -32
  39. package/dist/chunk-2IU4RGU5.js.map +1 -0
  40. package/dist/chunk-2SQB3WBT.js +4574 -0
  41. package/dist/chunk-2SQB3WBT.js.map +1 -0
  42. package/dist/{chunk-THZTRBFS.js → chunk-373OC54J.js} +8 -8
  43. package/dist/chunk-373OC54J.js.map +1 -0
  44. package/dist/{chunk-F2GAJSBI.js → chunk-4BC5FUAO.js} +8 -6
  45. package/dist/{chunk-F2GAJSBI.js.map → chunk-4BC5FUAO.js.map} +1 -1
  46. package/dist/chunk-55VPMN3N.js +250 -0
  47. package/dist/chunk-55VPMN3N.js.map +1 -0
  48. package/dist/{chunk-QM5SRDJX.js → chunk-5PTZG26U.js} +66 -84
  49. package/dist/chunk-5PTZG26U.js.map +1 -0
  50. package/dist/chunk-5VZGJTPR.js +4837 -0
  51. package/dist/chunk-5VZGJTPR.js.map +1 -0
  52. package/dist/{chunk-C36YRTZ6.js → chunk-62Q7K656.js} +6 -7
  53. package/dist/chunk-62Q7K656.js.map +1 -0
  54. package/dist/chunk-6PMMP3FR.js +7 -0
  55. package/dist/chunk-6PMMP3FR.js.map +1 -0
  56. package/dist/{chunk-DZUJEN5N.cjs → chunk-6SZKM6EC.cjs} +10 -3
  57. package/dist/{chunk-DZUJEN5N.cjs.map → chunk-6SZKM6EC.cjs.map} +1 -1
  58. package/dist/{chunk-5WRI5ZAA.js → chunk-7D4SUZUM.js} +10 -4
  59. package/dist/{chunk-5WRI5ZAA.js.map → chunk-7D4SUZUM.js.map} +1 -1
  60. package/dist/{chunk-YWMMBIOM.cjs → chunk-7HEAVZRS.cjs} +15 -15
  61. package/dist/{chunk-YWMMBIOM.cjs.map → chunk-7HEAVZRS.cjs.map} +1 -1
  62. package/dist/{chunk-BUKY6CTR.cjs → chunk-AGHLXC4I.cjs} +106 -36
  63. package/dist/chunk-AGHLXC4I.cjs.map +1 -0
  64. package/dist/{chunk-PK2A5WBG.js → chunk-ARAQIW6E.js} +222 -604
  65. package/dist/chunk-ARAQIW6E.js.map +1 -0
  66. package/dist/{chunk-US2U7ECW.js → chunk-BQDZIQ3G.js} +156 -90
  67. package/dist/chunk-BQDZIQ3G.js.map +1 -0
  68. package/dist/chunk-D22XABFZ.js +79 -0
  69. package/dist/chunk-D22XABFZ.js.map +1 -0
  70. package/dist/{chunk-2ULLRN4Y.js → chunk-E5BQRAJK.js} +943 -626
  71. package/dist/chunk-E5BQRAJK.js.map +1 -0
  72. package/dist/chunk-FST2G2FQ.cjs +84 -0
  73. package/dist/chunk-FST2G2FQ.cjs.map +1 -0
  74. package/dist/chunk-FVQTJUBD.cjs +2120 -0
  75. package/dist/chunk-FVQTJUBD.cjs.map +1 -0
  76. package/dist/chunk-G6E6V2Z4.js +2070 -0
  77. package/dist/chunk-G6E6V2Z4.js.map +1 -0
  78. package/dist/{chunk-7P6BNIJH.js → chunk-GIWC35YQ.js} +105 -35
  79. package/dist/chunk-GIWC35YQ.js.map +1 -0
  80. package/dist/{chunk-4JKEUSCC.cjs → chunk-H4VUIOWU.cjs} +22 -20
  81. package/dist/chunk-H4VUIOWU.cjs.map +1 -0
  82. package/dist/{chunk-TWH4PTDG.cjs → chunk-HWMMIRIF.cjs} +32 -27
  83. package/dist/chunk-HWMMIRIF.cjs.map +1 -0
  84. package/dist/chunk-IXZ2T2QX.cjs +448 -0
  85. package/dist/chunk-IXZ2T2QX.cjs.map +1 -0
  86. package/dist/chunk-L3NKIMF5.cjs +10 -0
  87. package/dist/chunk-L3NKIMF5.cjs.map +1 -0
  88. package/dist/chunk-L4JCRWDY.cjs +252 -0
  89. package/dist/chunk-L4JCRWDY.cjs.map +1 -0
  90. package/dist/{chunk-BJXKH4LG.cjs → chunk-LGB4VNZI.cjs} +43 -78
  91. package/dist/chunk-LGB4VNZI.cjs.map +1 -0
  92. package/dist/{chunk-PG5H6QIO.cjs → chunk-MLKE7HRS.cjs} +41 -21
  93. package/dist/chunk-MLKE7HRS.cjs.map +1 -0
  94. package/dist/{chunk-OEIVMCWX.js → chunk-MRRFTNF4.js} +2537 -84
  95. package/dist/chunk-MRRFTNF4.js.map +1 -0
  96. package/dist/chunk-MXBVP7HX.cjs +4842 -0
  97. package/dist/chunk-MXBVP7HX.cjs.map +1 -0
  98. package/dist/chunk-NESKUIRE.cjs +4586 -0
  99. package/dist/chunk-NESKUIRE.cjs.map +1 -0
  100. package/dist/{chunk-SVLMF4UZ.cjs → chunk-NIOEY3N3.cjs} +66 -85
  101. package/dist/chunk-NIOEY3N3.cjs.map +1 -0
  102. package/dist/{chunk-CZEJQSWB.cjs → chunk-OWIEOL55.cjs} +295 -677
  103. package/dist/chunk-OWIEOL55.cjs.map +1 -0
  104. package/dist/{chunk-WTSZBHIZ.cjs → chunk-PJAK4U6R.cjs} +24 -24
  105. package/dist/{chunk-WTSZBHIZ.cjs.map → chunk-PJAK4U6R.cjs.map} +1 -1
  106. package/dist/{chunk-52RSUALV.cjs → chunk-R5AJGM55.cjs} +1314 -995
  107. package/dist/chunk-R5AJGM55.cjs.map +1 -0
  108. package/dist/{chunk-IVV5TOMD.js → chunk-RCJLMMTO.js} +32 -12
  109. package/dist/chunk-RCJLMMTO.js.map +1 -0
  110. package/dist/{chunk-S73Z3PBJ.cjs → chunk-SZYSDJTN.cjs} +27 -28
  111. package/dist/chunk-SZYSDJTN.cjs.map +1 -0
  112. package/dist/{chunk-YC6PJEPH.cjs → chunk-U4CSOY6T.cjs} +188 -122
  113. package/dist/chunk-U4CSOY6T.cjs.map +1 -0
  114. package/dist/chunk-UBSPZTQX.js +434 -0
  115. package/dist/chunk-UBSPZTQX.js.map +1 -0
  116. package/dist/{chunk-SCUWP4II.cjs → chunk-VEPP75C4.cjs} +47 -74
  117. package/dist/chunk-VEPP75C4.cjs.map +1 -0
  118. package/dist/{chunk-JIGDJK2O.js → chunk-VETAQUW3.js} +4 -39
  119. package/dist/chunk-VETAQUW3.js.map +1 -0
  120. package/dist/{chunk-Z57R5WS4.js → chunk-WPTTKULS.js} +4 -4
  121. package/dist/{chunk-Z57R5WS4.js.map → chunk-WPTTKULS.js.map} +1 -1
  122. package/dist/{chunk-O2BJW7YA.js → chunk-WYGUWVTF.js} +5 -5
  123. package/dist/{chunk-O2BJW7YA.js.map → chunk-WYGUWVTF.js.map} +1 -1
  124. package/dist/{chunk-SXNQRJQD.js → chunk-WYWRMIQC.js} +127 -22
  125. package/dist/chunk-WYWRMIQC.js.map +1 -0
  126. package/dist/{chunk-5Q6WAYEY.cjs → chunk-X6IBA7FP.cjs} +137 -50
  127. package/dist/chunk-X6IBA7FP.cjs.map +1 -0
  128. package/dist/{chunk-MRFUISXC.cjs → chunk-Y7MZ5LJT.cjs} +2632 -179
  129. package/dist/chunk-Y7MZ5LJT.cjs.map +1 -0
  130. package/dist/{chunk-JJ5O45LH.js → chunk-YPLZDWG7.js} +32 -27
  131. package/dist/chunk-YPLZDWG7.js.map +1 -0
  132. package/dist/{chunk-MGCGWPQJ.cjs → chunk-Z55SJVEC.cjs} +8 -8
  133. package/dist/chunk-Z55SJVEC.cjs.map +1 -0
  134. package/dist/error/index.cjs +6 -6
  135. package/dist/error/index.d.ts +26 -20
  136. package/dist/error/index.d.ts.map +1 -1
  137. package/dist/error/index.js +1 -1
  138. package/dist/error/utils.d.ts +19 -5
  139. package/dist/error/utils.d.ts.map +1 -1
  140. package/dist/evals/index.cjs +4 -4
  141. package/dist/evals/index.js +1 -1
  142. package/dist/evals/run/index.d.ts +1 -1
  143. package/dist/evals/scoreTraces/index.cjs +8 -8
  144. package/dist/evals/scoreTraces/index.js +2 -2
  145. package/dist/evals/types.d.ts +1 -1
  146. package/dist/events/event-emitter.d.ts +6 -1
  147. package/dist/events/event-emitter.d.ts.map +1 -1
  148. package/dist/index.cjs +2 -2
  149. package/dist/index.js +1 -1
  150. package/dist/integration/index.cjs +2 -2
  151. package/dist/integration/index.js +1 -1
  152. package/dist/llm/index.cjs +15 -15
  153. package/dist/llm/index.d.ts +2 -2
  154. package/dist/llm/index.d.ts.map +1 -1
  155. package/dist/llm/index.js +5 -5
  156. package/dist/llm/model/aisdk/v5/model.d.ts +1 -1
  157. package/dist/llm/model/base.types.d.ts +2 -2
  158. package/dist/llm/model/model.d.ts +1 -1
  159. package/dist/llm/model/model.d.ts.map +1 -1
  160. package/dist/llm/model/model.loop.d.ts +2 -2
  161. package/dist/llm/model/model.loop.d.ts.map +1 -1
  162. package/dist/llm/model/model.loop.types.d.ts +1 -1
  163. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  164. package/dist/llm/model/provider-types.generated.d.ts +51 -11
  165. package/dist/llm/model/shared.types.d.ts +1 -1
  166. package/dist/loop/index.cjs +2 -2
  167. package/dist/loop/index.js +1 -1
  168. package/dist/loop/loop.d.ts +2 -2
  169. package/dist/loop/loop.d.ts.map +1 -1
  170. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts +1 -1
  171. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts.map +1 -1
  172. package/dist/loop/test-utils/options.d.ts.map +1 -1
  173. package/dist/loop/test-utils/streamObject.d.ts +1 -1
  174. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  175. package/dist/loop/test-utils/tools.d.ts.map +1 -1
  176. package/dist/loop/types.d.ts +3 -1
  177. package/dist/loop/types.d.ts.map +1 -1
  178. package/dist/loop/workflows/agentic-execution/index.d.ts +13 -13
  179. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  180. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +10 -10
  181. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  182. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +5 -5
  183. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  184. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +22 -21
  185. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  186. package/dist/loop/workflows/agentic-loop/index.d.ts +13 -13
  187. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  188. package/dist/loop/workflows/schema.d.ts +6 -6
  189. package/dist/loop/workflows/schema.d.ts.map +1 -1
  190. package/dist/loop/workflows/stream.d.ts +2 -2
  191. package/dist/loop/workflows/stream.d.ts.map +1 -1
  192. package/dist/mastra/index.cjs +2 -2
  193. package/dist/mastra/index.js +1 -1
  194. package/dist/mcp/index.cjs +4 -4
  195. package/dist/mcp/index.js +1 -1
  196. package/dist/memory/index.cjs +6 -6
  197. package/dist/memory/index.js +1 -1
  198. package/dist/memory/memory.d.ts +1 -1
  199. package/dist/memory/types.d.ts +3 -3
  200. package/dist/memory/types.d.ts.map +1 -1
  201. package/dist/models-dev-D3EKFGAO.cjs +12 -0
  202. package/dist/{models-dev-EO3SUIY2.cjs.map → models-dev-D3EKFGAO.cjs.map} +1 -1
  203. package/dist/models-dev-EO22XOXQ.js +3 -0
  204. package/dist/{models-dev-23RN2WHG.js.map → models-dev-EO22XOXQ.js.map} +1 -1
  205. package/dist/netlify-AE4LNCAI.js +3 -0
  206. package/dist/{netlify-GXJ5D5DD.js.map → netlify-AE4LNCAI.js.map} +1 -1
  207. package/dist/netlify-WE42TZIT.cjs +12 -0
  208. package/dist/{netlify-KJLY3GFS.cjs.map → netlify-WE42TZIT.cjs.map} +1 -1
  209. package/dist/processors/index.cjs +37 -37
  210. package/dist/processors/index.d.ts +2 -2
  211. package/dist/processors/index.d.ts.map +1 -1
  212. package/dist/processors/index.js +1 -1
  213. package/dist/processors/step-schema.d.ts +1267 -1267
  214. package/dist/processors/step-schema.d.ts.map +1 -1
  215. package/dist/provider-registry-6LF3NGC5.js +3 -0
  216. package/dist/{provider-registry-F67Y6OF2.js.map → provider-registry-6LF3NGC5.js.map} +1 -1
  217. package/dist/provider-registry-73FKMXJV.cjs +40 -0
  218. package/dist/{provider-registry-3TG2KUD2.cjs.map → provider-registry-73FKMXJV.cjs.map} +1 -1
  219. package/dist/provider-registry.json +100 -30
  220. package/dist/{registry-generator-UMTNPBJX.js → registry-generator-AVQXI3GX.js} +2 -2
  221. package/dist/{registry-generator-UMTNPBJX.js.map → registry-generator-AVQXI3GX.js.map} +1 -1
  222. package/dist/{registry-generator-34SC4TAU.cjs → registry-generator-KOFNIIWJ.cjs} +2 -2
  223. package/dist/{registry-generator-34SC4TAU.cjs.map → registry-generator-KOFNIIWJ.cjs.map} +1 -1
  224. package/dist/relevance/index.cjs +2 -2
  225. package/dist/relevance/index.js +1 -1
  226. package/dist/server/index.cjs +5 -5
  227. package/dist/server/index.js +1 -1
  228. package/dist/storage/base.d.ts +2 -10
  229. package/dist/storage/base.d.ts.map +1 -1
  230. package/dist/storage/domains/workflows/base.d.ts +2 -8
  231. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  232. package/dist/storage/domains/workflows/inmemory.d.ts +2 -8
  233. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  234. package/dist/storage/index.cjs +38 -38
  235. package/dist/storage/index.js +1 -1
  236. package/dist/storage/mock.d.ts +2 -8
  237. package/dist/storage/mock.d.ts.map +1 -1
  238. package/dist/storage/types.d.ts +9 -1
  239. package/dist/storage/types.d.ts.map +1 -1
  240. package/dist/stream/RunOutput.d.ts +1 -1
  241. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  242. package/dist/stream/aisdk/v5/compat/content.d.ts +1 -1
  243. package/dist/stream/aisdk/v5/compat/content.d.ts.map +1 -1
  244. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +1 -1
  245. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  246. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  247. package/dist/stream/aisdk/v5/compat/ui-message.d.ts.map +1 -1
  248. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  249. package/dist/stream/aisdk/v5/compat/validation.d.ts.map +1 -1
  250. package/dist/stream/aisdk/v5/execute.d.ts +2 -2
  251. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  252. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  253. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  254. package/dist/stream/aisdk/v5/output-helpers.d.ts +12 -27
  255. package/dist/stream/aisdk/v5/output-helpers.d.ts.map +1 -1
  256. package/dist/stream/aisdk/v5/output.d.ts +41 -91
  257. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  258. package/dist/stream/aisdk/v5/transform.d.ts +1 -1
  259. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  260. package/dist/stream/base/input.d.ts +1 -1
  261. package/dist/stream/base/output.d.ts +9 -31
  262. package/dist/stream/base/output.d.ts.map +1 -1
  263. package/dist/stream/base/schema.d.ts +2 -2
  264. package/dist/stream/base/schema.d.ts.map +1 -1
  265. package/dist/stream/index.cjs +12 -12
  266. package/dist/stream/index.js +2 -2
  267. package/dist/stream/types.d.ts +3 -2
  268. package/dist/stream/types.d.ts.map +1 -1
  269. package/dist/test-utils/llm-mock.cjs +14587 -14
  270. package/dist/test-utils/llm-mock.cjs.map +1 -1
  271. package/dist/test-utils/llm-mock.d.ts +3 -3
  272. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  273. package/dist/test-utils/llm-mock.js +14577 -4
  274. package/dist/test-utils/llm-mock.js.map +1 -1
  275. package/dist/token-6GSAFR2W-SGVIXFCP.cjs +63 -0
  276. package/dist/token-6GSAFR2W-SGVIXFCP.cjs.map +1 -0
  277. package/dist/token-6GSAFR2W-SPYPLMBM.js +61 -0
  278. package/dist/token-6GSAFR2W-SPYPLMBM.js.map +1 -0
  279. package/dist/token-util-NEHG7TUY-7GMW5FXI.cjs +10 -0
  280. package/dist/token-util-NEHG7TUY-7GMW5FXI.cjs.map +1 -0
  281. package/dist/token-util-NEHG7TUY-JRJTGTAB.js +8 -0
  282. package/dist/token-util-NEHG7TUY-JRJTGTAB.js.map +1 -0
  283. package/dist/tools/index.cjs +4 -4
  284. package/dist/tools/index.js +1 -1
  285. package/dist/tools/is-vercel-tool.cjs +2 -2
  286. package/dist/tools/is-vercel-tool.js +1 -1
  287. package/dist/tools/tool-builder/builder.d.ts +2 -1
  288. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  289. package/dist/tools/tool.d.ts.map +1 -1
  290. package/dist/tools/types.d.ts +5 -5
  291. package/dist/tools/types.d.ts.map +1 -1
  292. package/dist/utils.cjs +22 -22
  293. package/dist/utils.d.ts +3 -3
  294. package/dist/utils.d.ts.map +1 -1
  295. package/dist/utils.js +1 -1
  296. package/dist/vector/embed.d.ts +2 -2
  297. package/dist/vector/embed.d.ts.map +1 -1
  298. package/dist/vector/index.cjs +11 -11
  299. package/dist/vector/index.js +3 -3
  300. package/dist/vector/vector.d.ts +1 -1
  301. package/dist/voice/aisdk/speech.d.ts +1 -1
  302. package/dist/voice/aisdk/speech.d.ts.map +1 -1
  303. package/dist/voice/aisdk/transcription.d.ts +1 -1
  304. package/dist/voice/aisdk/transcription.d.ts.map +1 -1
  305. package/dist/voice/composite-voice.d.ts +1 -1
  306. package/dist/voice/composite-voice.d.ts.map +1 -1
  307. package/dist/voice/index.cjs +6 -6
  308. package/dist/voice/index.js +1 -1
  309. package/dist/workflows/constants.cjs +4 -4
  310. package/dist/workflows/constants.d.ts +1 -1
  311. package/dist/workflows/constants.d.ts.map +1 -1
  312. package/dist/workflows/constants.js +1 -1
  313. package/dist/workflows/default.d.ts +9 -16
  314. package/dist/workflows/default.d.ts.map +1 -1
  315. package/dist/workflows/evented/execution-engine.d.ts +3 -2
  316. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  317. package/dist/workflows/evented/index.cjs +10 -10
  318. package/dist/workflows/evented/index.js +1 -1
  319. package/dist/workflows/evented/step-executor.d.ts +1 -1
  320. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  321. package/dist/workflows/evented/workflow-event-processor/index.d.ts +1 -1
  322. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  323. package/dist/workflows/evented/workflow.d.ts +15 -0
  324. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  325. package/dist/workflows/execution-engine.d.ts +25 -2
  326. package/dist/workflows/execution-engine.d.ts.map +1 -1
  327. package/dist/workflows/handlers/control-flow.d.ts +6 -5
  328. package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
  329. package/dist/workflows/handlers/entry.d.ts +5 -3
  330. package/dist/workflows/handlers/entry.d.ts.map +1 -1
  331. package/dist/workflows/handlers/sleep.d.ts +4 -3
  332. package/dist/workflows/handlers/sleep.d.ts.map +1 -1
  333. package/dist/workflows/handlers/step.d.ts +5 -3
  334. package/dist/workflows/handlers/step.d.ts.map +1 -1
  335. package/dist/workflows/index.cjs +26 -22
  336. package/dist/workflows/index.js +1 -1
  337. package/dist/workflows/step.d.ts +5 -4
  338. package/dist/workflows/step.d.ts.map +1 -1
  339. package/dist/workflows/types.d.ts +66 -14
  340. package/dist/workflows/types.d.ts.map +1 -1
  341. package/dist/workflows/utils.d.ts +11 -0
  342. package/dist/workflows/utils.d.ts.map +1 -1
  343. package/dist/workflows/workflow.d.ts +26 -8
  344. package/dist/workflows/workflow.d.ts.map +1 -1
  345. package/package.json +12 -11
  346. package/src/llm/model/provider-types.generated.d.ts +51 -11
  347. package/dist/agent/__tests__/mock-model.d.ts +0 -8
  348. package/dist/agent/__tests__/mock-model.d.ts.map +0 -1
  349. package/dist/agent/agent-types.test-d.d.ts +0 -2
  350. package/dist/agent/agent-types.test-d.d.ts.map +0 -1
  351. package/dist/ai-sdk.types.d.ts +0 -4705
  352. package/dist/chunk-2ULLRN4Y.js.map +0 -1
  353. package/dist/chunk-3E3ILV6T.cjs +0 -518
  354. package/dist/chunk-3E3ILV6T.cjs.map +0 -1
  355. package/dist/chunk-4JKEUSCC.cjs.map +0 -1
  356. package/dist/chunk-52RSUALV.cjs.map +0 -1
  357. package/dist/chunk-5PAEYE3Q.js +0 -513
  358. package/dist/chunk-5PAEYE3Q.js.map +0 -1
  359. package/dist/chunk-5Q6WAYEY.cjs.map +0 -1
  360. package/dist/chunk-7P6BNIJH.js.map +0 -1
  361. package/dist/chunk-ABJOUEVA.cjs +0 -10
  362. package/dist/chunk-ABJOUEVA.cjs.map +0 -1
  363. package/dist/chunk-BJXKH4LG.cjs.map +0 -1
  364. package/dist/chunk-BUKY6CTR.cjs.map +0 -1
  365. package/dist/chunk-C36YRTZ6.js.map +0 -1
  366. package/dist/chunk-CZEJQSWB.cjs.map +0 -1
  367. package/dist/chunk-IVV5TOMD.js.map +0 -1
  368. package/dist/chunk-JIGDJK2O.js.map +0 -1
  369. package/dist/chunk-JJ5O45LH.js.map +0 -1
  370. package/dist/chunk-MGCGWPQJ.cjs.map +0 -1
  371. package/dist/chunk-MRFUISXC.cjs.map +0 -1
  372. package/dist/chunk-NLNKQD2T.js +0 -7
  373. package/dist/chunk-NLNKQD2T.js.map +0 -1
  374. package/dist/chunk-OEIVMCWX.js.map +0 -1
  375. package/dist/chunk-PG5H6QIO.cjs.map +0 -1
  376. package/dist/chunk-PK2A5WBG.js.map +0 -1
  377. package/dist/chunk-QM5SRDJX.js.map +0 -1
  378. package/dist/chunk-S73Z3PBJ.cjs.map +0 -1
  379. package/dist/chunk-SCUWP4II.cjs.map +0 -1
  380. package/dist/chunk-SVLMF4UZ.cjs.map +0 -1
  381. package/dist/chunk-SXNQRJQD.js.map +0 -1
  382. package/dist/chunk-THZTRBFS.js.map +0 -1
  383. package/dist/chunk-TWH4PTDG.cjs.map +0 -1
  384. package/dist/chunk-U3XOLEPX.js.map +0 -1
  385. package/dist/chunk-US2U7ECW.js.map +0 -1
  386. package/dist/chunk-YC6PJEPH.cjs.map +0 -1
  387. package/dist/models-dev-23RN2WHG.js +0 -3
  388. package/dist/models-dev-EO3SUIY2.cjs +0 -12
  389. package/dist/netlify-GXJ5D5DD.js +0 -3
  390. package/dist/netlify-KJLY3GFS.cjs +0 -12
  391. package/dist/provider-registry-3TG2KUD2.cjs +0 -40
  392. package/dist/provider-registry-F67Y6OF2.js +0 -3
  393. package/dist/tools/tool-stream-types.test-d.d.ts +0 -2
  394. package/dist/tools/tool-stream-types.test-d.d.ts.map +0 -1
@@ -0,0 +1,4837 @@
1
+ import { ModelsDevGateway, parseModelRouterId } from './chunk-MRRFTNF4.js';
2
+ import { NetlifyGateway } from './chunk-WPTTKULS.js';
3
+ import { createJsonErrorResponseHandler, lazyValidator, zodSchema, lazySchema, createProviderDefinedToolFactoryWithOutputSchema, MastraModelGateway, createOpenAICompatible, createOpenAI, createGoogleGenerativeAI, parseProviderOptions, postJsonToApi, createJsonResponseHandler, combineHeaders, generateId, createEventSourceResponseHandler, isParsableJson, loadApiKey, withUserAgentSuffix, loadSetting, convertToBase64, convertBase64ToUint8Array, mediaTypeToExtension, postFormDataToApi, createBinaryResponseHandler, validateTypes } from './chunk-ARAQIW6E.js';
4
+ import { PROVIDER_REGISTRY, GatewayRegistry } from './chunk-GIWC35YQ.js';
5
+ import { InvalidResponseDataError, UnsupportedFunctionalityError, TooManyEmbeddingValuesForCallError, APICallError, InvalidPromptError } from './chunk-UBSPZTQX.js';
6
+ import { AISDKV5LanguageModel } from './chunk-62Q7K656.js';
7
+ import { RequestContext } from './chunk-6TBWJV35.js';
8
+ import { MastraError } from './chunk-YPLZDWG7.js';
9
+ import { InMemoryServerCache } from './chunk-3CKZSDTQ.js';
10
+ import { createHash } from 'crypto';
11
+ import { z } from 'zod/v4';
12
+
13
+ var openaiErrorDataSchema = z.object({
14
+ error: z.object({
15
+ message: z.string(),
16
+ // The additional information below is handled loosely to support
17
+ // OpenAI-compatible providers that have slightly different error
18
+ // responses:
19
+ type: z.string().nullish(),
20
+ param: z.any().nullish(),
21
+ code: z.union([z.string(), z.number()]).nullish()
22
+ })
23
+ });
24
+ var openaiFailedResponseHandler = createJsonErrorResponseHandler({
25
+ errorSchema: openaiErrorDataSchema,
26
+ errorToMessage: (data) => data.error.message
27
+ });
28
+ function convertToOpenAIChatMessages({
29
+ prompt,
30
+ systemMessageMode = "system"
31
+ }) {
32
+ const messages = [];
33
+ const warnings = [];
34
+ for (const { role, content } of prompt) {
35
+ switch (role) {
36
+ case "system": {
37
+ switch (systemMessageMode) {
38
+ case "system": {
39
+ messages.push({ role: "system", content });
40
+ break;
41
+ }
42
+ case "developer": {
43
+ messages.push({ role: "developer", content });
44
+ break;
45
+ }
46
+ case "remove": {
47
+ warnings.push({
48
+ type: "other",
49
+ message: "system messages are removed for this model"
50
+ });
51
+ break;
52
+ }
53
+ default: {
54
+ const _exhaustiveCheck = systemMessageMode;
55
+ throw new Error(
56
+ `Unsupported system message mode: ${_exhaustiveCheck}`
57
+ );
58
+ }
59
+ }
60
+ break;
61
+ }
62
+ case "user": {
63
+ if (content.length === 1 && content[0].type === "text") {
64
+ messages.push({ role: "user", content: content[0].text });
65
+ break;
66
+ }
67
+ messages.push({
68
+ role: "user",
69
+ content: content.map((part, index) => {
70
+ var _a, _b, _c;
71
+ switch (part.type) {
72
+ case "text": {
73
+ return { type: "text", text: part.text };
74
+ }
75
+ case "file": {
76
+ if (part.mediaType.startsWith("image/")) {
77
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
78
+ return {
79
+ type: "image_url",
80
+ image_url: {
81
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`,
82
+ // OpenAI specific extension: image detail
83
+ detail: (_b = (_a = part.providerOptions) == null ? void 0 : _a.openai) == null ? void 0 : _b.imageDetail
84
+ }
85
+ };
86
+ } else if (part.mediaType.startsWith("audio/")) {
87
+ if (part.data instanceof URL) {
88
+ throw new UnsupportedFunctionalityError({
89
+ functionality: "audio file parts with URLs"
90
+ });
91
+ }
92
+ switch (part.mediaType) {
93
+ case "audio/wav": {
94
+ return {
95
+ type: "input_audio",
96
+ input_audio: {
97
+ data: convertToBase64(part.data),
98
+ format: "wav"
99
+ }
100
+ };
101
+ }
102
+ case "audio/mp3":
103
+ case "audio/mpeg": {
104
+ return {
105
+ type: "input_audio",
106
+ input_audio: {
107
+ data: convertToBase64(part.data),
108
+ format: "mp3"
109
+ }
110
+ };
111
+ }
112
+ default: {
113
+ throw new UnsupportedFunctionalityError({
114
+ functionality: `audio content parts with media type ${part.mediaType}`
115
+ });
116
+ }
117
+ }
118
+ } else if (part.mediaType === "application/pdf") {
119
+ if (part.data instanceof URL) {
120
+ throw new UnsupportedFunctionalityError({
121
+ functionality: "PDF file parts with URLs"
122
+ });
123
+ }
124
+ return {
125
+ type: "file",
126
+ file: typeof part.data === "string" && part.data.startsWith("file-") ? { file_id: part.data } : {
127
+ filename: (_c = part.filename) != null ? _c : `part-${index}.pdf`,
128
+ file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`
129
+ }
130
+ };
131
+ } else {
132
+ throw new UnsupportedFunctionalityError({
133
+ functionality: `file part media type ${part.mediaType}`
134
+ });
135
+ }
136
+ }
137
+ }
138
+ })
139
+ });
140
+ break;
141
+ }
142
+ case "assistant": {
143
+ let text = "";
144
+ const toolCalls = [];
145
+ for (const part of content) {
146
+ switch (part.type) {
147
+ case "text": {
148
+ text += part.text;
149
+ break;
150
+ }
151
+ case "tool-call": {
152
+ toolCalls.push({
153
+ id: part.toolCallId,
154
+ type: "function",
155
+ function: {
156
+ name: part.toolName,
157
+ arguments: JSON.stringify(part.input)
158
+ }
159
+ });
160
+ break;
161
+ }
162
+ }
163
+ }
164
+ messages.push({
165
+ role: "assistant",
166
+ content: text,
167
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
168
+ });
169
+ break;
170
+ }
171
+ case "tool": {
172
+ for (const toolResponse of content) {
173
+ const output = toolResponse.output;
174
+ let contentValue;
175
+ switch (output.type) {
176
+ case "text":
177
+ case "error-text":
178
+ contentValue = output.value;
179
+ break;
180
+ case "content":
181
+ case "json":
182
+ case "error-json":
183
+ contentValue = JSON.stringify(output.value);
184
+ break;
185
+ }
186
+ messages.push({
187
+ role: "tool",
188
+ tool_call_id: toolResponse.toolCallId,
189
+ content: contentValue
190
+ });
191
+ }
192
+ break;
193
+ }
194
+ default: {
195
+ const _exhaustiveCheck = role;
196
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
197
+ }
198
+ }
199
+ }
200
+ return { messages, warnings };
201
+ }
202
+ function getResponseMetadata({
203
+ id,
204
+ model,
205
+ created
206
+ }) {
207
+ return {
208
+ id: id != null ? id : void 0,
209
+ modelId: model != null ? model : void 0,
210
+ timestamp: created ? new Date(created * 1e3) : void 0
211
+ };
212
+ }
213
+ function mapOpenAIFinishReason(finishReason) {
214
+ switch (finishReason) {
215
+ case "stop":
216
+ return "stop";
217
+ case "length":
218
+ return "length";
219
+ case "content_filter":
220
+ return "content-filter";
221
+ case "function_call":
222
+ case "tool_calls":
223
+ return "tool-calls";
224
+ default:
225
+ return "unknown";
226
+ }
227
+ }
228
+ var openaiChatResponseSchema = lazyValidator(
229
+ () => zodSchema(
230
+ z.object({
231
+ id: z.string().nullish(),
232
+ created: z.number().nullish(),
233
+ model: z.string().nullish(),
234
+ choices: z.array(
235
+ z.object({
236
+ message: z.object({
237
+ role: z.literal("assistant").nullish(),
238
+ content: z.string().nullish(),
239
+ tool_calls: z.array(
240
+ z.object({
241
+ id: z.string().nullish(),
242
+ type: z.literal("function"),
243
+ function: z.object({
244
+ name: z.string(),
245
+ arguments: z.string()
246
+ })
247
+ })
248
+ ).nullish(),
249
+ annotations: z.array(
250
+ z.object({
251
+ type: z.literal("url_citation"),
252
+ start_index: z.number(),
253
+ end_index: z.number(),
254
+ url: z.string(),
255
+ title: z.string()
256
+ })
257
+ ).nullish()
258
+ }),
259
+ index: z.number(),
260
+ logprobs: z.object({
261
+ content: z.array(
262
+ z.object({
263
+ token: z.string(),
264
+ logprob: z.number(),
265
+ top_logprobs: z.array(
266
+ z.object({
267
+ token: z.string(),
268
+ logprob: z.number()
269
+ })
270
+ )
271
+ })
272
+ ).nullish()
273
+ }).nullish(),
274
+ finish_reason: z.string().nullish()
275
+ })
276
+ ),
277
+ usage: z.object({
278
+ prompt_tokens: z.number().nullish(),
279
+ completion_tokens: z.number().nullish(),
280
+ total_tokens: z.number().nullish(),
281
+ prompt_tokens_details: z.object({
282
+ cached_tokens: z.number().nullish()
283
+ }).nullish(),
284
+ completion_tokens_details: z.object({
285
+ reasoning_tokens: z.number().nullish(),
286
+ accepted_prediction_tokens: z.number().nullish(),
287
+ rejected_prediction_tokens: z.number().nullish()
288
+ }).nullish()
289
+ }).nullish()
290
+ })
291
+ )
292
+ );
293
+ var openaiChatChunkSchema = lazyValidator(
294
+ () => zodSchema(
295
+ z.union([
296
+ z.object({
297
+ id: z.string().nullish(),
298
+ created: z.number().nullish(),
299
+ model: z.string().nullish(),
300
+ choices: z.array(
301
+ z.object({
302
+ delta: z.object({
303
+ role: z.enum(["assistant"]).nullish(),
304
+ content: z.string().nullish(),
305
+ tool_calls: z.array(
306
+ z.object({
307
+ index: z.number(),
308
+ id: z.string().nullish(),
309
+ type: z.literal("function").nullish(),
310
+ function: z.object({
311
+ name: z.string().nullish(),
312
+ arguments: z.string().nullish()
313
+ })
314
+ })
315
+ ).nullish(),
316
+ annotations: z.array(
317
+ z.object({
318
+ type: z.literal("url_citation"),
319
+ start_index: z.number(),
320
+ end_index: z.number(),
321
+ url: z.string(),
322
+ title: z.string()
323
+ })
324
+ ).nullish()
325
+ }).nullish(),
326
+ logprobs: z.object({
327
+ content: z.array(
328
+ z.object({
329
+ token: z.string(),
330
+ logprob: z.number(),
331
+ top_logprobs: z.array(
332
+ z.object({
333
+ token: z.string(),
334
+ logprob: z.number()
335
+ })
336
+ )
337
+ })
338
+ ).nullish()
339
+ }).nullish(),
340
+ finish_reason: z.string().nullish(),
341
+ index: z.number()
342
+ })
343
+ ),
344
+ usage: z.object({
345
+ prompt_tokens: z.number().nullish(),
346
+ completion_tokens: z.number().nullish(),
347
+ total_tokens: z.number().nullish(),
348
+ prompt_tokens_details: z.object({
349
+ cached_tokens: z.number().nullish()
350
+ }).nullish(),
351
+ completion_tokens_details: z.object({
352
+ reasoning_tokens: z.number().nullish(),
353
+ accepted_prediction_tokens: z.number().nullish(),
354
+ rejected_prediction_tokens: z.number().nullish()
355
+ }).nullish()
356
+ }).nullish()
357
+ }),
358
+ openaiErrorDataSchema
359
+ ])
360
+ )
361
+ );
362
+ var openaiChatLanguageModelOptions = lazyValidator(
363
+ () => zodSchema(
364
+ z.object({
365
+ /**
366
+ * Modify the likelihood of specified tokens appearing in the completion.
367
+ *
368
+ * Accepts a JSON object that maps tokens (specified by their token ID in
369
+ * the GPT tokenizer) to an associated bias value from -100 to 100.
370
+ */
371
+ logitBias: z.record(z.coerce.number(), z.number()).optional(),
372
+ /**
373
+ * Return the log probabilities of the tokens.
374
+ *
375
+ * Setting to true will return the log probabilities of the tokens that
376
+ * were generated.
377
+ *
378
+ * Setting to a number will return the log probabilities of the top n
379
+ * tokens that were generated.
380
+ */
381
+ logprobs: z.union([z.boolean(), z.number()]).optional(),
382
+ /**
383
+ * Whether to enable parallel function calling during tool use. Default to true.
384
+ */
385
+ parallelToolCalls: z.boolean().optional(),
386
+ /**
387
+ * A unique identifier representing your end-user, which can help OpenAI to
388
+ * monitor and detect abuse.
389
+ */
390
+ user: z.string().optional(),
391
+ /**
392
+ * Reasoning effort for reasoning models. Defaults to `medium`.
393
+ */
394
+ reasoningEffort: z.enum(["none", "minimal", "low", "medium", "high"]).optional(),
395
+ /**
396
+ * Maximum number of completion tokens to generate. Useful for reasoning models.
397
+ */
398
+ maxCompletionTokens: z.number().optional(),
399
+ /**
400
+ * Whether to enable persistence in responses API.
401
+ */
402
+ store: z.boolean().optional(),
403
+ /**
404
+ * Metadata to associate with the request.
405
+ */
406
+ metadata: z.record(z.string().max(64), z.string().max(512)).optional(),
407
+ /**
408
+ * Parameters for prediction mode.
409
+ */
410
+ prediction: z.record(z.string(), z.any()).optional(),
411
+ /**
412
+ * Whether to use structured outputs.
413
+ *
414
+ * @default true
415
+ */
416
+ structuredOutputs: z.boolean().optional(),
417
+ /**
418
+ * Service tier for the request.
419
+ * - 'auto': Default service tier. The request will be processed with the service tier configured in the
420
+ * Project settings. Unless otherwise configured, the Project will use 'default'.
421
+ * - 'flex': 50% cheaper processing at the cost of increased latency. Only available for o3 and o4-mini models.
422
+ * - 'priority': Higher-speed processing with predictably low latency at premium cost. Available for Enterprise customers.
423
+ * - 'default': The request will be processed with the standard pricing and performance for the selected model.
424
+ *
425
+ * @default 'auto'
426
+ */
427
+ serviceTier: z.enum(["auto", "flex", "priority", "default"]).optional(),
428
+ /**
429
+ * Whether to use strict JSON schema validation.
430
+ *
431
+ * @default false
432
+ */
433
+ strictJsonSchema: z.boolean().optional(),
434
+ /**
435
+ * Controls the verbosity of the model's responses.
436
+ * Lower values will result in more concise responses, while higher values will result in more verbose responses.
437
+ */
438
+ textVerbosity: z.enum(["low", "medium", "high"]).optional(),
439
+ /**
440
+ * A cache key for prompt caching. Allows manual control over prompt caching behavior.
441
+ * Useful for improving cache hit rates and working around automatic caching issues.
442
+ */
443
+ promptCacheKey: z.string().optional(),
444
+ /**
445
+ * The retention policy for the prompt cache.
446
+ * - 'in_memory': Default. Standard prompt caching behavior.
447
+ * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours.
448
+ * Currently only available for 5.1 series models.
449
+ *
450
+ * @default 'in_memory'
451
+ */
452
+ promptCacheRetention: z.enum(["in_memory", "24h"]).optional(),
453
+ /**
454
+ * A stable identifier used to help detect users of your application
455
+ * that may be violating OpenAI's usage policies. The IDs should be a
456
+ * string that uniquely identifies each user. We recommend hashing their
457
+ * username or email address, in order to avoid sending us any identifying
458
+ * information.
459
+ */
460
+ safetyIdentifier: z.string().optional()
461
+ })
462
+ )
463
+ );
464
+ function prepareChatTools({
465
+ tools,
466
+ toolChoice,
467
+ structuredOutputs,
468
+ strictJsonSchema
469
+ }) {
470
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
471
+ const toolWarnings = [];
472
+ if (tools == null) {
473
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
474
+ }
475
+ const openaiTools = [];
476
+ for (const tool of tools) {
477
+ switch (tool.type) {
478
+ case "function":
479
+ openaiTools.push({
480
+ type: "function",
481
+ function: {
482
+ name: tool.name,
483
+ description: tool.description,
484
+ parameters: tool.inputSchema,
485
+ strict: structuredOutputs ? strictJsonSchema : void 0
486
+ }
487
+ });
488
+ break;
489
+ default:
490
+ toolWarnings.push({ type: "unsupported-tool", tool });
491
+ break;
492
+ }
493
+ }
494
+ if (toolChoice == null) {
495
+ return { tools: openaiTools, toolChoice: void 0, toolWarnings };
496
+ }
497
+ const type = toolChoice.type;
498
+ switch (type) {
499
+ case "auto":
500
+ case "none":
501
+ case "required":
502
+ return { tools: openaiTools, toolChoice: type, toolWarnings };
503
+ case "tool":
504
+ return {
505
+ tools: openaiTools,
506
+ toolChoice: {
507
+ type: "function",
508
+ function: {
509
+ name: toolChoice.toolName
510
+ }
511
+ },
512
+ toolWarnings
513
+ };
514
+ default: {
515
+ const _exhaustiveCheck = type;
516
+ throw new UnsupportedFunctionalityError({
517
+ functionality: `tool choice type: ${_exhaustiveCheck}`
518
+ });
519
+ }
520
+ }
521
+ }
522
+ var OpenAIChatLanguageModel = class {
523
+ constructor(modelId, config) {
524
+ this.specificationVersion = "v2";
525
+ this.supportedUrls = {
526
+ "image/*": [/^https?:\/\/.*$/]
527
+ };
528
+ this.modelId = modelId;
529
+ this.config = config;
530
+ }
531
+ get provider() {
532
+ return this.config.provider;
533
+ }
534
+ async getArgs({
535
+ prompt,
536
+ maxOutputTokens,
537
+ temperature,
538
+ topP,
539
+ topK,
540
+ frequencyPenalty,
541
+ presencePenalty,
542
+ stopSequences,
543
+ responseFormat,
544
+ seed,
545
+ tools,
546
+ toolChoice,
547
+ providerOptions
548
+ }) {
549
+ var _a, _b, _c, _d;
550
+ const warnings = [];
551
+ const openaiOptions = (_a = await parseProviderOptions({
552
+ provider: "openai",
553
+ providerOptions,
554
+ schema: openaiChatLanguageModelOptions
555
+ })) != null ? _a : {};
556
+ const structuredOutputs = (_b = openaiOptions.structuredOutputs) != null ? _b : true;
557
+ if (topK != null) {
558
+ warnings.push({
559
+ type: "unsupported-setting",
560
+ setting: "topK"
561
+ });
562
+ }
563
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !structuredOutputs) {
564
+ warnings.push({
565
+ type: "unsupported-setting",
566
+ setting: "responseFormat",
567
+ details: "JSON response format schema is only supported with structuredOutputs"
568
+ });
569
+ }
570
+ const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages(
571
+ {
572
+ prompt,
573
+ systemMessageMode: getSystemMessageMode(this.modelId)
574
+ }
575
+ );
576
+ warnings.push(...messageWarnings);
577
+ const strictJsonSchema = (_c = openaiOptions.strictJsonSchema) != null ? _c : false;
578
+ const baseArgs = {
579
+ // model id:
580
+ model: this.modelId,
581
+ // model specific settings:
582
+ logit_bias: openaiOptions.logitBias,
583
+ logprobs: openaiOptions.logprobs === true || typeof openaiOptions.logprobs === "number" ? true : void 0,
584
+ top_logprobs: typeof openaiOptions.logprobs === "number" ? openaiOptions.logprobs : typeof openaiOptions.logprobs === "boolean" ? openaiOptions.logprobs ? 0 : void 0 : void 0,
585
+ user: openaiOptions.user,
586
+ parallel_tool_calls: openaiOptions.parallelToolCalls,
587
+ // standardized settings:
588
+ max_tokens: maxOutputTokens,
589
+ temperature,
590
+ top_p: topP,
591
+ frequency_penalty: frequencyPenalty,
592
+ presence_penalty: presencePenalty,
593
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && responseFormat.schema != null ? {
594
+ type: "json_schema",
595
+ json_schema: {
596
+ schema: responseFormat.schema,
597
+ strict: strictJsonSchema,
598
+ name: (_d = responseFormat.name) != null ? _d : "response",
599
+ description: responseFormat.description
600
+ }
601
+ } : { type: "json_object" } : void 0,
602
+ stop: stopSequences,
603
+ seed,
604
+ verbosity: openaiOptions.textVerbosity,
605
+ // openai specific settings:
606
+ // TODO AI SDK 6: remove, we auto-map maxOutputTokens now
607
+ max_completion_tokens: openaiOptions.maxCompletionTokens,
608
+ store: openaiOptions.store,
609
+ metadata: openaiOptions.metadata,
610
+ prediction: openaiOptions.prediction,
611
+ reasoning_effort: openaiOptions.reasoningEffort,
612
+ service_tier: openaiOptions.serviceTier,
613
+ prompt_cache_key: openaiOptions.promptCacheKey,
614
+ prompt_cache_retention: openaiOptions.promptCacheRetention,
615
+ safety_identifier: openaiOptions.safetyIdentifier,
616
+ // messages:
617
+ messages
618
+ };
619
+ if (isReasoningModel(this.modelId)) {
620
+ if (baseArgs.temperature != null) {
621
+ baseArgs.temperature = void 0;
622
+ warnings.push({
623
+ type: "unsupported-setting",
624
+ setting: "temperature",
625
+ details: "temperature is not supported for reasoning models"
626
+ });
627
+ }
628
+ if (baseArgs.top_p != null) {
629
+ baseArgs.top_p = void 0;
630
+ warnings.push({
631
+ type: "unsupported-setting",
632
+ setting: "topP",
633
+ details: "topP is not supported for reasoning models"
634
+ });
635
+ }
636
+ if (baseArgs.frequency_penalty != null) {
637
+ baseArgs.frequency_penalty = void 0;
638
+ warnings.push({
639
+ type: "unsupported-setting",
640
+ setting: "frequencyPenalty",
641
+ details: "frequencyPenalty is not supported for reasoning models"
642
+ });
643
+ }
644
+ if (baseArgs.presence_penalty != null) {
645
+ baseArgs.presence_penalty = void 0;
646
+ warnings.push({
647
+ type: "unsupported-setting",
648
+ setting: "presencePenalty",
649
+ details: "presencePenalty is not supported for reasoning models"
650
+ });
651
+ }
652
+ if (baseArgs.logit_bias != null) {
653
+ baseArgs.logit_bias = void 0;
654
+ warnings.push({
655
+ type: "other",
656
+ message: "logitBias is not supported for reasoning models"
657
+ });
658
+ }
659
+ if (baseArgs.logprobs != null) {
660
+ baseArgs.logprobs = void 0;
661
+ warnings.push({
662
+ type: "other",
663
+ message: "logprobs is not supported for reasoning models"
664
+ });
665
+ }
666
+ if (baseArgs.top_logprobs != null) {
667
+ baseArgs.top_logprobs = void 0;
668
+ warnings.push({
669
+ type: "other",
670
+ message: "topLogprobs is not supported for reasoning models"
671
+ });
672
+ }
673
+ if (baseArgs.max_tokens != null) {
674
+ if (baseArgs.max_completion_tokens == null) {
675
+ baseArgs.max_completion_tokens = baseArgs.max_tokens;
676
+ }
677
+ baseArgs.max_tokens = void 0;
678
+ }
679
+ } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) {
680
+ if (baseArgs.temperature != null) {
681
+ baseArgs.temperature = void 0;
682
+ warnings.push({
683
+ type: "unsupported-setting",
684
+ setting: "temperature",
685
+ details: "temperature is not supported for the search preview models and has been removed."
686
+ });
687
+ }
688
+ }
689
+ if (openaiOptions.serviceTier === "flex" && !supportsFlexProcessing(this.modelId)) {
690
+ warnings.push({
691
+ type: "unsupported-setting",
692
+ setting: "serviceTier",
693
+ details: "flex processing is only available for o3, o4-mini, and gpt-5 models"
694
+ });
695
+ baseArgs.service_tier = void 0;
696
+ }
697
+ if (openaiOptions.serviceTier === "priority" && !supportsPriorityProcessing(this.modelId)) {
698
+ warnings.push({
699
+ type: "unsupported-setting",
700
+ setting: "serviceTier",
701
+ details: "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"
702
+ });
703
+ baseArgs.service_tier = void 0;
704
+ }
705
+ const {
706
+ tools: openaiTools,
707
+ toolChoice: openaiToolChoice,
708
+ toolWarnings
709
+ } = prepareChatTools({
710
+ tools,
711
+ toolChoice,
712
+ structuredOutputs,
713
+ strictJsonSchema
714
+ });
715
+ return {
716
+ args: {
717
+ ...baseArgs,
718
+ tools: openaiTools,
719
+ tool_choice: openaiToolChoice
720
+ },
721
+ warnings: [...warnings, ...toolWarnings]
722
+ };
723
+ }
724
+ async doGenerate(options) {
725
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
726
+ const { args: body, warnings } = await this.getArgs(options);
727
+ const {
728
+ responseHeaders,
729
+ value: response,
730
+ rawValue: rawResponse
731
+ } = await postJsonToApi({
732
+ url: this.config.url({
733
+ path: "/chat/completions",
734
+ modelId: this.modelId
735
+ }),
736
+ headers: combineHeaders(this.config.headers(), options.headers),
737
+ body,
738
+ failedResponseHandler: openaiFailedResponseHandler,
739
+ successfulResponseHandler: createJsonResponseHandler(
740
+ openaiChatResponseSchema
741
+ ),
742
+ abortSignal: options.abortSignal,
743
+ fetch: this.config.fetch
744
+ });
745
+ const choice = response.choices[0];
746
+ const content = [];
747
+ const text = choice.message.content;
748
+ if (text != null && text.length > 0) {
749
+ content.push({ type: "text", text });
750
+ }
751
+ for (const toolCall of (_a = choice.message.tool_calls) != null ? _a : []) {
752
+ content.push({
753
+ type: "tool-call",
754
+ toolCallId: (_b = toolCall.id) != null ? _b : generateId(),
755
+ toolName: toolCall.function.name,
756
+ input: toolCall.function.arguments
757
+ });
758
+ }
759
+ for (const annotation of (_c = choice.message.annotations) != null ? _c : []) {
760
+ content.push({
761
+ type: "source",
762
+ sourceType: "url",
763
+ id: generateId(),
764
+ url: annotation.url,
765
+ title: annotation.title
766
+ });
767
+ }
768
+ const completionTokenDetails = (_d = response.usage) == null ? void 0 : _d.completion_tokens_details;
769
+ const promptTokenDetails = (_e = response.usage) == null ? void 0 : _e.prompt_tokens_details;
770
+ const providerMetadata = { openai: {} };
771
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) {
772
+ providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
773
+ }
774
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) {
775
+ providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
776
+ }
777
+ if (((_f = choice.logprobs) == null ? void 0 : _f.content) != null) {
778
+ providerMetadata.openai.logprobs = choice.logprobs.content;
779
+ }
780
+ return {
781
+ content,
782
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
783
+ usage: {
784
+ inputTokens: (_h = (_g = response.usage) == null ? void 0 : _g.prompt_tokens) != null ? _h : void 0,
785
+ outputTokens: (_j = (_i = response.usage) == null ? void 0 : _i.completion_tokens) != null ? _j : void 0,
786
+ totalTokens: (_l = (_k = response.usage) == null ? void 0 : _k.total_tokens) != null ? _l : void 0,
787
+ reasoningTokens: (_m = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null ? _m : void 0,
788
+ cachedInputTokens: (_n = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null ? _n : void 0
789
+ },
790
+ request: { body },
791
+ response: {
792
+ ...getResponseMetadata(response),
793
+ headers: responseHeaders,
794
+ body: rawResponse
795
+ },
796
+ warnings,
797
+ providerMetadata
798
+ };
799
+ }
800
+ async doStream(options) {
801
+ const { args, warnings } = await this.getArgs(options);
802
+ const body = {
803
+ ...args,
804
+ stream: true,
805
+ stream_options: {
806
+ include_usage: true
807
+ }
808
+ };
809
+ const { responseHeaders, value: response } = await postJsonToApi({
810
+ url: this.config.url({
811
+ path: "/chat/completions",
812
+ modelId: this.modelId
813
+ }),
814
+ headers: combineHeaders(this.config.headers(), options.headers),
815
+ body,
816
+ failedResponseHandler: openaiFailedResponseHandler,
817
+ successfulResponseHandler: createEventSourceResponseHandler(
818
+ openaiChatChunkSchema
819
+ ),
820
+ abortSignal: options.abortSignal,
821
+ fetch: this.config.fetch
822
+ });
823
+ const toolCalls = [];
824
+ let finishReason = "unknown";
825
+ const usage = {
826
+ inputTokens: void 0,
827
+ outputTokens: void 0,
828
+ totalTokens: void 0
829
+ };
830
+ let metadataExtracted = false;
831
+ let isActiveText = false;
832
+ const providerMetadata = { openai: {} };
833
+ return {
834
+ stream: response.pipeThrough(
835
+ new TransformStream({
836
+ start(controller) {
837
+ controller.enqueue({ type: "stream-start", warnings });
838
+ },
839
+ transform(chunk, controller) {
840
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
841
+ if (options.includeRawChunks) {
842
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
843
+ }
844
+ if (!chunk.success) {
845
+ finishReason = "error";
846
+ controller.enqueue({ type: "error", error: chunk.error });
847
+ return;
848
+ }
849
+ const value = chunk.value;
850
+ if ("error" in value) {
851
+ finishReason = "error";
852
+ controller.enqueue({ type: "error", error: value.error });
853
+ return;
854
+ }
855
+ if (!metadataExtracted) {
856
+ const metadata = getResponseMetadata(value);
857
+ if (Object.values(metadata).some(Boolean)) {
858
+ metadataExtracted = true;
859
+ controller.enqueue({
860
+ type: "response-metadata",
861
+ ...getResponseMetadata(value)
862
+ });
863
+ }
864
+ }
865
+ if (value.usage != null) {
866
+ usage.inputTokens = (_a = value.usage.prompt_tokens) != null ? _a : void 0;
867
+ usage.outputTokens = (_b = value.usage.completion_tokens) != null ? _b : void 0;
868
+ usage.totalTokens = (_c = value.usage.total_tokens) != null ? _c : void 0;
869
+ usage.reasoningTokens = (_e = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : void 0;
870
+ usage.cachedInputTokens = (_g = (_f = value.usage.prompt_tokens_details) == null ? void 0 : _f.cached_tokens) != null ? _g : void 0;
871
+ if (((_h = value.usage.completion_tokens_details) == null ? void 0 : _h.accepted_prediction_tokens) != null) {
872
+ providerMetadata.openai.acceptedPredictionTokens = (_i = value.usage.completion_tokens_details) == null ? void 0 : _i.accepted_prediction_tokens;
873
+ }
874
+ if (((_j = value.usage.completion_tokens_details) == null ? void 0 : _j.rejected_prediction_tokens) != null) {
875
+ providerMetadata.openai.rejectedPredictionTokens = (_k = value.usage.completion_tokens_details) == null ? void 0 : _k.rejected_prediction_tokens;
876
+ }
877
+ }
878
+ const choice = value.choices[0];
879
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
880
+ finishReason = mapOpenAIFinishReason(choice.finish_reason);
881
+ }
882
+ if (((_l = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _l.content) != null) {
883
+ providerMetadata.openai.logprobs = choice.logprobs.content;
884
+ }
885
+ if ((choice == null ? void 0 : choice.delta) == null) {
886
+ return;
887
+ }
888
+ const delta = choice.delta;
889
+ if (delta.content != null) {
890
+ if (!isActiveText) {
891
+ controller.enqueue({ type: "text-start", id: "0" });
892
+ isActiveText = true;
893
+ }
894
+ controller.enqueue({
895
+ type: "text-delta",
896
+ id: "0",
897
+ delta: delta.content
898
+ });
899
+ }
900
+ if (delta.tool_calls != null) {
901
+ for (const toolCallDelta of delta.tool_calls) {
902
+ const index = toolCallDelta.index;
903
+ if (toolCalls[index] == null) {
904
+ if (toolCallDelta.type !== "function") {
905
+ throw new InvalidResponseDataError({
906
+ data: toolCallDelta,
907
+ message: `Expected 'function' type.`
908
+ });
909
+ }
910
+ if (toolCallDelta.id == null) {
911
+ throw new InvalidResponseDataError({
912
+ data: toolCallDelta,
913
+ message: `Expected 'id' to be a string.`
914
+ });
915
+ }
916
+ if (((_m = toolCallDelta.function) == null ? void 0 : _m.name) == null) {
917
+ throw new InvalidResponseDataError({
918
+ data: toolCallDelta,
919
+ message: `Expected 'function.name' to be a string.`
920
+ });
921
+ }
922
+ controller.enqueue({
923
+ type: "tool-input-start",
924
+ id: toolCallDelta.id,
925
+ toolName: toolCallDelta.function.name
926
+ });
927
+ toolCalls[index] = {
928
+ id: toolCallDelta.id,
929
+ type: "function",
930
+ function: {
931
+ name: toolCallDelta.function.name,
932
+ arguments: (_n = toolCallDelta.function.arguments) != null ? _n : ""
933
+ },
934
+ hasFinished: false
935
+ };
936
+ const toolCall2 = toolCalls[index];
937
+ if (((_o = toolCall2.function) == null ? void 0 : _o.name) != null && ((_p = toolCall2.function) == null ? void 0 : _p.arguments) != null) {
938
+ if (toolCall2.function.arguments.length > 0) {
939
+ controller.enqueue({
940
+ type: "tool-input-delta",
941
+ id: toolCall2.id,
942
+ delta: toolCall2.function.arguments
943
+ });
944
+ }
945
+ if (isParsableJson(toolCall2.function.arguments)) {
946
+ controller.enqueue({
947
+ type: "tool-input-end",
948
+ id: toolCall2.id
949
+ });
950
+ controller.enqueue({
951
+ type: "tool-call",
952
+ toolCallId: (_q = toolCall2.id) != null ? _q : generateId(),
953
+ toolName: toolCall2.function.name,
954
+ input: toolCall2.function.arguments
955
+ });
956
+ toolCall2.hasFinished = true;
957
+ }
958
+ }
959
+ continue;
960
+ }
961
+ const toolCall = toolCalls[index];
962
+ if (toolCall.hasFinished) {
963
+ continue;
964
+ }
965
+ if (((_r = toolCallDelta.function) == null ? void 0 : _r.arguments) != null) {
966
+ toolCall.function.arguments += (_t = (_s = toolCallDelta.function) == null ? void 0 : _s.arguments) != null ? _t : "";
967
+ }
968
+ controller.enqueue({
969
+ type: "tool-input-delta",
970
+ id: toolCall.id,
971
+ delta: (_u = toolCallDelta.function.arguments) != null ? _u : ""
972
+ });
973
+ if (((_v = toolCall.function) == null ? void 0 : _v.name) != null && ((_w = toolCall.function) == null ? void 0 : _w.arguments) != null && isParsableJson(toolCall.function.arguments)) {
974
+ controller.enqueue({
975
+ type: "tool-input-end",
976
+ id: toolCall.id
977
+ });
978
+ controller.enqueue({
979
+ type: "tool-call",
980
+ toolCallId: (_x = toolCall.id) != null ? _x : generateId(),
981
+ toolName: toolCall.function.name,
982
+ input: toolCall.function.arguments
983
+ });
984
+ toolCall.hasFinished = true;
985
+ }
986
+ }
987
+ }
988
+ if (delta.annotations != null) {
989
+ for (const annotation of delta.annotations) {
990
+ controller.enqueue({
991
+ type: "source",
992
+ sourceType: "url",
993
+ id: generateId(),
994
+ url: annotation.url,
995
+ title: annotation.title
996
+ });
997
+ }
998
+ }
999
+ },
1000
+ flush(controller) {
1001
+ if (isActiveText) {
1002
+ controller.enqueue({ type: "text-end", id: "0" });
1003
+ }
1004
+ controller.enqueue({
1005
+ type: "finish",
1006
+ finishReason,
1007
+ usage,
1008
+ ...providerMetadata != null ? { providerMetadata } : {}
1009
+ });
1010
+ }
1011
+ })
1012
+ ),
1013
+ request: { body },
1014
+ response: { headers: responseHeaders }
1015
+ };
1016
+ }
1017
+ };
1018
+ function isReasoningModel(modelId) {
1019
+ return (modelId.startsWith("o") || modelId.startsWith("gpt-5")) && !modelId.startsWith("gpt-5-chat");
1020
+ }
1021
+ function supportsFlexProcessing(modelId) {
1022
+ return modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
1023
+ }
1024
+ function supportsPriorityProcessing(modelId) {
1025
+ return modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") || modelId.startsWith("o3") || modelId.startsWith("o4-mini");
1026
+ }
1027
+ function getSystemMessageMode(modelId) {
1028
+ var _a, _b;
1029
+ if (!isReasoningModel(modelId)) {
1030
+ return "system";
1031
+ }
1032
+ return (_b = (_a = reasoningModels[modelId]) == null ? void 0 : _a.systemMessageMode) != null ? _b : "developer";
1033
+ }
1034
+ var reasoningModels = {
1035
+ o3: {
1036
+ systemMessageMode: "developer"
1037
+ },
1038
+ "o3-2025-04-16": {
1039
+ systemMessageMode: "developer"
1040
+ },
1041
+ "o3-mini": {
1042
+ systemMessageMode: "developer"
1043
+ },
1044
+ "o3-mini-2025-01-31": {
1045
+ systemMessageMode: "developer"
1046
+ },
1047
+ "o4-mini": {
1048
+ systemMessageMode: "developer"
1049
+ },
1050
+ "o4-mini-2025-04-16": {
1051
+ systemMessageMode: "developer"
1052
+ }
1053
+ };
1054
+ function convertToOpenAICompletionPrompt({
1055
+ prompt,
1056
+ user = "user",
1057
+ assistant = "assistant"
1058
+ }) {
1059
+ let text = "";
1060
+ if (prompt[0].role === "system") {
1061
+ text += `${prompt[0].content}
1062
+
1063
+ `;
1064
+ prompt = prompt.slice(1);
1065
+ }
1066
+ for (const { role, content } of prompt) {
1067
+ switch (role) {
1068
+ case "system": {
1069
+ throw new InvalidPromptError({
1070
+ message: "Unexpected system message in prompt: ${content}",
1071
+ prompt
1072
+ });
1073
+ }
1074
+ case "user": {
1075
+ const userMessage = content.map((part) => {
1076
+ switch (part.type) {
1077
+ case "text": {
1078
+ return part.text;
1079
+ }
1080
+ }
1081
+ }).filter(Boolean).join("");
1082
+ text += `${user}:
1083
+ ${userMessage}
1084
+
1085
+ `;
1086
+ break;
1087
+ }
1088
+ case "assistant": {
1089
+ const assistantMessage = content.map((part) => {
1090
+ switch (part.type) {
1091
+ case "text": {
1092
+ return part.text;
1093
+ }
1094
+ case "tool-call": {
1095
+ throw new UnsupportedFunctionalityError({
1096
+ functionality: "tool-call messages"
1097
+ });
1098
+ }
1099
+ }
1100
+ }).join("");
1101
+ text += `${assistant}:
1102
+ ${assistantMessage}
1103
+
1104
+ `;
1105
+ break;
1106
+ }
1107
+ case "tool": {
1108
+ throw new UnsupportedFunctionalityError({
1109
+ functionality: "tool messages"
1110
+ });
1111
+ }
1112
+ default: {
1113
+ const _exhaustiveCheck = role;
1114
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1115
+ }
1116
+ }
1117
+ }
1118
+ text += `${assistant}:
1119
+ `;
1120
+ return {
1121
+ prompt: text,
1122
+ stopSequences: [`
1123
+ ${user}:`]
1124
+ };
1125
+ }
1126
+ function getResponseMetadata2({
1127
+ id,
1128
+ model,
1129
+ created
1130
+ }) {
1131
+ return {
1132
+ id: id != null ? id : void 0,
1133
+ modelId: model != null ? model : void 0,
1134
+ timestamp: created != null ? new Date(created * 1e3) : void 0
1135
+ };
1136
+ }
1137
+ function mapOpenAIFinishReason2(finishReason) {
1138
+ switch (finishReason) {
1139
+ case "stop":
1140
+ return "stop";
1141
+ case "length":
1142
+ return "length";
1143
+ case "content_filter":
1144
+ return "content-filter";
1145
+ case "function_call":
1146
+ case "tool_calls":
1147
+ return "tool-calls";
1148
+ default:
1149
+ return "unknown";
1150
+ }
1151
+ }
1152
+ var openaiCompletionResponseSchema = lazyValidator(
1153
+ () => zodSchema(
1154
+ z.object({
1155
+ id: z.string().nullish(),
1156
+ created: z.number().nullish(),
1157
+ model: z.string().nullish(),
1158
+ choices: z.array(
1159
+ z.object({
1160
+ text: z.string(),
1161
+ finish_reason: z.string(),
1162
+ logprobs: z.object({
1163
+ tokens: z.array(z.string()),
1164
+ token_logprobs: z.array(z.number()),
1165
+ top_logprobs: z.array(z.record(z.string(), z.number())).nullish()
1166
+ }).nullish()
1167
+ })
1168
+ ),
1169
+ usage: z.object({
1170
+ prompt_tokens: z.number(),
1171
+ completion_tokens: z.number(),
1172
+ total_tokens: z.number()
1173
+ }).nullish()
1174
+ })
1175
+ )
1176
+ );
1177
+ var openaiCompletionChunkSchema = lazyValidator(
1178
+ () => zodSchema(
1179
+ z.union([
1180
+ z.object({
1181
+ id: z.string().nullish(),
1182
+ created: z.number().nullish(),
1183
+ model: z.string().nullish(),
1184
+ choices: z.array(
1185
+ z.object({
1186
+ text: z.string(),
1187
+ finish_reason: z.string().nullish(),
1188
+ index: z.number(),
1189
+ logprobs: z.object({
1190
+ tokens: z.array(z.string()),
1191
+ token_logprobs: z.array(z.number()),
1192
+ top_logprobs: z.array(z.record(z.string(), z.number())).nullish()
1193
+ }).nullish()
1194
+ })
1195
+ ),
1196
+ usage: z.object({
1197
+ prompt_tokens: z.number(),
1198
+ completion_tokens: z.number(),
1199
+ total_tokens: z.number()
1200
+ }).nullish()
1201
+ }),
1202
+ openaiErrorDataSchema
1203
+ ])
1204
+ )
1205
+ );
1206
+ var openaiCompletionProviderOptions = lazyValidator(
1207
+ () => zodSchema(
1208
+ z.object({
1209
+ /**
1210
+ Echo back the prompt in addition to the completion.
1211
+ */
1212
+ echo: z.boolean().optional(),
1213
+ /**
1214
+ Modify the likelihood of specified tokens appearing in the completion.
1215
+
1216
+ Accepts a JSON object that maps tokens (specified by their token ID in
1217
+ the GPT tokenizer) to an associated bias value from -100 to 100. You
1218
+ can use this tokenizer tool to convert text to token IDs. Mathematically,
1219
+ the bias is added to the logits generated by the model prior to sampling.
1220
+ The exact effect will vary per model, but values between -1 and 1 should
1221
+ decrease or increase likelihood of selection; values like -100 or 100
1222
+ should result in a ban or exclusive selection of the relevant token.
1223
+
1224
+ As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
1225
+ token from being generated.
1226
+ */
1227
+ logitBias: z.record(z.string(), z.number()).optional(),
1228
+ /**
1229
+ The suffix that comes after a completion of inserted text.
1230
+ */
1231
+ suffix: z.string().optional(),
1232
+ /**
1233
+ A unique identifier representing your end-user, which can help OpenAI to
1234
+ monitor and detect abuse. Learn more.
1235
+ */
1236
+ user: z.string().optional(),
1237
+ /**
1238
+ Return the log probabilities of the tokens. Including logprobs will increase
1239
+ the response size and can slow down response times. However, it can
1240
+ be useful to better understand how the model is behaving.
1241
+ Setting to true will return the log probabilities of the tokens that
1242
+ were generated.
1243
+ Setting to a number will return the log probabilities of the top n
1244
+ tokens that were generated.
1245
+ */
1246
+ logprobs: z.union([z.boolean(), z.number()]).optional()
1247
+ })
1248
+ )
1249
+ );
1250
+ var OpenAICompletionLanguageModel = class {
1251
+ constructor(modelId, config) {
1252
+ this.specificationVersion = "v2";
1253
+ this.supportedUrls = {
1254
+ // No URLs are supported for completion models.
1255
+ };
1256
+ this.modelId = modelId;
1257
+ this.config = config;
1258
+ }
1259
+ get providerOptionsName() {
1260
+ return this.config.provider.split(".")[0].trim();
1261
+ }
1262
+ get provider() {
1263
+ return this.config.provider;
1264
+ }
1265
+ async getArgs({
1266
+ prompt,
1267
+ maxOutputTokens,
1268
+ temperature,
1269
+ topP,
1270
+ topK,
1271
+ frequencyPenalty,
1272
+ presencePenalty,
1273
+ stopSequences: userStopSequences,
1274
+ responseFormat,
1275
+ tools,
1276
+ toolChoice,
1277
+ seed,
1278
+ providerOptions
1279
+ }) {
1280
+ const warnings = [];
1281
+ const openaiOptions = {
1282
+ ...await parseProviderOptions({
1283
+ provider: "openai",
1284
+ providerOptions,
1285
+ schema: openaiCompletionProviderOptions
1286
+ }),
1287
+ ...await parseProviderOptions({
1288
+ provider: this.providerOptionsName,
1289
+ providerOptions,
1290
+ schema: openaiCompletionProviderOptions
1291
+ })
1292
+ };
1293
+ if (topK != null) {
1294
+ warnings.push({ type: "unsupported-setting", setting: "topK" });
1295
+ }
1296
+ if (tools == null ? void 0 : tools.length) {
1297
+ warnings.push({ type: "unsupported-setting", setting: "tools" });
1298
+ }
1299
+ if (toolChoice != null) {
1300
+ warnings.push({ type: "unsupported-setting", setting: "toolChoice" });
1301
+ }
1302
+ if (responseFormat != null && responseFormat.type !== "text") {
1303
+ warnings.push({
1304
+ type: "unsupported-setting",
1305
+ setting: "responseFormat",
1306
+ details: "JSON response format is not supported."
1307
+ });
1308
+ }
1309
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt });
1310
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
1311
+ return {
1312
+ args: {
1313
+ // model id:
1314
+ model: this.modelId,
1315
+ // model specific settings:
1316
+ echo: openaiOptions.echo,
1317
+ logit_bias: openaiOptions.logitBias,
1318
+ logprobs: (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? 0 : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === false ? void 0 : openaiOptions == null ? void 0 : openaiOptions.logprobs,
1319
+ suffix: openaiOptions.suffix,
1320
+ user: openaiOptions.user,
1321
+ // standardized settings:
1322
+ max_tokens: maxOutputTokens,
1323
+ temperature,
1324
+ top_p: topP,
1325
+ frequency_penalty: frequencyPenalty,
1326
+ presence_penalty: presencePenalty,
1327
+ seed,
1328
+ // prompt:
1329
+ prompt: completionPrompt,
1330
+ // stop sequences:
1331
+ stop: stop.length > 0 ? stop : void 0
1332
+ },
1333
+ warnings
1334
+ };
1335
+ }
1336
+ async doGenerate(options) {
1337
+ var _a, _b, _c;
1338
+ const { args, warnings } = await this.getArgs(options);
1339
+ const {
1340
+ responseHeaders,
1341
+ value: response,
1342
+ rawValue: rawResponse
1343
+ } = await postJsonToApi({
1344
+ url: this.config.url({
1345
+ path: "/completions",
1346
+ modelId: this.modelId
1347
+ }),
1348
+ headers: combineHeaders(this.config.headers(), options.headers),
1349
+ body: args,
1350
+ failedResponseHandler: openaiFailedResponseHandler,
1351
+ successfulResponseHandler: createJsonResponseHandler(
1352
+ openaiCompletionResponseSchema
1353
+ ),
1354
+ abortSignal: options.abortSignal,
1355
+ fetch: this.config.fetch
1356
+ });
1357
+ const choice = response.choices[0];
1358
+ const providerMetadata = { openai: {} };
1359
+ if (choice.logprobs != null) {
1360
+ providerMetadata.openai.logprobs = choice.logprobs;
1361
+ }
1362
+ return {
1363
+ content: [{ type: "text", text: choice.text }],
1364
+ usage: {
1365
+ inputTokens: (_a = response.usage) == null ? void 0 : _a.prompt_tokens,
1366
+ outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens,
1367
+ totalTokens: (_c = response.usage) == null ? void 0 : _c.total_tokens
1368
+ },
1369
+ finishReason: mapOpenAIFinishReason2(choice.finish_reason),
1370
+ request: { body: args },
1371
+ response: {
1372
+ ...getResponseMetadata2(response),
1373
+ headers: responseHeaders,
1374
+ body: rawResponse
1375
+ },
1376
+ providerMetadata,
1377
+ warnings
1378
+ };
1379
+ }
1380
+ async doStream(options) {
1381
+ const { args, warnings } = await this.getArgs(options);
1382
+ const body = {
1383
+ ...args,
1384
+ stream: true,
1385
+ stream_options: {
1386
+ include_usage: true
1387
+ }
1388
+ };
1389
+ const { responseHeaders, value: response } = await postJsonToApi({
1390
+ url: this.config.url({
1391
+ path: "/completions",
1392
+ modelId: this.modelId
1393
+ }),
1394
+ headers: combineHeaders(this.config.headers(), options.headers),
1395
+ body,
1396
+ failedResponseHandler: openaiFailedResponseHandler,
1397
+ successfulResponseHandler: createEventSourceResponseHandler(
1398
+ openaiCompletionChunkSchema
1399
+ ),
1400
+ abortSignal: options.abortSignal,
1401
+ fetch: this.config.fetch
1402
+ });
1403
+ let finishReason = "unknown";
1404
+ const providerMetadata = { openai: {} };
1405
+ const usage = {
1406
+ inputTokens: void 0,
1407
+ outputTokens: void 0,
1408
+ totalTokens: void 0
1409
+ };
1410
+ let isFirstChunk = true;
1411
+ return {
1412
+ stream: response.pipeThrough(
1413
+ new TransformStream({
1414
+ start(controller) {
1415
+ controller.enqueue({ type: "stream-start", warnings });
1416
+ },
1417
+ transform(chunk, controller) {
1418
+ if (options.includeRawChunks) {
1419
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1420
+ }
1421
+ if (!chunk.success) {
1422
+ finishReason = "error";
1423
+ controller.enqueue({ type: "error", error: chunk.error });
1424
+ return;
1425
+ }
1426
+ const value = chunk.value;
1427
+ if ("error" in value) {
1428
+ finishReason = "error";
1429
+ controller.enqueue({ type: "error", error: value.error });
1430
+ return;
1431
+ }
1432
+ if (isFirstChunk) {
1433
+ isFirstChunk = false;
1434
+ controller.enqueue({
1435
+ type: "response-metadata",
1436
+ ...getResponseMetadata2(value)
1437
+ });
1438
+ controller.enqueue({ type: "text-start", id: "0" });
1439
+ }
1440
+ if (value.usage != null) {
1441
+ usage.inputTokens = value.usage.prompt_tokens;
1442
+ usage.outputTokens = value.usage.completion_tokens;
1443
+ usage.totalTokens = value.usage.total_tokens;
1444
+ }
1445
+ const choice = value.choices[0];
1446
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
1447
+ finishReason = mapOpenAIFinishReason2(choice.finish_reason);
1448
+ }
1449
+ if ((choice == null ? void 0 : choice.logprobs) != null) {
1450
+ providerMetadata.openai.logprobs = choice.logprobs;
1451
+ }
1452
+ if ((choice == null ? void 0 : choice.text) != null && choice.text.length > 0) {
1453
+ controller.enqueue({
1454
+ type: "text-delta",
1455
+ id: "0",
1456
+ delta: choice.text
1457
+ });
1458
+ }
1459
+ },
1460
+ flush(controller) {
1461
+ if (!isFirstChunk) {
1462
+ controller.enqueue({ type: "text-end", id: "0" });
1463
+ }
1464
+ controller.enqueue({
1465
+ type: "finish",
1466
+ finishReason,
1467
+ providerMetadata,
1468
+ usage
1469
+ });
1470
+ }
1471
+ })
1472
+ ),
1473
+ request: { body },
1474
+ response: { headers: responseHeaders }
1475
+ };
1476
+ }
1477
+ };
1478
+ var openaiEmbeddingProviderOptions = lazyValidator(
1479
+ () => zodSchema(
1480
+ z.object({
1481
+ /**
1482
+ The number of dimensions the resulting output embeddings should have.
1483
+ Only supported in text-embedding-3 and later models.
1484
+ */
1485
+ dimensions: z.number().optional(),
1486
+ /**
1487
+ A unique identifier representing your end-user, which can help OpenAI to
1488
+ monitor and detect abuse. Learn more.
1489
+ */
1490
+ user: z.string().optional()
1491
+ })
1492
+ )
1493
+ );
1494
+ var openaiTextEmbeddingResponseSchema = lazyValidator(
1495
+ () => zodSchema(
1496
+ z.object({
1497
+ data: z.array(z.object({ embedding: z.array(z.number()) })),
1498
+ usage: z.object({ prompt_tokens: z.number() }).nullish()
1499
+ })
1500
+ )
1501
+ );
1502
+ var OpenAIEmbeddingModel = class {
1503
+ constructor(modelId, config) {
1504
+ this.specificationVersion = "v2";
1505
+ this.maxEmbeddingsPerCall = 2048;
1506
+ this.supportsParallelCalls = true;
1507
+ this.modelId = modelId;
1508
+ this.config = config;
1509
+ }
1510
+ get provider() {
1511
+ return this.config.provider;
1512
+ }
1513
+ async doEmbed({
1514
+ values,
1515
+ headers,
1516
+ abortSignal,
1517
+ providerOptions
1518
+ }) {
1519
+ var _a;
1520
+ if (values.length > this.maxEmbeddingsPerCall) {
1521
+ throw new TooManyEmbeddingValuesForCallError({
1522
+ provider: this.provider,
1523
+ modelId: this.modelId,
1524
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
1525
+ values
1526
+ });
1527
+ }
1528
+ const openaiOptions = (_a = await parseProviderOptions({
1529
+ provider: "openai",
1530
+ providerOptions,
1531
+ schema: openaiEmbeddingProviderOptions
1532
+ })) != null ? _a : {};
1533
+ const {
1534
+ responseHeaders,
1535
+ value: response,
1536
+ rawValue
1537
+ } = await postJsonToApi({
1538
+ url: this.config.url({
1539
+ path: "/embeddings",
1540
+ modelId: this.modelId
1541
+ }),
1542
+ headers: combineHeaders(this.config.headers(), headers),
1543
+ body: {
1544
+ model: this.modelId,
1545
+ input: values,
1546
+ encoding_format: "float",
1547
+ dimensions: openaiOptions.dimensions,
1548
+ user: openaiOptions.user
1549
+ },
1550
+ failedResponseHandler: openaiFailedResponseHandler,
1551
+ successfulResponseHandler: createJsonResponseHandler(
1552
+ openaiTextEmbeddingResponseSchema
1553
+ ),
1554
+ abortSignal,
1555
+ fetch: this.config.fetch
1556
+ });
1557
+ return {
1558
+ embeddings: response.data.map((item) => item.embedding),
1559
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
1560
+ response: { headers: responseHeaders, body: rawValue }
1561
+ };
1562
+ }
1563
+ };
1564
+ var openaiImageResponseSchema = lazyValidator(
1565
+ () => zodSchema(
1566
+ z.object({
1567
+ data: z.array(
1568
+ z.object({
1569
+ b64_json: z.string(),
1570
+ revised_prompt: z.string().nullish()
1571
+ })
1572
+ )
1573
+ })
1574
+ )
1575
+ );
1576
+ var modelMaxImagesPerCall = {
1577
+ "dall-e-3": 1,
1578
+ "dall-e-2": 10,
1579
+ "gpt-image-1": 10,
1580
+ "gpt-image-1-mini": 10
1581
+ };
1582
+ var hasDefaultResponseFormat = /* @__PURE__ */ new Set([
1583
+ "gpt-image-1",
1584
+ "gpt-image-1-mini"
1585
+ ]);
1586
+ var OpenAIImageModel = class {
1587
+ constructor(modelId, config) {
1588
+ this.modelId = modelId;
1589
+ this.config = config;
1590
+ this.specificationVersion = "v2";
1591
+ }
1592
+ get maxImagesPerCall() {
1593
+ var _a;
1594
+ return (_a = modelMaxImagesPerCall[this.modelId]) != null ? _a : 1;
1595
+ }
1596
+ get provider() {
1597
+ return this.config.provider;
1598
+ }
1599
+ async doGenerate({
1600
+ prompt,
1601
+ n,
1602
+ size,
1603
+ aspectRatio,
1604
+ seed,
1605
+ providerOptions,
1606
+ headers,
1607
+ abortSignal
1608
+ }) {
1609
+ var _a, _b, _c, _d;
1610
+ const warnings = [];
1611
+ if (aspectRatio != null) {
1612
+ warnings.push({
1613
+ type: "unsupported-setting",
1614
+ setting: "aspectRatio",
1615
+ details: "This model does not support aspect ratio. Use `size` instead."
1616
+ });
1617
+ }
1618
+ if (seed != null) {
1619
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
1620
+ }
1621
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1622
+ const { value: response, responseHeaders } = await postJsonToApi({
1623
+ url: this.config.url({
1624
+ path: "/images/generations",
1625
+ modelId: this.modelId
1626
+ }),
1627
+ headers: combineHeaders(this.config.headers(), headers),
1628
+ body: {
1629
+ model: this.modelId,
1630
+ prompt,
1631
+ n,
1632
+ size,
1633
+ ...(_d = providerOptions.openai) != null ? _d : {},
1634
+ ...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
1635
+ },
1636
+ failedResponseHandler: openaiFailedResponseHandler,
1637
+ successfulResponseHandler: createJsonResponseHandler(
1638
+ openaiImageResponseSchema
1639
+ ),
1640
+ abortSignal,
1641
+ fetch: this.config.fetch
1642
+ });
1643
+ return {
1644
+ images: response.data.map((item) => item.b64_json),
1645
+ warnings,
1646
+ response: {
1647
+ timestamp: currentDate,
1648
+ modelId: this.modelId,
1649
+ headers: responseHeaders
1650
+ },
1651
+ providerMetadata: {
1652
+ openai: {
1653
+ images: response.data.map(
1654
+ (item) => item.revised_prompt ? {
1655
+ revisedPrompt: item.revised_prompt
1656
+ } : null
1657
+ )
1658
+ }
1659
+ }
1660
+ };
1661
+ }
1662
+ };
1663
+ var openaiTranscriptionResponseSchema = lazyValidator(
1664
+ () => zodSchema(
1665
+ z.object({
1666
+ text: z.string(),
1667
+ language: z.string().nullish(),
1668
+ duration: z.number().nullish(),
1669
+ words: z.array(
1670
+ z.object({
1671
+ word: z.string(),
1672
+ start: z.number(),
1673
+ end: z.number()
1674
+ })
1675
+ ).nullish(),
1676
+ segments: z.array(
1677
+ z.object({
1678
+ id: z.number(),
1679
+ seek: z.number(),
1680
+ start: z.number(),
1681
+ end: z.number(),
1682
+ text: z.string(),
1683
+ tokens: z.array(z.number()),
1684
+ temperature: z.number(),
1685
+ avg_logprob: z.number(),
1686
+ compression_ratio: z.number(),
1687
+ no_speech_prob: z.number()
1688
+ })
1689
+ ).nullish()
1690
+ })
1691
+ )
1692
+ );
1693
+ var openAITranscriptionProviderOptions = lazyValidator(
1694
+ () => zodSchema(
1695
+ z.object({
1696
+ /**
1697
+ * Additional information to include in the transcription response.
1698
+ */
1699
+ include: z.array(z.string()).optional(),
1700
+ /**
1701
+ * The language of the input audio in ISO-639-1 format.
1702
+ */
1703
+ language: z.string().optional(),
1704
+ /**
1705
+ * An optional text to guide the model's style or continue a previous audio segment.
1706
+ */
1707
+ prompt: z.string().optional(),
1708
+ /**
1709
+ * The sampling temperature, between 0 and 1.
1710
+ * @default 0
1711
+ */
1712
+ temperature: z.number().min(0).max(1).default(0).optional(),
1713
+ /**
1714
+ * The timestamp granularities to populate for this transcription.
1715
+ * @default ['segment']
1716
+ */
1717
+ timestampGranularities: z.array(z.enum(["word", "segment"])).default(["segment"]).optional()
1718
+ })
1719
+ )
1720
+ );
1721
+ var languageMap = {
1722
+ afrikaans: "af",
1723
+ arabic: "ar",
1724
+ armenian: "hy",
1725
+ azerbaijani: "az",
1726
+ belarusian: "be",
1727
+ bosnian: "bs",
1728
+ bulgarian: "bg",
1729
+ catalan: "ca",
1730
+ chinese: "zh",
1731
+ croatian: "hr",
1732
+ czech: "cs",
1733
+ danish: "da",
1734
+ dutch: "nl",
1735
+ english: "en",
1736
+ estonian: "et",
1737
+ finnish: "fi",
1738
+ french: "fr",
1739
+ galician: "gl",
1740
+ german: "de",
1741
+ greek: "el",
1742
+ hebrew: "he",
1743
+ hindi: "hi",
1744
+ hungarian: "hu",
1745
+ icelandic: "is",
1746
+ indonesian: "id",
1747
+ italian: "it",
1748
+ japanese: "ja",
1749
+ kannada: "kn",
1750
+ kazakh: "kk",
1751
+ korean: "ko",
1752
+ latvian: "lv",
1753
+ lithuanian: "lt",
1754
+ macedonian: "mk",
1755
+ malay: "ms",
1756
+ marathi: "mr",
1757
+ maori: "mi",
1758
+ nepali: "ne",
1759
+ norwegian: "no",
1760
+ persian: "fa",
1761
+ polish: "pl",
1762
+ portuguese: "pt",
1763
+ romanian: "ro",
1764
+ russian: "ru",
1765
+ serbian: "sr",
1766
+ slovak: "sk",
1767
+ slovenian: "sl",
1768
+ spanish: "es",
1769
+ swahili: "sw",
1770
+ swedish: "sv",
1771
+ tagalog: "tl",
1772
+ tamil: "ta",
1773
+ thai: "th",
1774
+ turkish: "tr",
1775
+ ukrainian: "uk",
1776
+ urdu: "ur",
1777
+ vietnamese: "vi",
1778
+ welsh: "cy"
1779
+ };
1780
+ var OpenAITranscriptionModel = class {
1781
+ constructor(modelId, config) {
1782
+ this.modelId = modelId;
1783
+ this.config = config;
1784
+ this.specificationVersion = "v2";
1785
+ }
1786
+ get provider() {
1787
+ return this.config.provider;
1788
+ }
1789
+ async getArgs({
1790
+ audio,
1791
+ mediaType,
1792
+ providerOptions
1793
+ }) {
1794
+ const warnings = [];
1795
+ const openAIOptions = await parseProviderOptions({
1796
+ provider: "openai",
1797
+ providerOptions,
1798
+ schema: openAITranscriptionProviderOptions
1799
+ });
1800
+ const formData = new FormData();
1801
+ const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
1802
+ formData.append("model", this.modelId);
1803
+ const fileExtension = mediaTypeToExtension(mediaType);
1804
+ formData.append(
1805
+ "file",
1806
+ new File([blob], "audio", { type: mediaType }),
1807
+ `audio.${fileExtension}`
1808
+ );
1809
+ if (openAIOptions) {
1810
+ const transcriptionModelOptions = {
1811
+ include: openAIOptions.include,
1812
+ language: openAIOptions.language,
1813
+ prompt: openAIOptions.prompt,
1814
+ // https://platform.openai.com/docs/api-reference/audio/createTranscription#audio_createtranscription-response_format
1815
+ // prefer verbose_json to get segments for models that support it
1816
+ response_format: [
1817
+ "gpt-4o-transcribe",
1818
+ "gpt-4o-mini-transcribe"
1819
+ ].includes(this.modelId) ? "json" : "verbose_json",
1820
+ temperature: openAIOptions.temperature,
1821
+ timestamp_granularities: openAIOptions.timestampGranularities
1822
+ };
1823
+ for (const [key, value] of Object.entries(transcriptionModelOptions)) {
1824
+ if (value != null) {
1825
+ if (Array.isArray(value)) {
1826
+ for (const item of value) {
1827
+ formData.append(`${key}[]`, String(item));
1828
+ }
1829
+ } else {
1830
+ formData.append(key, String(value));
1831
+ }
1832
+ }
1833
+ }
1834
+ }
1835
+ return {
1836
+ formData,
1837
+ warnings
1838
+ };
1839
+ }
1840
+ async doGenerate(options) {
1841
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1842
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1843
+ const { formData, warnings } = await this.getArgs(options);
1844
+ const {
1845
+ value: response,
1846
+ responseHeaders,
1847
+ rawValue: rawResponse
1848
+ } = await postFormDataToApi({
1849
+ url: this.config.url({
1850
+ path: "/audio/transcriptions",
1851
+ modelId: this.modelId
1852
+ }),
1853
+ headers: combineHeaders(this.config.headers(), options.headers),
1854
+ formData,
1855
+ failedResponseHandler: openaiFailedResponseHandler,
1856
+ successfulResponseHandler: createJsonResponseHandler(
1857
+ openaiTranscriptionResponseSchema
1858
+ ),
1859
+ abortSignal: options.abortSignal,
1860
+ fetch: this.config.fetch
1861
+ });
1862
+ const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0;
1863
+ return {
1864
+ text: response.text,
1865
+ segments: (_g = (_f = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({
1866
+ text: segment.text,
1867
+ startSecond: segment.start,
1868
+ endSecond: segment.end
1869
+ }))) != null ? _f : (_e = response.words) == null ? void 0 : _e.map((word) => ({
1870
+ text: word.word,
1871
+ startSecond: word.start,
1872
+ endSecond: word.end
1873
+ }))) != null ? _g : [],
1874
+ language,
1875
+ durationInSeconds: (_h = response.duration) != null ? _h : void 0,
1876
+ warnings,
1877
+ response: {
1878
+ timestamp: currentDate,
1879
+ modelId: this.modelId,
1880
+ headers: responseHeaders,
1881
+ body: rawResponse
1882
+ }
1883
+ };
1884
+ }
1885
+ };
1886
+ var openaiSpeechProviderOptionsSchema = lazyValidator(
1887
+ () => zodSchema(
1888
+ z.object({
1889
+ instructions: z.string().nullish(),
1890
+ speed: z.number().min(0.25).max(4).default(1).nullish()
1891
+ })
1892
+ )
1893
+ );
1894
+ var OpenAISpeechModel = class {
1895
+ constructor(modelId, config) {
1896
+ this.modelId = modelId;
1897
+ this.config = config;
1898
+ this.specificationVersion = "v2";
1899
+ }
1900
+ get provider() {
1901
+ return this.config.provider;
1902
+ }
1903
+ async getArgs({
1904
+ text,
1905
+ voice = "alloy",
1906
+ outputFormat = "mp3",
1907
+ speed,
1908
+ instructions,
1909
+ language,
1910
+ providerOptions
1911
+ }) {
1912
+ const warnings = [];
1913
+ const openAIOptions = await parseProviderOptions({
1914
+ provider: "openai",
1915
+ providerOptions,
1916
+ schema: openaiSpeechProviderOptionsSchema
1917
+ });
1918
+ const requestBody = {
1919
+ model: this.modelId,
1920
+ input: text,
1921
+ voice,
1922
+ response_format: "mp3",
1923
+ speed,
1924
+ instructions
1925
+ };
1926
+ if (outputFormat) {
1927
+ if (["mp3", "opus", "aac", "flac", "wav", "pcm"].includes(outputFormat)) {
1928
+ requestBody.response_format = outputFormat;
1929
+ } else {
1930
+ warnings.push({
1931
+ type: "unsupported-setting",
1932
+ setting: "outputFormat",
1933
+ details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`
1934
+ });
1935
+ }
1936
+ }
1937
+ if (openAIOptions) {
1938
+ const speechModelOptions = {};
1939
+ for (const key in speechModelOptions) {
1940
+ const value = speechModelOptions[key];
1941
+ if (value !== void 0) {
1942
+ requestBody[key] = value;
1943
+ }
1944
+ }
1945
+ }
1946
+ if (language) {
1947
+ warnings.push({
1948
+ type: "unsupported-setting",
1949
+ setting: "language",
1950
+ details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.`
1951
+ });
1952
+ }
1953
+ return {
1954
+ requestBody,
1955
+ warnings
1956
+ };
1957
+ }
1958
+ async doGenerate(options) {
1959
+ var _a, _b, _c;
1960
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1961
+ const { requestBody, warnings } = await this.getArgs(options);
1962
+ const {
1963
+ value: audio,
1964
+ responseHeaders,
1965
+ rawValue: rawResponse
1966
+ } = await postJsonToApi({
1967
+ url: this.config.url({
1968
+ path: "/audio/speech",
1969
+ modelId: this.modelId
1970
+ }),
1971
+ headers: combineHeaders(this.config.headers(), options.headers),
1972
+ body: requestBody,
1973
+ failedResponseHandler: openaiFailedResponseHandler,
1974
+ successfulResponseHandler: createBinaryResponseHandler(),
1975
+ abortSignal: options.abortSignal,
1976
+ fetch: this.config.fetch
1977
+ });
1978
+ return {
1979
+ audio,
1980
+ warnings,
1981
+ request: {
1982
+ body: JSON.stringify(requestBody)
1983
+ },
1984
+ response: {
1985
+ timestamp: currentDate,
1986
+ modelId: this.modelId,
1987
+ headers: responseHeaders,
1988
+ body: rawResponse
1989
+ }
1990
+ };
1991
+ }
1992
+ };
1993
+ var localShellInputSchema = lazySchema(
1994
+ () => zodSchema(
1995
+ z.object({
1996
+ action: z.object({
1997
+ type: z.literal("exec"),
1998
+ command: z.array(z.string()),
1999
+ timeoutMs: z.number().optional(),
2000
+ user: z.string().optional(),
2001
+ workingDirectory: z.string().optional(),
2002
+ env: z.record(z.string(), z.string()).optional()
2003
+ })
2004
+ })
2005
+ )
2006
+ );
2007
+ var localShellOutputSchema = lazySchema(
2008
+ () => zodSchema(z.object({ output: z.string() }))
2009
+ );
2010
+ createProviderDefinedToolFactoryWithOutputSchema({
2011
+ id: "openai.local_shell",
2012
+ name: "local_shell",
2013
+ inputSchema: localShellInputSchema,
2014
+ outputSchema: localShellOutputSchema
2015
+ });
2016
+ function isFileId(data, prefixes) {
2017
+ if (!prefixes) return false;
2018
+ return prefixes.some((prefix) => data.startsWith(prefix));
2019
+ }
2020
+ async function convertToOpenAIResponsesInput({
2021
+ prompt,
2022
+ systemMessageMode,
2023
+ fileIdPrefixes,
2024
+ store,
2025
+ hasLocalShellTool = false
2026
+ }) {
2027
+ var _a, _b, _c, _d;
2028
+ const input = [];
2029
+ const warnings = [];
2030
+ for (const { role, content } of prompt) {
2031
+ switch (role) {
2032
+ case "system": {
2033
+ switch (systemMessageMode) {
2034
+ case "system": {
2035
+ input.push({ role: "system", content });
2036
+ break;
2037
+ }
2038
+ case "developer": {
2039
+ input.push({ role: "developer", content });
2040
+ break;
2041
+ }
2042
+ case "remove": {
2043
+ warnings.push({
2044
+ type: "other",
2045
+ message: "system messages are removed for this model"
2046
+ });
2047
+ break;
2048
+ }
2049
+ default: {
2050
+ const _exhaustiveCheck = systemMessageMode;
2051
+ throw new Error(
2052
+ `Unsupported system message mode: ${_exhaustiveCheck}`
2053
+ );
2054
+ }
2055
+ }
2056
+ break;
2057
+ }
2058
+ case "user": {
2059
+ input.push({
2060
+ role: "user",
2061
+ content: content.map((part, index) => {
2062
+ var _a2, _b2, _c2;
2063
+ switch (part.type) {
2064
+ case "text": {
2065
+ return { type: "input_text", text: part.text };
2066
+ }
2067
+ case "file": {
2068
+ if (part.mediaType.startsWith("image/")) {
2069
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
2070
+ return {
2071
+ type: "input_image",
2072
+ ...part.data instanceof URL ? { image_url: part.data.toString() } : typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : {
2073
+ image_url: `data:${mediaType};base64,${convertToBase64(part.data)}`
2074
+ },
2075
+ detail: (_b2 = (_a2 = part.providerOptions) == null ? void 0 : _a2.openai) == null ? void 0 : _b2.imageDetail
2076
+ };
2077
+ } else if (part.mediaType === "application/pdf") {
2078
+ if (part.data instanceof URL) {
2079
+ return {
2080
+ type: "input_file",
2081
+ file_url: part.data.toString()
2082
+ };
2083
+ }
2084
+ return {
2085
+ type: "input_file",
2086
+ ...typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : {
2087
+ filename: (_c2 = part.filename) != null ? _c2 : `part-${index}.pdf`,
2088
+ file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`
2089
+ }
2090
+ };
2091
+ } else {
2092
+ throw new UnsupportedFunctionalityError({
2093
+ functionality: `file part media type ${part.mediaType}`
2094
+ });
2095
+ }
2096
+ }
2097
+ }
2098
+ })
2099
+ });
2100
+ break;
2101
+ }
2102
+ case "assistant": {
2103
+ const reasoningMessages = {};
2104
+ for (const part of content) {
2105
+ switch (part.type) {
2106
+ case "text": {
2107
+ const id = (_b = (_a = part.providerOptions) == null ? void 0 : _a.openai) == null ? void 0 : _b.itemId;
2108
+ if (store && id != null) {
2109
+ input.push({ type: "item_reference", id });
2110
+ break;
2111
+ }
2112
+ input.push({
2113
+ role: "assistant",
2114
+ content: [{ type: "output_text", text: part.text }],
2115
+ id
2116
+ });
2117
+ break;
2118
+ }
2119
+ case "tool-call": {
2120
+ if (part.providerExecuted) {
2121
+ break;
2122
+ }
2123
+ const id = (_d = (_c = part.providerOptions) == null ? void 0 : _c.openai) == null ? void 0 : _d.itemId;
2124
+ if (store && id != null) {
2125
+ input.push({ type: "item_reference", id });
2126
+ break;
2127
+ }
2128
+ if (hasLocalShellTool && part.toolName === "local_shell") {
2129
+ const parsedInput = await validateTypes({
2130
+ value: part.input,
2131
+ schema: localShellInputSchema
2132
+ });
2133
+ input.push({
2134
+ type: "local_shell_call",
2135
+ call_id: part.toolCallId,
2136
+ id,
2137
+ action: {
2138
+ type: "exec",
2139
+ command: parsedInput.action.command,
2140
+ timeout_ms: parsedInput.action.timeoutMs,
2141
+ user: parsedInput.action.user,
2142
+ working_directory: parsedInput.action.workingDirectory,
2143
+ env: parsedInput.action.env
2144
+ }
2145
+ });
2146
+ break;
2147
+ }
2148
+ input.push({
2149
+ type: "function_call",
2150
+ call_id: part.toolCallId,
2151
+ name: part.toolName,
2152
+ arguments: JSON.stringify(part.input),
2153
+ id
2154
+ });
2155
+ break;
2156
+ }
2157
+ // assistant tool result parts are from provider-executed tools:
2158
+ case "tool-result": {
2159
+ if (store) {
2160
+ input.push({ type: "item_reference", id: part.toolCallId });
2161
+ } else {
2162
+ warnings.push({
2163
+ type: "other",
2164
+ message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false`
2165
+ });
2166
+ }
2167
+ break;
2168
+ }
2169
+ case "reasoning": {
2170
+ const providerOptions = await parseProviderOptions({
2171
+ provider: "openai",
2172
+ providerOptions: part.providerOptions,
2173
+ schema: openaiResponsesReasoningProviderOptionsSchema
2174
+ });
2175
+ const reasoningId = providerOptions == null ? void 0 : providerOptions.itemId;
2176
+ if (reasoningId != null) {
2177
+ const reasoningMessage = reasoningMessages[reasoningId];
2178
+ if (store) {
2179
+ if (reasoningMessage === void 0) {
2180
+ input.push({ type: "item_reference", id: reasoningId });
2181
+ reasoningMessages[reasoningId] = {
2182
+ type: "reasoning",
2183
+ id: reasoningId,
2184
+ summary: []
2185
+ };
2186
+ }
2187
+ } else {
2188
+ const summaryParts = [];
2189
+ if (part.text.length > 0) {
2190
+ summaryParts.push({
2191
+ type: "summary_text",
2192
+ text: part.text
2193
+ });
2194
+ } else if (reasoningMessage !== void 0) {
2195
+ warnings.push({
2196
+ type: "other",
2197
+ message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.`
2198
+ });
2199
+ }
2200
+ if (reasoningMessage === void 0) {
2201
+ reasoningMessages[reasoningId] = {
2202
+ type: "reasoning",
2203
+ id: reasoningId,
2204
+ encrypted_content: providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent,
2205
+ summary: summaryParts
2206
+ };
2207
+ input.push(reasoningMessages[reasoningId]);
2208
+ } else {
2209
+ reasoningMessage.summary.push(...summaryParts);
2210
+ if ((providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent) != null) {
2211
+ reasoningMessage.encrypted_content = providerOptions.reasoningEncryptedContent;
2212
+ }
2213
+ }
2214
+ }
2215
+ } else {
2216
+ warnings.push({
2217
+ type: "other",
2218
+ message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
2219
+ });
2220
+ }
2221
+ break;
2222
+ }
2223
+ }
2224
+ }
2225
+ break;
2226
+ }
2227
+ case "tool": {
2228
+ for (const part of content) {
2229
+ const output = part.output;
2230
+ if (hasLocalShellTool && part.toolName === "local_shell" && output.type === "json") {
2231
+ const parsedOutput = await validateTypes({
2232
+ value: output.value,
2233
+ schema: localShellOutputSchema
2234
+ });
2235
+ input.push({
2236
+ type: "local_shell_call_output",
2237
+ call_id: part.toolCallId,
2238
+ output: parsedOutput.output
2239
+ });
2240
+ break;
2241
+ }
2242
+ let contentValue;
2243
+ switch (output.type) {
2244
+ case "text":
2245
+ case "error-text":
2246
+ contentValue = output.value;
2247
+ break;
2248
+ case "json":
2249
+ case "error-json":
2250
+ contentValue = JSON.stringify(output.value);
2251
+ break;
2252
+ case "content":
2253
+ contentValue = output.value.map((item) => {
2254
+ switch (item.type) {
2255
+ case "text": {
2256
+ return { type: "input_text", text: item.text };
2257
+ }
2258
+ case "media": {
2259
+ return item.mediaType.startsWith("image/") ? {
2260
+ type: "input_image",
2261
+ image_url: `data:${item.mediaType};base64,${item.data}`
2262
+ } : {
2263
+ type: "input_file",
2264
+ filename: "data",
2265
+ file_data: `data:${item.mediaType};base64,${item.data}`
2266
+ };
2267
+ }
2268
+ }
2269
+ });
2270
+ break;
2271
+ }
2272
+ input.push({
2273
+ type: "function_call_output",
2274
+ call_id: part.toolCallId,
2275
+ output: contentValue
2276
+ });
2277
+ }
2278
+ break;
2279
+ }
2280
+ default: {
2281
+ const _exhaustiveCheck = role;
2282
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
2283
+ }
2284
+ }
2285
+ }
2286
+ return { input, warnings };
2287
+ }
2288
+ var openaiResponsesReasoningProviderOptionsSchema = z.object({
2289
+ itemId: z.string().nullish(),
2290
+ reasoningEncryptedContent: z.string().nullish()
2291
+ });
2292
+ function mapOpenAIResponseFinishReason({
2293
+ finishReason,
2294
+ hasFunctionCall
2295
+ }) {
2296
+ switch (finishReason) {
2297
+ case void 0:
2298
+ case null:
2299
+ return hasFunctionCall ? "tool-calls" : "stop";
2300
+ case "max_output_tokens":
2301
+ return "length";
2302
+ case "content_filter":
2303
+ return "content-filter";
2304
+ default:
2305
+ return hasFunctionCall ? "tool-calls" : "unknown";
2306
+ }
2307
+ }
2308
+ var openaiResponsesChunkSchema = lazyValidator(
2309
+ () => zodSchema(
2310
+ z.union([
2311
+ z.object({
2312
+ type: z.literal("response.output_text.delta"),
2313
+ item_id: z.string(),
2314
+ delta: z.string(),
2315
+ logprobs: z.array(
2316
+ z.object({
2317
+ token: z.string(),
2318
+ logprob: z.number(),
2319
+ top_logprobs: z.array(
2320
+ z.object({
2321
+ token: z.string(),
2322
+ logprob: z.number()
2323
+ })
2324
+ )
2325
+ })
2326
+ ).nullish()
2327
+ }),
2328
+ z.object({
2329
+ type: z.enum(["response.completed", "response.incomplete"]),
2330
+ response: z.object({
2331
+ incomplete_details: z.object({ reason: z.string() }).nullish(),
2332
+ usage: z.object({
2333
+ input_tokens: z.number(),
2334
+ input_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
2335
+ output_tokens: z.number(),
2336
+ output_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish()
2337
+ }),
2338
+ service_tier: z.string().nullish()
2339
+ })
2340
+ }),
2341
+ z.object({
2342
+ type: z.literal("response.created"),
2343
+ response: z.object({
2344
+ id: z.string(),
2345
+ created_at: z.number(),
2346
+ model: z.string(),
2347
+ service_tier: z.string().nullish()
2348
+ })
2349
+ }),
2350
+ z.object({
2351
+ type: z.literal("response.output_item.added"),
2352
+ output_index: z.number(),
2353
+ item: z.discriminatedUnion("type", [
2354
+ z.object({
2355
+ type: z.literal("message"),
2356
+ id: z.string()
2357
+ }),
2358
+ z.object({
2359
+ type: z.literal("reasoning"),
2360
+ id: z.string(),
2361
+ encrypted_content: z.string().nullish()
2362
+ }),
2363
+ z.object({
2364
+ type: z.literal("function_call"),
2365
+ id: z.string(),
2366
+ call_id: z.string(),
2367
+ name: z.string(),
2368
+ arguments: z.string()
2369
+ }),
2370
+ z.object({
2371
+ type: z.literal("web_search_call"),
2372
+ id: z.string(),
2373
+ status: z.string()
2374
+ }),
2375
+ z.object({
2376
+ type: z.literal("computer_call"),
2377
+ id: z.string(),
2378
+ status: z.string()
2379
+ }),
2380
+ z.object({
2381
+ type: z.literal("file_search_call"),
2382
+ id: z.string()
2383
+ }),
2384
+ z.object({
2385
+ type: z.literal("image_generation_call"),
2386
+ id: z.string()
2387
+ }),
2388
+ z.object({
2389
+ type: z.literal("code_interpreter_call"),
2390
+ id: z.string(),
2391
+ container_id: z.string(),
2392
+ code: z.string().nullable(),
2393
+ outputs: z.array(
2394
+ z.discriminatedUnion("type", [
2395
+ z.object({ type: z.literal("logs"), logs: z.string() }),
2396
+ z.object({ type: z.literal("image"), url: z.string() })
2397
+ ])
2398
+ ).nullable(),
2399
+ status: z.string()
2400
+ })
2401
+ ])
2402
+ }),
2403
+ z.object({
2404
+ type: z.literal("response.output_item.done"),
2405
+ output_index: z.number(),
2406
+ item: z.discriminatedUnion("type", [
2407
+ z.object({
2408
+ type: z.literal("message"),
2409
+ id: z.string()
2410
+ }),
2411
+ z.object({
2412
+ type: z.literal("reasoning"),
2413
+ id: z.string(),
2414
+ encrypted_content: z.string().nullish()
2415
+ }),
2416
+ z.object({
2417
+ type: z.literal("function_call"),
2418
+ id: z.string(),
2419
+ call_id: z.string(),
2420
+ name: z.string(),
2421
+ arguments: z.string(),
2422
+ status: z.literal("completed")
2423
+ }),
2424
+ z.object({
2425
+ type: z.literal("code_interpreter_call"),
2426
+ id: z.string(),
2427
+ code: z.string().nullable(),
2428
+ container_id: z.string(),
2429
+ outputs: z.array(
2430
+ z.discriminatedUnion("type", [
2431
+ z.object({ type: z.literal("logs"), logs: z.string() }),
2432
+ z.object({ type: z.literal("image"), url: z.string() })
2433
+ ])
2434
+ ).nullable()
2435
+ }),
2436
+ z.object({
2437
+ type: z.literal("image_generation_call"),
2438
+ id: z.string(),
2439
+ result: z.string()
2440
+ }),
2441
+ z.object({
2442
+ type: z.literal("web_search_call"),
2443
+ id: z.string(),
2444
+ status: z.string(),
2445
+ action: z.discriminatedUnion("type", [
2446
+ z.object({
2447
+ type: z.literal("search"),
2448
+ query: z.string().nullish(),
2449
+ sources: z.array(
2450
+ z.discriminatedUnion("type", [
2451
+ z.object({ type: z.literal("url"), url: z.string() }),
2452
+ z.object({ type: z.literal("api"), name: z.string() })
2453
+ ])
2454
+ ).nullish()
2455
+ }),
2456
+ z.object({
2457
+ type: z.literal("open_page"),
2458
+ url: z.string()
2459
+ }),
2460
+ z.object({
2461
+ type: z.literal("find"),
2462
+ url: z.string(),
2463
+ pattern: z.string()
2464
+ })
2465
+ ])
2466
+ }),
2467
+ z.object({
2468
+ type: z.literal("file_search_call"),
2469
+ id: z.string(),
2470
+ queries: z.array(z.string()),
2471
+ results: z.array(
2472
+ z.object({
2473
+ attributes: z.record(z.string(), z.unknown()),
2474
+ file_id: z.string(),
2475
+ filename: z.string(),
2476
+ score: z.number(),
2477
+ text: z.string()
2478
+ })
2479
+ ).nullish()
2480
+ }),
2481
+ z.object({
2482
+ type: z.literal("local_shell_call"),
2483
+ id: z.string(),
2484
+ call_id: z.string(),
2485
+ action: z.object({
2486
+ type: z.literal("exec"),
2487
+ command: z.array(z.string()),
2488
+ timeout_ms: z.number().optional(),
2489
+ user: z.string().optional(),
2490
+ working_directory: z.string().optional(),
2491
+ env: z.record(z.string(), z.string()).optional()
2492
+ })
2493
+ }),
2494
+ z.object({
2495
+ type: z.literal("computer_call"),
2496
+ id: z.string(),
2497
+ status: z.literal("completed")
2498
+ })
2499
+ ])
2500
+ }),
2501
+ z.object({
2502
+ type: z.literal("response.function_call_arguments.delta"),
2503
+ item_id: z.string(),
2504
+ output_index: z.number(),
2505
+ delta: z.string()
2506
+ }),
2507
+ z.object({
2508
+ type: z.literal("response.image_generation_call.partial_image"),
2509
+ item_id: z.string(),
2510
+ output_index: z.number(),
2511
+ partial_image_b64: z.string()
2512
+ }),
2513
+ z.object({
2514
+ type: z.literal("response.code_interpreter_call_code.delta"),
2515
+ item_id: z.string(),
2516
+ output_index: z.number(),
2517
+ delta: z.string()
2518
+ }),
2519
+ z.object({
2520
+ type: z.literal("response.code_interpreter_call_code.done"),
2521
+ item_id: z.string(),
2522
+ output_index: z.number(),
2523
+ code: z.string()
2524
+ }),
2525
+ z.object({
2526
+ type: z.literal("response.output_text.annotation.added"),
2527
+ annotation: z.discriminatedUnion("type", [
2528
+ z.object({
2529
+ type: z.literal("url_citation"),
2530
+ start_index: z.number(),
2531
+ end_index: z.number(),
2532
+ url: z.string(),
2533
+ title: z.string()
2534
+ }),
2535
+ z.object({
2536
+ type: z.literal("file_citation"),
2537
+ file_id: z.string(),
2538
+ filename: z.string().nullish(),
2539
+ index: z.number().nullish(),
2540
+ start_index: z.number().nullish(),
2541
+ end_index: z.number().nullish(),
2542
+ quote: z.string().nullish()
2543
+ })
2544
+ ])
2545
+ }),
2546
+ z.object({
2547
+ type: z.literal("response.reasoning_summary_part.added"),
2548
+ item_id: z.string(),
2549
+ summary_index: z.number()
2550
+ }),
2551
+ z.object({
2552
+ type: z.literal("response.reasoning_summary_text.delta"),
2553
+ item_id: z.string(),
2554
+ summary_index: z.number(),
2555
+ delta: z.string()
2556
+ }),
2557
+ z.object({
2558
+ type: z.literal("response.reasoning_summary_part.done"),
2559
+ item_id: z.string(),
2560
+ summary_index: z.number()
2561
+ }),
2562
+ z.object({
2563
+ type: z.literal("error"),
2564
+ sequence_number: z.number(),
2565
+ error: z.object({
2566
+ type: z.string(),
2567
+ code: z.string(),
2568
+ message: z.string(),
2569
+ param: z.string().nullish()
2570
+ })
2571
+ }),
2572
+ z.object({ type: z.string() }).loose().transform((value) => ({
2573
+ type: "unknown_chunk",
2574
+ message: value.type
2575
+ }))
2576
+ // fallback for unknown chunks
2577
+ ])
2578
+ )
2579
+ );
2580
+ var openaiResponsesResponseSchema = lazyValidator(
2581
+ () => zodSchema(
2582
+ z.object({
2583
+ id: z.string().optional(),
2584
+ created_at: z.number().optional(),
2585
+ error: z.object({
2586
+ message: z.string(),
2587
+ type: z.string(),
2588
+ param: z.string().nullish(),
2589
+ code: z.string()
2590
+ }).nullish(),
2591
+ model: z.string().optional(),
2592
+ output: z.array(
2593
+ z.discriminatedUnion("type", [
2594
+ z.object({
2595
+ type: z.literal("message"),
2596
+ role: z.literal("assistant"),
2597
+ id: z.string(),
2598
+ content: z.array(
2599
+ z.object({
2600
+ type: z.literal("output_text"),
2601
+ text: z.string(),
2602
+ logprobs: z.array(
2603
+ z.object({
2604
+ token: z.string(),
2605
+ logprob: z.number(),
2606
+ top_logprobs: z.array(
2607
+ z.object({
2608
+ token: z.string(),
2609
+ logprob: z.number()
2610
+ })
2611
+ )
2612
+ })
2613
+ ).nullish(),
2614
+ annotations: z.array(
2615
+ z.discriminatedUnion("type", [
2616
+ z.object({
2617
+ type: z.literal("url_citation"),
2618
+ start_index: z.number(),
2619
+ end_index: z.number(),
2620
+ url: z.string(),
2621
+ title: z.string()
2622
+ }),
2623
+ z.object({
2624
+ type: z.literal("file_citation"),
2625
+ file_id: z.string(),
2626
+ filename: z.string().nullish(),
2627
+ index: z.number().nullish(),
2628
+ start_index: z.number().nullish(),
2629
+ end_index: z.number().nullish(),
2630
+ quote: z.string().nullish()
2631
+ }),
2632
+ z.object({
2633
+ type: z.literal("container_file_citation"),
2634
+ container_id: z.string(),
2635
+ file_id: z.string(),
2636
+ filename: z.string().nullish(),
2637
+ start_index: z.number().nullish(),
2638
+ end_index: z.number().nullish(),
2639
+ index: z.number().nullish()
2640
+ }),
2641
+ z.object({
2642
+ type: z.literal("file_path"),
2643
+ file_id: z.string(),
2644
+ index: z.number().nullish()
2645
+ })
2646
+ ])
2647
+ )
2648
+ })
2649
+ )
2650
+ }),
2651
+ z.object({
2652
+ type: z.literal("web_search_call"),
2653
+ id: z.string(),
2654
+ status: z.string(),
2655
+ action: z.discriminatedUnion("type", [
2656
+ z.object({
2657
+ type: z.literal("search"),
2658
+ query: z.string().nullish(),
2659
+ sources: z.array(
2660
+ z.discriminatedUnion("type", [
2661
+ z.object({ type: z.literal("url"), url: z.string() }),
2662
+ z.object({ type: z.literal("api"), name: z.string() })
2663
+ ])
2664
+ ).nullish()
2665
+ }),
2666
+ z.object({
2667
+ type: z.literal("open_page"),
2668
+ url: z.string()
2669
+ }),
2670
+ z.object({
2671
+ type: z.literal("find"),
2672
+ url: z.string(),
2673
+ pattern: z.string()
2674
+ })
2675
+ ])
2676
+ }),
2677
+ z.object({
2678
+ type: z.literal("file_search_call"),
2679
+ id: z.string(),
2680
+ queries: z.array(z.string()),
2681
+ results: z.array(
2682
+ z.object({
2683
+ attributes: z.record(
2684
+ z.string(),
2685
+ z.union([z.string(), z.number(), z.boolean()])
2686
+ ),
2687
+ file_id: z.string(),
2688
+ filename: z.string(),
2689
+ score: z.number(),
2690
+ text: z.string()
2691
+ })
2692
+ ).nullish()
2693
+ }),
2694
+ z.object({
2695
+ type: z.literal("code_interpreter_call"),
2696
+ id: z.string(),
2697
+ code: z.string().nullable(),
2698
+ container_id: z.string(),
2699
+ outputs: z.array(
2700
+ z.discriminatedUnion("type", [
2701
+ z.object({ type: z.literal("logs"), logs: z.string() }),
2702
+ z.object({ type: z.literal("image"), url: z.string() })
2703
+ ])
2704
+ ).nullable()
2705
+ }),
2706
+ z.object({
2707
+ type: z.literal("image_generation_call"),
2708
+ id: z.string(),
2709
+ result: z.string()
2710
+ }),
2711
+ z.object({
2712
+ type: z.literal("local_shell_call"),
2713
+ id: z.string(),
2714
+ call_id: z.string(),
2715
+ action: z.object({
2716
+ type: z.literal("exec"),
2717
+ command: z.array(z.string()),
2718
+ timeout_ms: z.number().optional(),
2719
+ user: z.string().optional(),
2720
+ working_directory: z.string().optional(),
2721
+ env: z.record(z.string(), z.string()).optional()
2722
+ })
2723
+ }),
2724
+ z.object({
2725
+ type: z.literal("function_call"),
2726
+ call_id: z.string(),
2727
+ name: z.string(),
2728
+ arguments: z.string(),
2729
+ id: z.string()
2730
+ }),
2731
+ z.object({
2732
+ type: z.literal("computer_call"),
2733
+ id: z.string(),
2734
+ status: z.string().optional()
2735
+ }),
2736
+ z.object({
2737
+ type: z.literal("reasoning"),
2738
+ id: z.string(),
2739
+ encrypted_content: z.string().nullish(),
2740
+ summary: z.array(
2741
+ z.object({
2742
+ type: z.literal("summary_text"),
2743
+ text: z.string()
2744
+ })
2745
+ )
2746
+ })
2747
+ ])
2748
+ ).optional(),
2749
+ service_tier: z.string().nullish(),
2750
+ incomplete_details: z.object({ reason: z.string() }).nullish(),
2751
+ usage: z.object({
2752
+ input_tokens: z.number(),
2753
+ input_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
2754
+ output_tokens: z.number(),
2755
+ output_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish()
2756
+ }).optional()
2757
+ })
2758
+ )
2759
+ );
2760
+ var TOP_LOGPROBS_MAX = 20;
2761
+ var openaiResponsesProviderOptionsSchema = lazyValidator(
2762
+ () => zodSchema(
2763
+ z.object({
2764
+ conversation: z.string().nullish(),
2765
+ include: z.array(
2766
+ z.enum([
2767
+ "reasoning.encrypted_content",
2768
+ // handled internally by default, only needed for unknown reasoning models
2769
+ "file_search_call.results",
2770
+ "message.output_text.logprobs"
2771
+ ])
2772
+ ).nullish(),
2773
+ instructions: z.string().nullish(),
2774
+ /**
2775
+ * Return the log probabilities of the tokens.
2776
+ *
2777
+ * Setting to true will return the log probabilities of the tokens that
2778
+ * were generated.
2779
+ *
2780
+ * Setting to a number will return the log probabilities of the top n
2781
+ * tokens that were generated.
2782
+ *
2783
+ * @see https://platform.openai.com/docs/api-reference/responses/create
2784
+ * @see https://cookbook.openai.com/examples/using_logprobs
2785
+ */
2786
+ logprobs: z.union([z.boolean(), z.number().min(1).max(TOP_LOGPROBS_MAX)]).optional(),
2787
+ /**
2788
+ * The maximum number of total calls to built-in tools that can be processed in a response.
2789
+ * This maximum number applies across all built-in tool calls, not per individual tool.
2790
+ * Any further attempts to call a tool by the model will be ignored.
2791
+ */
2792
+ maxToolCalls: z.number().nullish(),
2793
+ metadata: z.any().nullish(),
2794
+ parallelToolCalls: z.boolean().nullish(),
2795
+ previousResponseId: z.string().nullish(),
2796
+ promptCacheKey: z.string().nullish(),
2797
+ /**
2798
+ * The retention policy for the prompt cache.
2799
+ * - 'in_memory': Default. Standard prompt caching behavior.
2800
+ * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours.
2801
+ * Currently only available for 5.1 series models.
2802
+ *
2803
+ * @default 'in_memory'
2804
+ */
2805
+ promptCacheRetention: z.enum(["in_memory", "24h"]).nullish(),
2806
+ reasoningEffort: z.string().nullish(),
2807
+ reasoningSummary: z.string().nullish(),
2808
+ safetyIdentifier: z.string().nullish(),
2809
+ serviceTier: z.enum(["auto", "flex", "priority", "default"]).nullish(),
2810
+ store: z.boolean().nullish(),
2811
+ strictJsonSchema: z.boolean().nullish(),
2812
+ textVerbosity: z.enum(["low", "medium", "high"]).nullish(),
2813
+ truncation: z.enum(["auto", "disabled"]).nullish(),
2814
+ user: z.string().nullish()
2815
+ })
2816
+ )
2817
+ );
2818
+ var codeInterpreterInputSchema = lazySchema(
2819
+ () => zodSchema(
2820
+ z.object({
2821
+ code: z.string().nullish(),
2822
+ containerId: z.string()
2823
+ })
2824
+ )
2825
+ );
2826
+ var codeInterpreterOutputSchema = lazySchema(
2827
+ () => zodSchema(
2828
+ z.object({
2829
+ outputs: z.array(
2830
+ z.discriminatedUnion("type", [
2831
+ z.object({ type: z.literal("logs"), logs: z.string() }),
2832
+ z.object({ type: z.literal("image"), url: z.string() })
2833
+ ])
2834
+ ).nullish()
2835
+ })
2836
+ )
2837
+ );
2838
+ var codeInterpreterArgsSchema = lazySchema(
2839
+ () => zodSchema(
2840
+ z.object({
2841
+ container: z.union([
2842
+ z.string(),
2843
+ z.object({
2844
+ fileIds: z.array(z.string()).optional()
2845
+ })
2846
+ ]).optional()
2847
+ })
2848
+ )
2849
+ );
2850
+ var codeInterpreterToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
2851
+ id: "openai.code_interpreter",
2852
+ name: "code_interpreter",
2853
+ inputSchema: codeInterpreterInputSchema,
2854
+ outputSchema: codeInterpreterOutputSchema
2855
+ });
2856
+ var codeInterpreter = (args = {}) => {
2857
+ return codeInterpreterToolFactory(args);
2858
+ };
2859
+ var comparisonFilterSchema = z.object({
2860
+ key: z.string(),
2861
+ type: z.enum(["eq", "ne", "gt", "gte", "lt", "lte"]),
2862
+ value: z.union([z.string(), z.number(), z.boolean()])
2863
+ });
2864
+ var compoundFilterSchema = z.object({
2865
+ type: z.enum(["and", "or"]),
2866
+ filters: z.array(
2867
+ z.union([comparisonFilterSchema, z.lazy(() => compoundFilterSchema)])
2868
+ )
2869
+ });
2870
+ var fileSearchArgsSchema = lazySchema(
2871
+ () => zodSchema(
2872
+ z.object({
2873
+ vectorStoreIds: z.array(z.string()),
2874
+ maxNumResults: z.number().optional(),
2875
+ ranking: z.object({
2876
+ ranker: z.string().optional(),
2877
+ scoreThreshold: z.number().optional()
2878
+ }).optional(),
2879
+ filters: z.union([comparisonFilterSchema, compoundFilterSchema]).optional()
2880
+ })
2881
+ )
2882
+ );
2883
+ var fileSearchOutputSchema = lazySchema(
2884
+ () => zodSchema(
2885
+ z.object({
2886
+ queries: z.array(z.string()),
2887
+ results: z.array(
2888
+ z.object({
2889
+ attributes: z.record(z.string(), z.unknown()),
2890
+ fileId: z.string(),
2891
+ filename: z.string(),
2892
+ score: z.number(),
2893
+ text: z.string()
2894
+ })
2895
+ ).nullable()
2896
+ })
2897
+ )
2898
+ );
2899
+ var fileSearch = createProviderDefinedToolFactoryWithOutputSchema({
2900
+ id: "openai.file_search",
2901
+ name: "file_search",
2902
+ inputSchema: z.object({}),
2903
+ outputSchema: fileSearchOutputSchema
2904
+ });
2905
+ var webSearchArgsSchema = lazySchema(
2906
+ () => zodSchema(
2907
+ z.object({
2908
+ externalWebAccess: z.boolean().optional(),
2909
+ filters: z.object({ allowedDomains: z.array(z.string()).optional() }).optional(),
2910
+ searchContextSize: z.enum(["low", "medium", "high"]).optional(),
2911
+ userLocation: z.object({
2912
+ type: z.literal("approximate"),
2913
+ country: z.string().optional(),
2914
+ city: z.string().optional(),
2915
+ region: z.string().optional(),
2916
+ timezone: z.string().optional()
2917
+ }).optional()
2918
+ })
2919
+ )
2920
+ );
2921
+ var webSearchInputSchema = lazySchema(() => zodSchema(z.object({})));
2922
+ var webSearchOutputSchema = lazySchema(
2923
+ () => zodSchema(
2924
+ z.object({
2925
+ action: z.discriminatedUnion("type", [
2926
+ z.object({
2927
+ type: z.literal("search"),
2928
+ query: z.string().optional()
2929
+ }),
2930
+ z.object({
2931
+ type: z.literal("openPage"),
2932
+ url: z.string()
2933
+ }),
2934
+ z.object({
2935
+ type: z.literal("find"),
2936
+ url: z.string(),
2937
+ pattern: z.string()
2938
+ })
2939
+ ]),
2940
+ sources: z.array(
2941
+ z.discriminatedUnion("type", [
2942
+ z.object({ type: z.literal("url"), url: z.string() }),
2943
+ z.object({ type: z.literal("api"), name: z.string() })
2944
+ ])
2945
+ ).optional()
2946
+ })
2947
+ )
2948
+ );
2949
+ createProviderDefinedToolFactoryWithOutputSchema({
2950
+ id: "openai.web_search",
2951
+ name: "web_search",
2952
+ inputSchema: webSearchInputSchema,
2953
+ outputSchema: webSearchOutputSchema
2954
+ });
2955
+ var webSearchPreviewArgsSchema = lazySchema(
2956
+ () => zodSchema(
2957
+ z.object({
2958
+ searchContextSize: z.enum(["low", "medium", "high"]).optional(),
2959
+ userLocation: z.object({
2960
+ type: z.literal("approximate"),
2961
+ country: z.string().optional(),
2962
+ city: z.string().optional(),
2963
+ region: z.string().optional(),
2964
+ timezone: z.string().optional()
2965
+ }).optional()
2966
+ })
2967
+ )
2968
+ );
2969
+ var webSearchPreviewInputSchema = lazySchema(
2970
+ () => zodSchema(z.object({}))
2971
+ );
2972
+ var webSearchPreviewOutputSchema = lazySchema(
2973
+ () => zodSchema(
2974
+ z.object({
2975
+ action: z.discriminatedUnion("type", [
2976
+ z.object({
2977
+ type: z.literal("search"),
2978
+ query: z.string().optional()
2979
+ }),
2980
+ z.object({
2981
+ type: z.literal("openPage"),
2982
+ url: z.string()
2983
+ }),
2984
+ z.object({
2985
+ type: z.literal("find"),
2986
+ url: z.string(),
2987
+ pattern: z.string()
2988
+ })
2989
+ ])
2990
+ })
2991
+ )
2992
+ );
2993
+ var webSearchPreview = createProviderDefinedToolFactoryWithOutputSchema({
2994
+ id: "openai.web_search_preview",
2995
+ name: "web_search_preview",
2996
+ inputSchema: webSearchPreviewInputSchema,
2997
+ outputSchema: webSearchPreviewOutputSchema
2998
+ });
2999
+ var imageGenerationArgsSchema = lazySchema(
3000
+ () => zodSchema(
3001
+ z.object({
3002
+ background: z.enum(["auto", "opaque", "transparent"]).optional(),
3003
+ inputFidelity: z.enum(["low", "high"]).optional(),
3004
+ inputImageMask: z.object({
3005
+ fileId: z.string().optional(),
3006
+ imageUrl: z.string().optional()
3007
+ }).optional(),
3008
+ model: z.string().optional(),
3009
+ moderation: z.enum(["auto"]).optional(),
3010
+ outputCompression: z.number().int().min(0).max(100).optional(),
3011
+ outputFormat: z.enum(["png", "jpeg", "webp"]).optional(),
3012
+ partialImages: z.number().int().min(0).max(3).optional(),
3013
+ quality: z.enum(["auto", "low", "medium", "high"]).optional(),
3014
+ size: z.enum(["1024x1024", "1024x1536", "1536x1024", "auto"]).optional()
3015
+ }).strict()
3016
+ )
3017
+ );
3018
+ var imageGenerationInputSchema = lazySchema(() => zodSchema(z.object({})));
3019
+ var imageGenerationOutputSchema = lazySchema(
3020
+ () => zodSchema(z.object({ result: z.string() }))
3021
+ );
3022
+ var imageGenerationToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
3023
+ id: "openai.image_generation",
3024
+ name: "image_generation",
3025
+ inputSchema: imageGenerationInputSchema,
3026
+ outputSchema: imageGenerationOutputSchema
3027
+ });
3028
+ var imageGeneration = (args = {}) => {
3029
+ return imageGenerationToolFactory(args);
3030
+ };
3031
+ async function prepareResponsesTools({
3032
+ tools,
3033
+ toolChoice,
3034
+ strictJsonSchema
3035
+ }) {
3036
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
3037
+ const toolWarnings = [];
3038
+ if (tools == null) {
3039
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
3040
+ }
3041
+ const openaiTools = [];
3042
+ for (const tool of tools) {
3043
+ switch (tool.type) {
3044
+ case "function":
3045
+ openaiTools.push({
3046
+ type: "function",
3047
+ name: tool.name,
3048
+ description: tool.description,
3049
+ parameters: tool.inputSchema,
3050
+ strict: strictJsonSchema
3051
+ });
3052
+ break;
3053
+ case "provider-defined": {
3054
+ switch (tool.id) {
3055
+ case "openai.file_search": {
3056
+ const args = await validateTypes({
3057
+ value: tool.args,
3058
+ schema: fileSearchArgsSchema
3059
+ });
3060
+ openaiTools.push({
3061
+ type: "file_search",
3062
+ vector_store_ids: args.vectorStoreIds,
3063
+ max_num_results: args.maxNumResults,
3064
+ ranking_options: args.ranking ? {
3065
+ ranker: args.ranking.ranker,
3066
+ score_threshold: args.ranking.scoreThreshold
3067
+ } : void 0,
3068
+ filters: args.filters
3069
+ });
3070
+ break;
3071
+ }
3072
+ case "openai.local_shell": {
3073
+ openaiTools.push({
3074
+ type: "local_shell"
3075
+ });
3076
+ break;
3077
+ }
3078
+ case "openai.web_search_preview": {
3079
+ const args = await validateTypes({
3080
+ value: tool.args,
3081
+ schema: webSearchPreviewArgsSchema
3082
+ });
3083
+ openaiTools.push({
3084
+ type: "web_search_preview",
3085
+ search_context_size: args.searchContextSize,
3086
+ user_location: args.userLocation
3087
+ });
3088
+ break;
3089
+ }
3090
+ case "openai.web_search": {
3091
+ const args = await validateTypes({
3092
+ value: tool.args,
3093
+ schema: webSearchArgsSchema
3094
+ });
3095
+ openaiTools.push({
3096
+ type: "web_search",
3097
+ filters: args.filters != null ? { allowed_domains: args.filters.allowedDomains } : void 0,
3098
+ external_web_access: args.externalWebAccess,
3099
+ search_context_size: args.searchContextSize,
3100
+ user_location: args.userLocation
3101
+ });
3102
+ break;
3103
+ }
3104
+ case "openai.code_interpreter": {
3105
+ const args = await validateTypes({
3106
+ value: tool.args,
3107
+ schema: codeInterpreterArgsSchema
3108
+ });
3109
+ openaiTools.push({
3110
+ type: "code_interpreter",
3111
+ container: args.container == null ? { type: "auto", file_ids: void 0 } : typeof args.container === "string" ? args.container : { type: "auto", file_ids: args.container.fileIds }
3112
+ });
3113
+ break;
3114
+ }
3115
+ case "openai.image_generation": {
3116
+ const args = await validateTypes({
3117
+ value: tool.args,
3118
+ schema: imageGenerationArgsSchema
3119
+ });
3120
+ openaiTools.push({
3121
+ type: "image_generation",
3122
+ background: args.background,
3123
+ input_fidelity: args.inputFidelity,
3124
+ input_image_mask: args.inputImageMask ? {
3125
+ file_id: args.inputImageMask.fileId,
3126
+ image_url: args.inputImageMask.imageUrl
3127
+ } : void 0,
3128
+ model: args.model,
3129
+ size: args.size,
3130
+ quality: args.quality,
3131
+ moderation: args.moderation,
3132
+ output_format: args.outputFormat,
3133
+ output_compression: args.outputCompression
3134
+ });
3135
+ break;
3136
+ }
3137
+ }
3138
+ break;
3139
+ }
3140
+ default:
3141
+ toolWarnings.push({ type: "unsupported-tool", tool });
3142
+ break;
3143
+ }
3144
+ }
3145
+ if (toolChoice == null) {
3146
+ return { tools: openaiTools, toolChoice: void 0, toolWarnings };
3147
+ }
3148
+ const type = toolChoice.type;
3149
+ switch (type) {
3150
+ case "auto":
3151
+ case "none":
3152
+ case "required":
3153
+ return { tools: openaiTools, toolChoice: type, toolWarnings };
3154
+ case "tool":
3155
+ return {
3156
+ tools: openaiTools,
3157
+ toolChoice: toolChoice.toolName === "code_interpreter" || toolChoice.toolName === "file_search" || toolChoice.toolName === "image_generation" || toolChoice.toolName === "web_search_preview" || toolChoice.toolName === "web_search" ? { type: toolChoice.toolName } : { type: "function", name: toolChoice.toolName },
3158
+ toolWarnings
3159
+ };
3160
+ default: {
3161
+ const _exhaustiveCheck = type;
3162
+ throw new UnsupportedFunctionalityError({
3163
+ functionality: `tool choice type: ${_exhaustiveCheck}`
3164
+ });
3165
+ }
3166
+ }
3167
+ }
3168
+ var OpenAIResponsesLanguageModel = class {
3169
+ constructor(modelId, config) {
3170
+ this.specificationVersion = "v2";
3171
+ this.supportedUrls = {
3172
+ "image/*": [/^https?:\/\/.*$/],
3173
+ "application/pdf": [/^https?:\/\/.*$/]
3174
+ };
3175
+ this.modelId = modelId;
3176
+ this.config = config;
3177
+ }
3178
+ get provider() {
3179
+ return this.config.provider;
3180
+ }
3181
+ async getArgs({
3182
+ maxOutputTokens,
3183
+ temperature,
3184
+ stopSequences,
3185
+ topP,
3186
+ topK,
3187
+ presencePenalty,
3188
+ frequencyPenalty,
3189
+ seed,
3190
+ prompt,
3191
+ providerOptions,
3192
+ tools,
3193
+ toolChoice,
3194
+ responseFormat
3195
+ }) {
3196
+ var _a, _b, _c, _d;
3197
+ const warnings = [];
3198
+ const modelConfig = getResponsesModelConfig(this.modelId);
3199
+ if (topK != null) {
3200
+ warnings.push({ type: "unsupported-setting", setting: "topK" });
3201
+ }
3202
+ if (seed != null) {
3203
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
3204
+ }
3205
+ if (presencePenalty != null) {
3206
+ warnings.push({
3207
+ type: "unsupported-setting",
3208
+ setting: "presencePenalty"
3209
+ });
3210
+ }
3211
+ if (frequencyPenalty != null) {
3212
+ warnings.push({
3213
+ type: "unsupported-setting",
3214
+ setting: "frequencyPenalty"
3215
+ });
3216
+ }
3217
+ if (stopSequences != null) {
3218
+ warnings.push({ type: "unsupported-setting", setting: "stopSequences" });
3219
+ }
3220
+ const openaiOptions = await parseProviderOptions({
3221
+ provider: "openai",
3222
+ providerOptions,
3223
+ schema: openaiResponsesProviderOptionsSchema
3224
+ });
3225
+ if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) {
3226
+ warnings.push({
3227
+ type: "unsupported-setting",
3228
+ setting: "conversation",
3229
+ details: "conversation and previousResponseId cannot be used together"
3230
+ });
3231
+ }
3232
+ const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
3233
+ prompt,
3234
+ systemMessageMode: modelConfig.systemMessageMode,
3235
+ fileIdPrefixes: this.config.fileIdPrefixes,
3236
+ store: (_a = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _a : true,
3237
+ hasLocalShellTool: hasOpenAITool("openai.local_shell")
3238
+ });
3239
+ warnings.push(...inputWarnings);
3240
+ const strictJsonSchema = (_b = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _b : false;
3241
+ let include = openaiOptions == null ? void 0 : openaiOptions.include;
3242
+ function addInclude(key) {
3243
+ if (include == null) {
3244
+ include = [key];
3245
+ } else if (!include.includes(key)) {
3246
+ include = [...include, key];
3247
+ }
3248
+ }
3249
+ function hasOpenAITool(id) {
3250
+ return (tools == null ? void 0 : tools.find(
3251
+ (tool) => tool.type === "provider-defined" && tool.id === id
3252
+ )) != null;
3253
+ }
3254
+ const topLogprobs = typeof (openaiOptions == null ? void 0 : openaiOptions.logprobs) === "number" ? openaiOptions == null ? void 0 : openaiOptions.logprobs : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0;
3255
+ if (topLogprobs) {
3256
+ addInclude("message.output_text.logprobs");
3257
+ }
3258
+ const webSearchToolName = (_c = tools == null ? void 0 : tools.find(
3259
+ (tool) => tool.type === "provider-defined" && (tool.id === "openai.web_search" || tool.id === "openai.web_search_preview")
3260
+ )) == null ? void 0 : _c.name;
3261
+ if (webSearchToolName) {
3262
+ addInclude("web_search_call.action.sources");
3263
+ }
3264
+ if (hasOpenAITool("openai.code_interpreter")) {
3265
+ addInclude("code_interpreter_call.outputs");
3266
+ }
3267
+ const store = openaiOptions == null ? void 0 : openaiOptions.store;
3268
+ if (store === false && modelConfig.isReasoningModel) {
3269
+ addInclude("reasoning.encrypted_content");
3270
+ }
3271
+ const baseArgs = {
3272
+ model: this.modelId,
3273
+ input,
3274
+ temperature,
3275
+ top_p: topP,
3276
+ max_output_tokens: maxOutputTokens,
3277
+ ...((responseFormat == null ? void 0 : responseFormat.type) === "json" || (openaiOptions == null ? void 0 : openaiOptions.textVerbosity)) && {
3278
+ text: {
3279
+ ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && {
3280
+ format: responseFormat.schema != null ? {
3281
+ type: "json_schema",
3282
+ strict: strictJsonSchema,
3283
+ name: (_d = responseFormat.name) != null ? _d : "response",
3284
+ description: responseFormat.description,
3285
+ schema: responseFormat.schema
3286
+ } : { type: "json_object" }
3287
+ },
3288
+ ...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && {
3289
+ verbosity: openaiOptions.textVerbosity
3290
+ }
3291
+ }
3292
+ },
3293
+ // provider options:
3294
+ conversation: openaiOptions == null ? void 0 : openaiOptions.conversation,
3295
+ max_tool_calls: openaiOptions == null ? void 0 : openaiOptions.maxToolCalls,
3296
+ metadata: openaiOptions == null ? void 0 : openaiOptions.metadata,
3297
+ parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls,
3298
+ previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId,
3299
+ store,
3300
+ user: openaiOptions == null ? void 0 : openaiOptions.user,
3301
+ instructions: openaiOptions == null ? void 0 : openaiOptions.instructions,
3302
+ service_tier: openaiOptions == null ? void 0 : openaiOptions.serviceTier,
3303
+ include,
3304
+ prompt_cache_key: openaiOptions == null ? void 0 : openaiOptions.promptCacheKey,
3305
+ prompt_cache_retention: openaiOptions == null ? void 0 : openaiOptions.promptCacheRetention,
3306
+ safety_identifier: openaiOptions == null ? void 0 : openaiOptions.safetyIdentifier,
3307
+ top_logprobs: topLogprobs,
3308
+ truncation: openaiOptions == null ? void 0 : openaiOptions.truncation,
3309
+ // model-specific settings:
3310
+ ...modelConfig.isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && {
3311
+ reasoning: {
3312
+ ...(openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && {
3313
+ effort: openaiOptions.reasoningEffort
3314
+ },
3315
+ ...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && {
3316
+ summary: openaiOptions.reasoningSummary
3317
+ }
3318
+ }
3319
+ }
3320
+ };
3321
+ if (modelConfig.isReasoningModel) {
3322
+ if (baseArgs.temperature != null) {
3323
+ baseArgs.temperature = void 0;
3324
+ warnings.push({
3325
+ type: "unsupported-setting",
3326
+ setting: "temperature",
3327
+ details: "temperature is not supported for reasoning models"
3328
+ });
3329
+ }
3330
+ if (baseArgs.top_p != null) {
3331
+ baseArgs.top_p = void 0;
3332
+ warnings.push({
3333
+ type: "unsupported-setting",
3334
+ setting: "topP",
3335
+ details: "topP is not supported for reasoning models"
3336
+ });
3337
+ }
3338
+ } else {
3339
+ if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) {
3340
+ warnings.push({
3341
+ type: "unsupported-setting",
3342
+ setting: "reasoningEffort",
3343
+ details: "reasoningEffort is not supported for non-reasoning models"
3344
+ });
3345
+ }
3346
+ if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) {
3347
+ warnings.push({
3348
+ type: "unsupported-setting",
3349
+ setting: "reasoningSummary",
3350
+ details: "reasoningSummary is not supported for non-reasoning models"
3351
+ });
3352
+ }
3353
+ }
3354
+ if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "flex" && !modelConfig.supportsFlexProcessing) {
3355
+ warnings.push({
3356
+ type: "unsupported-setting",
3357
+ setting: "serviceTier",
3358
+ details: "flex processing is only available for o3, o4-mini, and gpt-5 models"
3359
+ });
3360
+ delete baseArgs.service_tier;
3361
+ }
3362
+ if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "priority" && !modelConfig.supportsPriorityProcessing) {
3363
+ warnings.push({
3364
+ type: "unsupported-setting",
3365
+ setting: "serviceTier",
3366
+ details: "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"
3367
+ });
3368
+ delete baseArgs.service_tier;
3369
+ }
3370
+ const {
3371
+ tools: openaiTools,
3372
+ toolChoice: openaiToolChoice,
3373
+ toolWarnings
3374
+ } = await prepareResponsesTools({
3375
+ tools,
3376
+ toolChoice,
3377
+ strictJsonSchema
3378
+ });
3379
+ return {
3380
+ webSearchToolName,
3381
+ args: {
3382
+ ...baseArgs,
3383
+ tools: openaiTools,
3384
+ tool_choice: openaiToolChoice
3385
+ },
3386
+ warnings: [...warnings, ...toolWarnings],
3387
+ store
3388
+ };
3389
+ }
3390
+ async doGenerate(options) {
3391
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
3392
+ const {
3393
+ args: body,
3394
+ warnings,
3395
+ webSearchToolName
3396
+ } = await this.getArgs(options);
3397
+ const url = this.config.url({
3398
+ path: "/responses",
3399
+ modelId: this.modelId
3400
+ });
3401
+ const {
3402
+ responseHeaders,
3403
+ value: response,
3404
+ rawValue: rawResponse
3405
+ } = await postJsonToApi({
3406
+ url,
3407
+ headers: combineHeaders(this.config.headers(), options.headers),
3408
+ body,
3409
+ failedResponseHandler: openaiFailedResponseHandler,
3410
+ successfulResponseHandler: createJsonResponseHandler(
3411
+ openaiResponsesResponseSchema
3412
+ ),
3413
+ abortSignal: options.abortSignal,
3414
+ fetch: this.config.fetch
3415
+ });
3416
+ if (response.error) {
3417
+ throw new APICallError({
3418
+ message: response.error.message,
3419
+ url,
3420
+ requestBodyValues: body,
3421
+ statusCode: 400,
3422
+ responseHeaders,
3423
+ responseBody: rawResponse,
3424
+ isRetryable: false
3425
+ });
3426
+ }
3427
+ const content = [];
3428
+ const logprobs = [];
3429
+ let hasFunctionCall = false;
3430
+ for (const part of response.output) {
3431
+ switch (part.type) {
3432
+ case "reasoning": {
3433
+ if (part.summary.length === 0) {
3434
+ part.summary.push({ type: "summary_text", text: "" });
3435
+ }
3436
+ for (const summary of part.summary) {
3437
+ content.push({
3438
+ type: "reasoning",
3439
+ text: summary.text,
3440
+ providerMetadata: {
3441
+ openai: {
3442
+ itemId: part.id,
3443
+ reasoningEncryptedContent: (_a = part.encrypted_content) != null ? _a : null
3444
+ }
3445
+ }
3446
+ });
3447
+ }
3448
+ break;
3449
+ }
3450
+ case "image_generation_call": {
3451
+ content.push({
3452
+ type: "tool-call",
3453
+ toolCallId: part.id,
3454
+ toolName: "image_generation",
3455
+ input: "{}",
3456
+ providerExecuted: true
3457
+ });
3458
+ content.push({
3459
+ type: "tool-result",
3460
+ toolCallId: part.id,
3461
+ toolName: "image_generation",
3462
+ result: {
3463
+ result: part.result
3464
+ },
3465
+ providerExecuted: true
3466
+ });
3467
+ break;
3468
+ }
3469
+ case "local_shell_call": {
3470
+ content.push({
3471
+ type: "tool-call",
3472
+ toolCallId: part.call_id,
3473
+ toolName: "local_shell",
3474
+ input: JSON.stringify({
3475
+ action: part.action
3476
+ }),
3477
+ providerMetadata: {
3478
+ openai: {
3479
+ itemId: part.id
3480
+ }
3481
+ }
3482
+ });
3483
+ break;
3484
+ }
3485
+ case "message": {
3486
+ for (const contentPart of part.content) {
3487
+ if (((_c = (_b = options.providerOptions) == null ? void 0 : _b.openai) == null ? void 0 : _c.logprobs) && contentPart.logprobs) {
3488
+ logprobs.push(contentPart.logprobs);
3489
+ }
3490
+ content.push({
3491
+ type: "text",
3492
+ text: contentPart.text,
3493
+ providerMetadata: {
3494
+ openai: {
3495
+ itemId: part.id
3496
+ }
3497
+ }
3498
+ });
3499
+ for (const annotation of contentPart.annotations) {
3500
+ if (annotation.type === "url_citation") {
3501
+ content.push({
3502
+ type: "source",
3503
+ sourceType: "url",
3504
+ id: (_f = (_e = (_d = this.config).generateId) == null ? void 0 : _e.call(_d)) != null ? _f : generateId(),
3505
+ url: annotation.url,
3506
+ title: annotation.title
3507
+ });
3508
+ } else if (annotation.type === "file_citation") {
3509
+ content.push({
3510
+ type: "source",
3511
+ sourceType: "document",
3512
+ id: (_i = (_h = (_g = this.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId(),
3513
+ mediaType: "text/plain",
3514
+ title: (_k = (_j = annotation.quote) != null ? _j : annotation.filename) != null ? _k : "Document",
3515
+ filename: (_l = annotation.filename) != null ? _l : annotation.file_id,
3516
+ ...annotation.file_id ? {
3517
+ providerMetadata: {
3518
+ openai: {
3519
+ fileId: annotation.file_id
3520
+ }
3521
+ }
3522
+ } : {}
3523
+ });
3524
+ }
3525
+ }
3526
+ }
3527
+ break;
3528
+ }
3529
+ case "function_call": {
3530
+ hasFunctionCall = true;
3531
+ content.push({
3532
+ type: "tool-call",
3533
+ toolCallId: part.call_id,
3534
+ toolName: part.name,
3535
+ input: part.arguments,
3536
+ providerMetadata: {
3537
+ openai: {
3538
+ itemId: part.id
3539
+ }
3540
+ }
3541
+ });
3542
+ break;
3543
+ }
3544
+ case "web_search_call": {
3545
+ content.push({
3546
+ type: "tool-call",
3547
+ toolCallId: part.id,
3548
+ toolName: webSearchToolName != null ? webSearchToolName : "web_search",
3549
+ input: JSON.stringify({}),
3550
+ providerExecuted: true
3551
+ });
3552
+ content.push({
3553
+ type: "tool-result",
3554
+ toolCallId: part.id,
3555
+ toolName: webSearchToolName != null ? webSearchToolName : "web_search",
3556
+ result: mapWebSearchOutput(part.action),
3557
+ providerExecuted: true
3558
+ });
3559
+ break;
3560
+ }
3561
+ case "computer_call": {
3562
+ content.push({
3563
+ type: "tool-call",
3564
+ toolCallId: part.id,
3565
+ toolName: "computer_use",
3566
+ input: "",
3567
+ providerExecuted: true
3568
+ });
3569
+ content.push({
3570
+ type: "tool-result",
3571
+ toolCallId: part.id,
3572
+ toolName: "computer_use",
3573
+ result: {
3574
+ type: "computer_use_tool_result",
3575
+ status: part.status || "completed"
3576
+ },
3577
+ providerExecuted: true
3578
+ });
3579
+ break;
3580
+ }
3581
+ case "file_search_call": {
3582
+ content.push({
3583
+ type: "tool-call",
3584
+ toolCallId: part.id,
3585
+ toolName: "file_search",
3586
+ input: "{}",
3587
+ providerExecuted: true
3588
+ });
3589
+ content.push({
3590
+ type: "tool-result",
3591
+ toolCallId: part.id,
3592
+ toolName: "file_search",
3593
+ result: {
3594
+ queries: part.queries,
3595
+ results: (_n = (_m = part.results) == null ? void 0 : _m.map((result) => ({
3596
+ attributes: result.attributes,
3597
+ fileId: result.file_id,
3598
+ filename: result.filename,
3599
+ score: result.score,
3600
+ text: result.text
3601
+ }))) != null ? _n : null
3602
+ },
3603
+ providerExecuted: true
3604
+ });
3605
+ break;
3606
+ }
3607
+ case "code_interpreter_call": {
3608
+ content.push({
3609
+ type: "tool-call",
3610
+ toolCallId: part.id,
3611
+ toolName: "code_interpreter",
3612
+ input: JSON.stringify({
3613
+ code: part.code,
3614
+ containerId: part.container_id
3615
+ }),
3616
+ providerExecuted: true
3617
+ });
3618
+ content.push({
3619
+ type: "tool-result",
3620
+ toolCallId: part.id,
3621
+ toolName: "code_interpreter",
3622
+ result: {
3623
+ outputs: part.outputs
3624
+ },
3625
+ providerExecuted: true
3626
+ });
3627
+ break;
3628
+ }
3629
+ }
3630
+ }
3631
+ const providerMetadata = {
3632
+ openai: {
3633
+ ...response.id != null ? { responseId: response.id } : {}
3634
+ }
3635
+ };
3636
+ if (logprobs.length > 0) {
3637
+ providerMetadata.openai.logprobs = logprobs;
3638
+ }
3639
+ if (typeof response.service_tier === "string") {
3640
+ providerMetadata.openai.serviceTier = response.service_tier;
3641
+ }
3642
+ const usage = response.usage;
3643
+ return {
3644
+ content,
3645
+ finishReason: mapOpenAIResponseFinishReason({
3646
+ finishReason: (_o = response.incomplete_details) == null ? void 0 : _o.reason,
3647
+ hasFunctionCall
3648
+ }),
3649
+ usage: {
3650
+ inputTokens: usage.input_tokens,
3651
+ outputTokens: usage.output_tokens,
3652
+ totalTokens: usage.input_tokens + usage.output_tokens,
3653
+ reasoningTokens: (_q = (_p = usage.output_tokens_details) == null ? void 0 : _p.reasoning_tokens) != null ? _q : void 0,
3654
+ cachedInputTokens: (_s = (_r = usage.input_tokens_details) == null ? void 0 : _r.cached_tokens) != null ? _s : void 0
3655
+ },
3656
+ request: { body },
3657
+ response: {
3658
+ id: response.id,
3659
+ timestamp: new Date(response.created_at * 1e3),
3660
+ modelId: response.model,
3661
+ headers: responseHeaders,
3662
+ body: rawResponse
3663
+ },
3664
+ providerMetadata,
3665
+ warnings
3666
+ };
3667
+ }
3668
+ async doStream(options) {
3669
+ const {
3670
+ args: body,
3671
+ warnings,
3672
+ webSearchToolName,
3673
+ store
3674
+ } = await this.getArgs(options);
3675
+ const { responseHeaders, value: response } = await postJsonToApi({
3676
+ url: this.config.url({
3677
+ path: "/responses",
3678
+ modelId: this.modelId
3679
+ }),
3680
+ headers: combineHeaders(this.config.headers(), options.headers),
3681
+ body: {
3682
+ ...body,
3683
+ stream: true
3684
+ },
3685
+ failedResponseHandler: openaiFailedResponseHandler,
3686
+ successfulResponseHandler: createEventSourceResponseHandler(
3687
+ openaiResponsesChunkSchema
3688
+ ),
3689
+ abortSignal: options.abortSignal,
3690
+ fetch: this.config.fetch
3691
+ });
3692
+ const self = this;
3693
+ let finishReason = "unknown";
3694
+ const usage = {
3695
+ inputTokens: void 0,
3696
+ outputTokens: void 0,
3697
+ totalTokens: void 0
3698
+ };
3699
+ const logprobs = [];
3700
+ let responseId = null;
3701
+ const ongoingToolCalls = {};
3702
+ const ongoingAnnotations = [];
3703
+ let hasFunctionCall = false;
3704
+ const activeReasoning = {};
3705
+ let serviceTier;
3706
+ return {
3707
+ stream: response.pipeThrough(
3708
+ new TransformStream({
3709
+ start(controller) {
3710
+ controller.enqueue({ type: "stream-start", warnings });
3711
+ },
3712
+ transform(chunk, controller) {
3713
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
3714
+ if (options.includeRawChunks) {
3715
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3716
+ }
3717
+ if (!chunk.success) {
3718
+ finishReason = "error";
3719
+ controller.enqueue({ type: "error", error: chunk.error });
3720
+ return;
3721
+ }
3722
+ const value = chunk.value;
3723
+ if (isResponseOutputItemAddedChunk(value)) {
3724
+ if (value.item.type === "function_call") {
3725
+ ongoingToolCalls[value.output_index] = {
3726
+ toolName: value.item.name,
3727
+ toolCallId: value.item.call_id
3728
+ };
3729
+ controller.enqueue({
3730
+ type: "tool-input-start",
3731
+ id: value.item.call_id,
3732
+ toolName: value.item.name
3733
+ });
3734
+ } else if (value.item.type === "web_search_call") {
3735
+ ongoingToolCalls[value.output_index] = {
3736
+ toolName: webSearchToolName != null ? webSearchToolName : "web_search",
3737
+ toolCallId: value.item.id
3738
+ };
3739
+ controller.enqueue({
3740
+ type: "tool-input-start",
3741
+ id: value.item.id,
3742
+ toolName: webSearchToolName != null ? webSearchToolName : "web_search",
3743
+ providerExecuted: true
3744
+ });
3745
+ controller.enqueue({
3746
+ type: "tool-input-end",
3747
+ id: value.item.id
3748
+ });
3749
+ controller.enqueue({
3750
+ type: "tool-call",
3751
+ toolCallId: value.item.id,
3752
+ toolName: webSearchToolName != null ? webSearchToolName : "web_search",
3753
+ input: JSON.stringify({}),
3754
+ providerExecuted: true
3755
+ });
3756
+ } else if (value.item.type === "computer_call") {
3757
+ ongoingToolCalls[value.output_index] = {
3758
+ toolName: "computer_use",
3759
+ toolCallId: value.item.id
3760
+ };
3761
+ controller.enqueue({
3762
+ type: "tool-input-start",
3763
+ id: value.item.id,
3764
+ toolName: "computer_use",
3765
+ providerExecuted: true
3766
+ });
3767
+ } else if (value.item.type === "code_interpreter_call") {
3768
+ ongoingToolCalls[value.output_index] = {
3769
+ toolName: "code_interpreter",
3770
+ toolCallId: value.item.id,
3771
+ codeInterpreter: {
3772
+ containerId: value.item.container_id
3773
+ }
3774
+ };
3775
+ controller.enqueue({
3776
+ type: "tool-input-start",
3777
+ id: value.item.id,
3778
+ toolName: "code_interpreter",
3779
+ providerExecuted: true
3780
+ });
3781
+ controller.enqueue({
3782
+ type: "tool-input-delta",
3783
+ id: value.item.id,
3784
+ delta: `{"containerId":"${value.item.container_id}","code":"`
3785
+ });
3786
+ } else if (value.item.type === "file_search_call") {
3787
+ controller.enqueue({
3788
+ type: "tool-call",
3789
+ toolCallId: value.item.id,
3790
+ toolName: "file_search",
3791
+ input: "{}",
3792
+ providerExecuted: true
3793
+ });
3794
+ } else if (value.item.type === "image_generation_call") {
3795
+ controller.enqueue({
3796
+ type: "tool-call",
3797
+ toolCallId: value.item.id,
3798
+ toolName: "image_generation",
3799
+ input: "{}",
3800
+ providerExecuted: true
3801
+ });
3802
+ } else if (value.item.type === "message") {
3803
+ ongoingAnnotations.splice(0, ongoingAnnotations.length);
3804
+ controller.enqueue({
3805
+ type: "text-start",
3806
+ id: value.item.id,
3807
+ providerMetadata: {
3808
+ openai: {
3809
+ itemId: value.item.id
3810
+ }
3811
+ }
3812
+ });
3813
+ } else if (isResponseOutputItemAddedChunk(value) && value.item.type === "reasoning") {
3814
+ activeReasoning[value.item.id] = {
3815
+ encryptedContent: value.item.encrypted_content,
3816
+ summaryParts: { 0: "active" }
3817
+ };
3818
+ controller.enqueue({
3819
+ type: "reasoning-start",
3820
+ id: `${value.item.id}:0`,
3821
+ providerMetadata: {
3822
+ openai: {
3823
+ itemId: value.item.id,
3824
+ reasoningEncryptedContent: (_a = value.item.encrypted_content) != null ? _a : null
3825
+ }
3826
+ }
3827
+ });
3828
+ }
3829
+ } else if (isResponseOutputItemDoneChunk(value) && value.item.type !== "message") {
3830
+ if (value.item.type === "function_call") {
3831
+ ongoingToolCalls[value.output_index] = void 0;
3832
+ hasFunctionCall = true;
3833
+ controller.enqueue({
3834
+ type: "tool-input-end",
3835
+ id: value.item.call_id
3836
+ });
3837
+ controller.enqueue({
3838
+ type: "tool-call",
3839
+ toolCallId: value.item.call_id,
3840
+ toolName: value.item.name,
3841
+ input: value.item.arguments,
3842
+ providerMetadata: {
3843
+ openai: {
3844
+ itemId: value.item.id
3845
+ }
3846
+ }
3847
+ });
3848
+ } else if (value.item.type === "web_search_call") {
3849
+ ongoingToolCalls[value.output_index] = void 0;
3850
+ controller.enqueue({
3851
+ type: "tool-result",
3852
+ toolCallId: value.item.id,
3853
+ toolName: webSearchToolName != null ? webSearchToolName : "web_search",
3854
+ result: mapWebSearchOutput(value.item.action),
3855
+ providerExecuted: true
3856
+ });
3857
+ } else if (value.item.type === "computer_call") {
3858
+ ongoingToolCalls[value.output_index] = void 0;
3859
+ controller.enqueue({
3860
+ type: "tool-input-end",
3861
+ id: value.item.id
3862
+ });
3863
+ controller.enqueue({
3864
+ type: "tool-call",
3865
+ toolCallId: value.item.id,
3866
+ toolName: "computer_use",
3867
+ input: "",
3868
+ providerExecuted: true
3869
+ });
3870
+ controller.enqueue({
3871
+ type: "tool-result",
3872
+ toolCallId: value.item.id,
3873
+ toolName: "computer_use",
3874
+ result: {
3875
+ type: "computer_use_tool_result",
3876
+ status: value.item.status || "completed"
3877
+ },
3878
+ providerExecuted: true
3879
+ });
3880
+ } else if (value.item.type === "file_search_call") {
3881
+ ongoingToolCalls[value.output_index] = void 0;
3882
+ controller.enqueue({
3883
+ type: "tool-result",
3884
+ toolCallId: value.item.id,
3885
+ toolName: "file_search",
3886
+ result: {
3887
+ queries: value.item.queries,
3888
+ results: (_c = (_b = value.item.results) == null ? void 0 : _b.map((result) => ({
3889
+ attributes: result.attributes,
3890
+ fileId: result.file_id,
3891
+ filename: result.filename,
3892
+ score: result.score,
3893
+ text: result.text
3894
+ }))) != null ? _c : null
3895
+ },
3896
+ providerExecuted: true
3897
+ });
3898
+ } else if (value.item.type === "code_interpreter_call") {
3899
+ ongoingToolCalls[value.output_index] = void 0;
3900
+ controller.enqueue({
3901
+ type: "tool-result",
3902
+ toolCallId: value.item.id,
3903
+ toolName: "code_interpreter",
3904
+ result: {
3905
+ outputs: value.item.outputs
3906
+ },
3907
+ providerExecuted: true
3908
+ });
3909
+ } else if (value.item.type === "image_generation_call") {
3910
+ controller.enqueue({
3911
+ type: "tool-result",
3912
+ toolCallId: value.item.id,
3913
+ toolName: "image_generation",
3914
+ result: {
3915
+ result: value.item.result
3916
+ },
3917
+ providerExecuted: true
3918
+ });
3919
+ } else if (value.item.type === "local_shell_call") {
3920
+ ongoingToolCalls[value.output_index] = void 0;
3921
+ controller.enqueue({
3922
+ type: "tool-call",
3923
+ toolCallId: value.item.call_id,
3924
+ toolName: "local_shell",
3925
+ input: JSON.stringify({
3926
+ action: {
3927
+ type: "exec",
3928
+ command: value.item.action.command,
3929
+ timeoutMs: value.item.action.timeout_ms,
3930
+ user: value.item.action.user,
3931
+ workingDirectory: value.item.action.working_directory,
3932
+ env: value.item.action.env
3933
+ }
3934
+ }),
3935
+ providerMetadata: {
3936
+ openai: { itemId: value.item.id }
3937
+ }
3938
+ });
3939
+ } else if (value.item.type === "reasoning") {
3940
+ const activeReasoningPart = activeReasoning[value.item.id];
3941
+ const summaryPartIndices = Object.entries(
3942
+ activeReasoningPart.summaryParts
3943
+ ).filter(
3944
+ ([_, status]) => status === "active" || status === "can-conclude"
3945
+ ).map(([summaryIndex]) => summaryIndex);
3946
+ for (const summaryIndex of summaryPartIndices) {
3947
+ controller.enqueue({
3948
+ type: "reasoning-end",
3949
+ id: `${value.item.id}:${summaryIndex}`,
3950
+ providerMetadata: {
3951
+ openai: {
3952
+ itemId: value.item.id,
3953
+ reasoningEncryptedContent: (_d = value.item.encrypted_content) != null ? _d : null
3954
+ }
3955
+ }
3956
+ });
3957
+ }
3958
+ delete activeReasoning[value.item.id];
3959
+ }
3960
+ } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {
3961
+ const toolCall = ongoingToolCalls[value.output_index];
3962
+ if (toolCall != null) {
3963
+ controller.enqueue({
3964
+ type: "tool-input-delta",
3965
+ id: toolCall.toolCallId,
3966
+ delta: value.delta
3967
+ });
3968
+ }
3969
+ } else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) {
3970
+ const toolCall = ongoingToolCalls[value.output_index];
3971
+ if (toolCall != null) {
3972
+ controller.enqueue({
3973
+ type: "tool-input-delta",
3974
+ id: toolCall.toolCallId,
3975
+ // The delta is code, which is embedding in a JSON string.
3976
+ // To escape it, we use JSON.stringify and slice to remove the outer quotes.
3977
+ delta: JSON.stringify(value.delta).slice(1, -1)
3978
+ });
3979
+ }
3980
+ } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) {
3981
+ const toolCall = ongoingToolCalls[value.output_index];
3982
+ if (toolCall != null) {
3983
+ controller.enqueue({
3984
+ type: "tool-input-delta",
3985
+ id: toolCall.toolCallId,
3986
+ delta: '"}'
3987
+ });
3988
+ controller.enqueue({
3989
+ type: "tool-input-end",
3990
+ id: toolCall.toolCallId
3991
+ });
3992
+ controller.enqueue({
3993
+ type: "tool-call",
3994
+ toolCallId: toolCall.toolCallId,
3995
+ toolName: "code_interpreter",
3996
+ input: JSON.stringify({
3997
+ code: value.code,
3998
+ containerId: toolCall.codeInterpreter.containerId
3999
+ }),
4000
+ providerExecuted: true
4001
+ });
4002
+ }
4003
+ } else if (isResponseCreatedChunk(value)) {
4004
+ responseId = value.response.id;
4005
+ controller.enqueue({
4006
+ type: "response-metadata",
4007
+ id: value.response.id,
4008
+ timestamp: new Date(value.response.created_at * 1e3),
4009
+ modelId: value.response.model
4010
+ });
4011
+ } else if (isTextDeltaChunk(value)) {
4012
+ controller.enqueue({
4013
+ type: "text-delta",
4014
+ id: value.item_id,
4015
+ delta: value.delta
4016
+ });
4017
+ if (((_f = (_e = options.providerOptions) == null ? void 0 : _e.openai) == null ? void 0 : _f.logprobs) && value.logprobs) {
4018
+ logprobs.push(value.logprobs);
4019
+ }
4020
+ } else if (value.type === "response.reasoning_summary_part.added") {
4021
+ if (value.summary_index > 0) {
4022
+ const activeReasoningPart = activeReasoning[value.item_id];
4023
+ activeReasoningPart.summaryParts[value.summary_index] = "active";
4024
+ for (const summaryIndex of Object.keys(
4025
+ activeReasoningPart.summaryParts
4026
+ )) {
4027
+ if (activeReasoningPart.summaryParts[summaryIndex] === "can-conclude") {
4028
+ controller.enqueue({
4029
+ type: "reasoning-end",
4030
+ id: `${value.item_id}:${summaryIndex}`,
4031
+ providerMetadata: { openai: { itemId: value.item_id } }
4032
+ });
4033
+ activeReasoningPart.summaryParts[summaryIndex] = "concluded";
4034
+ }
4035
+ }
4036
+ controller.enqueue({
4037
+ type: "reasoning-start",
4038
+ id: `${value.item_id}:${value.summary_index}`,
4039
+ providerMetadata: {
4040
+ openai: {
4041
+ itemId: value.item_id,
4042
+ reasoningEncryptedContent: (_h = (_g = activeReasoning[value.item_id]) == null ? void 0 : _g.encryptedContent) != null ? _h : null
4043
+ }
4044
+ }
4045
+ });
4046
+ }
4047
+ } else if (value.type === "response.reasoning_summary_text.delta") {
4048
+ controller.enqueue({
4049
+ type: "reasoning-delta",
4050
+ id: `${value.item_id}:${value.summary_index}`,
4051
+ delta: value.delta,
4052
+ providerMetadata: {
4053
+ openai: {
4054
+ itemId: value.item_id
4055
+ }
4056
+ }
4057
+ });
4058
+ } else if (value.type === "response.reasoning_summary_part.done") {
4059
+ if (store) {
4060
+ controller.enqueue({
4061
+ type: "reasoning-end",
4062
+ id: `${value.item_id}:${value.summary_index}`,
4063
+ providerMetadata: {
4064
+ openai: { itemId: value.item_id }
4065
+ }
4066
+ });
4067
+ activeReasoning[value.item_id].summaryParts[value.summary_index] = "concluded";
4068
+ } else {
4069
+ activeReasoning[value.item_id].summaryParts[value.summary_index] = "can-conclude";
4070
+ }
4071
+ } else if (isResponseFinishedChunk(value)) {
4072
+ finishReason = mapOpenAIResponseFinishReason({
4073
+ finishReason: (_i = value.response.incomplete_details) == null ? void 0 : _i.reason,
4074
+ hasFunctionCall
4075
+ });
4076
+ usage.inputTokens = value.response.usage.input_tokens;
4077
+ usage.outputTokens = value.response.usage.output_tokens;
4078
+ usage.totalTokens = value.response.usage.input_tokens + value.response.usage.output_tokens;
4079
+ usage.reasoningTokens = (_k = (_j = value.response.usage.output_tokens_details) == null ? void 0 : _j.reasoning_tokens) != null ? _k : void 0;
4080
+ usage.cachedInputTokens = (_m = (_l = value.response.usage.input_tokens_details) == null ? void 0 : _l.cached_tokens) != null ? _m : void 0;
4081
+ if (typeof value.response.service_tier === "string") {
4082
+ serviceTier = value.response.service_tier;
4083
+ }
4084
+ } else if (isResponseAnnotationAddedChunk(value)) {
4085
+ ongoingAnnotations.push(value.annotation);
4086
+ if (value.annotation.type === "url_citation") {
4087
+ controller.enqueue({
4088
+ type: "source",
4089
+ sourceType: "url",
4090
+ id: (_p = (_o = (_n = self.config).generateId) == null ? void 0 : _o.call(_n)) != null ? _p : generateId(),
4091
+ url: value.annotation.url,
4092
+ title: value.annotation.title
4093
+ });
4094
+ } else if (value.annotation.type === "file_citation") {
4095
+ controller.enqueue({
4096
+ type: "source",
4097
+ sourceType: "document",
4098
+ id: (_s = (_r = (_q = self.config).generateId) == null ? void 0 : _r.call(_q)) != null ? _s : generateId(),
4099
+ mediaType: "text/plain",
4100
+ title: (_u = (_t = value.annotation.quote) != null ? _t : value.annotation.filename) != null ? _u : "Document",
4101
+ filename: (_v = value.annotation.filename) != null ? _v : value.annotation.file_id,
4102
+ ...value.annotation.file_id ? {
4103
+ providerMetadata: {
4104
+ openai: {
4105
+ fileId: value.annotation.file_id
4106
+ }
4107
+ }
4108
+ } : {}
4109
+ });
4110
+ }
4111
+ } else if (isResponseOutputItemDoneChunk(value) && value.item.type === "message") {
4112
+ controller.enqueue({
4113
+ type: "text-end",
4114
+ id: value.item.id,
4115
+ providerMetadata: {
4116
+ openai: {
4117
+ itemId: value.item.id,
4118
+ ...ongoingAnnotations.length > 0 && {
4119
+ annotations: ongoingAnnotations
4120
+ }
4121
+ }
4122
+ }
4123
+ });
4124
+ } else if (isErrorChunk(value)) {
4125
+ controller.enqueue({ type: "error", error: value });
4126
+ }
4127
+ },
4128
+ flush(controller) {
4129
+ const providerMetadata = {
4130
+ openai: {
4131
+ responseId
4132
+ }
4133
+ };
4134
+ if (logprobs.length > 0) {
4135
+ providerMetadata.openai.logprobs = logprobs;
4136
+ }
4137
+ if (serviceTier !== void 0) {
4138
+ providerMetadata.openai.serviceTier = serviceTier;
4139
+ }
4140
+ controller.enqueue({
4141
+ type: "finish",
4142
+ finishReason,
4143
+ usage,
4144
+ providerMetadata
4145
+ });
4146
+ }
4147
+ })
4148
+ ),
4149
+ request: { body },
4150
+ response: { headers: responseHeaders }
4151
+ };
4152
+ }
4153
+ };
4154
+ function isTextDeltaChunk(chunk) {
4155
+ return chunk.type === "response.output_text.delta";
4156
+ }
4157
+ function isResponseOutputItemDoneChunk(chunk) {
4158
+ return chunk.type === "response.output_item.done";
4159
+ }
4160
+ function isResponseFinishedChunk(chunk) {
4161
+ return chunk.type === "response.completed" || chunk.type === "response.incomplete";
4162
+ }
4163
+ function isResponseCreatedChunk(chunk) {
4164
+ return chunk.type === "response.created";
4165
+ }
4166
+ function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
4167
+ return chunk.type === "response.function_call_arguments.delta";
4168
+ }
4169
+ function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) {
4170
+ return chunk.type === "response.code_interpreter_call_code.delta";
4171
+ }
4172
+ function isResponseCodeInterpreterCallCodeDoneChunk(chunk) {
4173
+ return chunk.type === "response.code_interpreter_call_code.done";
4174
+ }
4175
+ function isResponseOutputItemAddedChunk(chunk) {
4176
+ return chunk.type === "response.output_item.added";
4177
+ }
4178
+ function isResponseAnnotationAddedChunk(chunk) {
4179
+ return chunk.type === "response.output_text.annotation.added";
4180
+ }
4181
+ function isErrorChunk(chunk) {
4182
+ return chunk.type === "error";
4183
+ }
4184
+ function getResponsesModelConfig(modelId) {
4185
+ const supportsFlexProcessing2 = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
4186
+ const supportsPriorityProcessing2 = modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") || modelId.startsWith("o3") || modelId.startsWith("o4-mini");
4187
+ const defaults = {
4188
+ systemMessageMode: "system",
4189
+ supportsFlexProcessing: supportsFlexProcessing2,
4190
+ supportsPriorityProcessing: supportsPriorityProcessing2
4191
+ };
4192
+ if (modelId.startsWith("gpt-5-chat")) {
4193
+ return {
4194
+ ...defaults,
4195
+ isReasoningModel: false
4196
+ };
4197
+ }
4198
+ if (modelId.startsWith("o") || modelId.startsWith("gpt-5") || modelId.startsWith("codex-") || modelId.startsWith("computer-use")) {
4199
+ return {
4200
+ ...defaults,
4201
+ isReasoningModel: true,
4202
+ systemMessageMode: "developer"
4203
+ };
4204
+ }
4205
+ return {
4206
+ ...defaults,
4207
+ isReasoningModel: false
4208
+ };
4209
+ }
4210
+ function mapWebSearchOutput(action) {
4211
+ var _a;
4212
+ switch (action.type) {
4213
+ case "search":
4214
+ return {
4215
+ action: { type: "search", query: (_a = action.query) != null ? _a : void 0 },
4216
+ // include sources when provided by the Responses API (behind include flag)
4217
+ ...action.sources != null && { sources: action.sources }
4218
+ };
4219
+ case "open_page":
4220
+ return { action: { type: "openPage", url: action.url } };
4221
+ case "find":
4222
+ return {
4223
+ action: { type: "find", url: action.url, pattern: action.pattern }
4224
+ };
4225
+ }
4226
+ }
4227
+
4228
+ // ../../node_modules/.pnpm/@ai-sdk+azure@2.0.74_zod@3.25.76/node_modules/@ai-sdk/azure/dist/index.mjs
4229
+ var azureOpenaiTools = {
4230
+ codeInterpreter,
4231
+ fileSearch,
4232
+ imageGeneration,
4233
+ webSearchPreview
4234
+ };
4235
+ var VERSION = "2.0.74" ;
4236
+ function createAzure(options = {}) {
4237
+ var _a;
4238
+ const getHeaders = () => {
4239
+ const baseHeaders = {
4240
+ "api-key": loadApiKey({
4241
+ apiKey: options.apiKey,
4242
+ environmentVariableName: "AZURE_API_KEY",
4243
+ description: "Azure OpenAI"
4244
+ }),
4245
+ ...options.headers
4246
+ };
4247
+ return withUserAgentSuffix(baseHeaders, `ai-sdk/azure/${VERSION}`);
4248
+ };
4249
+ const getResourceName = () => loadSetting({
4250
+ settingValue: options.resourceName,
4251
+ settingName: "resourceName",
4252
+ environmentVariableName: "AZURE_RESOURCE_NAME",
4253
+ description: "Azure OpenAI resource name"
4254
+ });
4255
+ const apiVersion = (_a = options.apiVersion) != null ? _a : "v1";
4256
+ const url = ({ path, modelId }) => {
4257
+ var _a2;
4258
+ const baseUrlPrefix = (_a2 = options.baseURL) != null ? _a2 : `https://${getResourceName()}.openai.azure.com/openai`;
4259
+ let fullUrl;
4260
+ if (options.useDeploymentBasedUrls) {
4261
+ fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path}`);
4262
+ } else {
4263
+ fullUrl = new URL(`${baseUrlPrefix}/v1${path}`);
4264
+ }
4265
+ fullUrl.searchParams.set("api-version", apiVersion);
4266
+ return fullUrl.toString();
4267
+ };
4268
+ const createChatModel = (deploymentName) => new OpenAIChatLanguageModel(deploymentName, {
4269
+ provider: "azure.chat",
4270
+ url,
4271
+ headers: getHeaders,
4272
+ fetch: options.fetch
4273
+ });
4274
+ const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
4275
+ provider: "azure.completion",
4276
+ url,
4277
+ headers: getHeaders,
4278
+ fetch: options.fetch
4279
+ });
4280
+ const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
4281
+ provider: "azure.embeddings",
4282
+ headers: getHeaders,
4283
+ url,
4284
+ fetch: options.fetch
4285
+ });
4286
+ const createResponsesModel = (modelId) => new OpenAIResponsesLanguageModel(modelId, {
4287
+ provider: "azure.responses",
4288
+ url,
4289
+ headers: getHeaders,
4290
+ fetch: options.fetch,
4291
+ fileIdPrefixes: ["assistant-"]
4292
+ });
4293
+ const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
4294
+ provider: "azure.image",
4295
+ url,
4296
+ headers: getHeaders,
4297
+ fetch: options.fetch
4298
+ });
4299
+ const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
4300
+ provider: "azure.transcription",
4301
+ url,
4302
+ headers: getHeaders,
4303
+ fetch: options.fetch
4304
+ });
4305
+ const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
4306
+ provider: "azure.speech",
4307
+ url,
4308
+ headers: getHeaders,
4309
+ fetch: options.fetch
4310
+ });
4311
+ const provider = function(deploymentId) {
4312
+ if (new.target) {
4313
+ throw new Error(
4314
+ "The Azure OpenAI model function cannot be called with the new keyword."
4315
+ );
4316
+ }
4317
+ return createChatModel(deploymentId);
4318
+ };
4319
+ provider.languageModel = createChatModel;
4320
+ provider.chat = createChatModel;
4321
+ provider.completion = createCompletionModel;
4322
+ provider.embedding = createEmbeddingModel;
4323
+ provider.image = createImageModel;
4324
+ provider.imageModel = createImageModel;
4325
+ provider.textEmbedding = createEmbeddingModel;
4326
+ provider.textEmbeddingModel = createEmbeddingModel;
4327
+ provider.responses = createResponsesModel;
4328
+ provider.transcription = createTranscriptionModel;
4329
+ provider.speech = createSpeechModel;
4330
+ provider.tools = azureOpenaiTools;
4331
+ return provider;
4332
+ }
4333
+ createAzure();
4334
+
4335
+ // src/llm/model/gateways/azure.ts
4336
+ var AzureOpenAIGateway = class extends MastraModelGateway {
4337
+ constructor(config) {
4338
+ super();
4339
+ this.config = config;
4340
+ this.validateConfig();
4341
+ }
4342
+ id = "azure-openai";
4343
+ name = "azure-openai";
4344
+ tokenCache = new InMemoryServerCache();
4345
+ validateConfig() {
4346
+ if (!this.config.resourceName) {
4347
+ throw new MastraError({
4348
+ id: "AZURE_GATEWAY_INVALID_CONFIG",
4349
+ domain: "LLM",
4350
+ category: "UNKNOWN",
4351
+ text: "resourceName is required for Azure OpenAI gateway"
4352
+ });
4353
+ }
4354
+ if (!this.config.apiKey) {
4355
+ throw new MastraError({
4356
+ id: "AZURE_GATEWAY_INVALID_CONFIG",
4357
+ domain: "LLM",
4358
+ category: "UNKNOWN",
4359
+ text: "apiKey is required for Azure OpenAI gateway"
4360
+ });
4361
+ }
4362
+ const hasDeployments = this.config.deployments && this.config.deployments.length > 0;
4363
+ const hasManagement = this.config.management !== void 0;
4364
+ if (hasDeployments && hasManagement) {
4365
+ console.warn(
4366
+ "[AzureOpenAIGateway] Both deployments and management credentials provided. Using static deployments list and ignoring management API."
4367
+ );
4368
+ }
4369
+ if (hasManagement) {
4370
+ this.getManagementCredentials(this.config.management);
4371
+ }
4372
+ }
4373
+ async fetchProviders() {
4374
+ if (this.config.deployments && this.config.deployments.length > 0) {
4375
+ return {
4376
+ "azure-openai": {
4377
+ apiKeyEnvVar: [],
4378
+ apiKeyHeader: "api-key",
4379
+ name: "Azure OpenAI",
4380
+ models: this.config.deployments,
4381
+ docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
4382
+ gateway: "azure-openai"
4383
+ }
4384
+ };
4385
+ }
4386
+ if (!this.config.management) {
4387
+ return {
4388
+ "azure-openai": {
4389
+ apiKeyEnvVar: [],
4390
+ apiKeyHeader: "api-key",
4391
+ name: "Azure OpenAI",
4392
+ models: [],
4393
+ docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
4394
+ gateway: "azure-openai"
4395
+ }
4396
+ };
4397
+ }
4398
+ try {
4399
+ const credentials = this.getManagementCredentials(this.config.management);
4400
+ const token = await this.getAzureADToken({
4401
+ tenantId: credentials.tenantId,
4402
+ clientId: credentials.clientId,
4403
+ clientSecret: credentials.clientSecret
4404
+ });
4405
+ const deployments = await this.fetchDeployments(token, {
4406
+ subscriptionId: credentials.subscriptionId,
4407
+ resourceGroup: credentials.resourceGroup,
4408
+ resourceName: this.config.resourceName
4409
+ });
4410
+ return {
4411
+ "azure-openai": {
4412
+ apiKeyEnvVar: [],
4413
+ apiKeyHeader: "api-key",
4414
+ name: "Azure OpenAI",
4415
+ models: deployments.map((d) => d.name),
4416
+ docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
4417
+ gateway: "azure-openai"
4418
+ }
4419
+ };
4420
+ } catch (error) {
4421
+ const errorMsg = error instanceof Error ? error.message : String(error);
4422
+ console.warn(
4423
+ `[AzureOpenAIGateway] Deployment discovery failed: ${errorMsg}`,
4424
+ "\nReturning fallback configuration. Azure OpenAI can still be used by manually specifying deployment names."
4425
+ );
4426
+ return {
4427
+ "azure-openai": {
4428
+ apiKeyEnvVar: [],
4429
+ apiKeyHeader: "api-key",
4430
+ name: "Azure OpenAI",
4431
+ models: [],
4432
+ docUrl: "https://learn.microsoft.com/en-us/azure/ai-services/openai/",
4433
+ gateway: "azure-openai"
4434
+ }
4435
+ };
4436
+ }
4437
+ }
4438
+ getManagementCredentials(management) {
4439
+ const { tenantId, clientId, clientSecret, subscriptionId, resourceGroup } = management;
4440
+ const missing = [];
4441
+ if (!tenantId) missing.push("tenantId");
4442
+ if (!clientId) missing.push("clientId");
4443
+ if (!clientSecret) missing.push("clientSecret");
4444
+ if (!subscriptionId) missing.push("subscriptionId");
4445
+ if (!resourceGroup) missing.push("resourceGroup");
4446
+ if (missing.length > 0) {
4447
+ throw new MastraError({
4448
+ id: "AZURE_MANAGEMENT_CREDENTIALS_MISSING",
4449
+ domain: "LLM",
4450
+ category: "UNKNOWN",
4451
+ text: `Management credentials incomplete. Missing: ${missing.join(", ")}. Required fields: tenantId, clientId, clientSecret, subscriptionId, resourceGroup.`
4452
+ });
4453
+ }
4454
+ return {
4455
+ tenantId,
4456
+ clientId,
4457
+ clientSecret,
4458
+ subscriptionId,
4459
+ resourceGroup
4460
+ };
4461
+ }
4462
+ async getAzureADToken(credentials) {
4463
+ const { tenantId, clientId, clientSecret } = credentials;
4464
+ const cacheKey = `azure-mgmt-token:${tenantId}:${clientId}`;
4465
+ const cached = await this.tokenCache.get(cacheKey);
4466
+ if (cached && cached.expiresAt > Date.now() / 1e3 + 60) {
4467
+ return cached.token;
4468
+ }
4469
+ const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
4470
+ const body = new URLSearchParams({
4471
+ grant_type: "client_credentials",
4472
+ client_id: clientId,
4473
+ client_secret: clientSecret,
4474
+ scope: "https://management.azure.com/.default"
4475
+ });
4476
+ const response = await fetch(tokenEndpoint, {
4477
+ method: "POST",
4478
+ headers: {
4479
+ "Content-Type": "application/x-www-form-urlencoded"
4480
+ },
4481
+ body: body.toString()
4482
+ });
4483
+ if (!response.ok) {
4484
+ const error = await response.text();
4485
+ throw new MastraError({
4486
+ id: "AZURE_AD_TOKEN_ERROR",
4487
+ domain: "LLM",
4488
+ category: "UNKNOWN",
4489
+ text: `Failed to get Azure AD token: ${response.status} ${error}`
4490
+ });
4491
+ }
4492
+ const tokenResponse = await response.json();
4493
+ const expiresAt = Math.floor(Date.now() / 1e3) + tokenResponse.expires_in;
4494
+ await this.tokenCache.set(cacheKey, {
4495
+ token: tokenResponse.access_token,
4496
+ expiresAt
4497
+ });
4498
+ return tokenResponse.access_token;
4499
+ }
4500
+ async fetchDeployments(token, credentials) {
4501
+ const { subscriptionId, resourceGroup, resourceName } = credentials;
4502
+ let url = `https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.CognitiveServices/accounts/${resourceName}/deployments?api-version=2024-10-01`;
4503
+ const allDeployments = [];
4504
+ while (url) {
4505
+ const response = await fetch(url, {
4506
+ headers: {
4507
+ Authorization: `Bearer ${token}`,
4508
+ "Content-Type": "application/json"
4509
+ }
4510
+ });
4511
+ if (!response.ok) {
4512
+ const error = await response.text();
4513
+ throw new MastraError({
4514
+ id: "AZURE_DEPLOYMENTS_FETCH_ERROR",
4515
+ domain: "LLM",
4516
+ category: "UNKNOWN",
4517
+ text: `Failed to fetch Azure deployments: ${response.status} ${error}`
4518
+ });
4519
+ }
4520
+ const data = await response.json();
4521
+ allDeployments.push(...data.value);
4522
+ url = data.nextLink;
4523
+ }
4524
+ const successfulDeployments = allDeployments.filter((d) => d.properties.provisioningState === "Succeeded");
4525
+ return successfulDeployments;
4526
+ }
4527
+ buildUrl(_routerId, _envVars) {
4528
+ return void 0;
4529
+ }
4530
+ async getApiKey(_modelId) {
4531
+ return this.config.apiKey;
4532
+ }
4533
+ async resolveLanguageModel({
4534
+ modelId,
4535
+ apiKey
4536
+ }) {
4537
+ const apiVersion = this.config.apiVersion || "2024-04-01-preview";
4538
+ return createAzure({
4539
+ resourceName: this.config.resourceName,
4540
+ apiKey,
4541
+ apiVersion,
4542
+ useDeploymentBasedUrls: true
4543
+ })(modelId);
4544
+ }
4545
+ };
4546
+
4547
+ // src/llm/model/gateways/index.ts
4548
+ function findGatewayForModel(gatewayId, gateways) {
4549
+ const prefixedGateway = gateways.find(
4550
+ (g) => g.id !== "models.dev" && (g.id === gatewayId || gatewayId.startsWith(`${g.id}/`))
4551
+ );
4552
+ if (prefixedGateway) {
4553
+ return prefixedGateway;
4554
+ }
4555
+ const modelsDevGateway = gateways.find((g) => g.id === "models.dev");
4556
+ if (modelsDevGateway) {
4557
+ return modelsDevGateway;
4558
+ }
4559
+ throw new MastraError({
4560
+ id: "MODEL_ROUTER_NO_GATEWAY_FOUND",
4561
+ category: "USER",
4562
+ domain: "MODEL_ROUTER",
4563
+ text: `No Mastra model router gateway found for model id ${gatewayId}`
4564
+ });
4565
+ }
4566
+
4567
+ // src/llm/model/router.ts
4568
+ function getStaticProvidersByGateway(name) {
4569
+ return Object.fromEntries(Object.entries(PROVIDER_REGISTRY).filter(([_provider, config]) => config.gateway === name));
4570
+ }
4571
+ var defaultGateways = [new NetlifyGateway(), new ModelsDevGateway(getStaticProvidersByGateway(`models.dev`))];
4572
+ var ModelRouterLanguageModel = class _ModelRouterLanguageModel {
4573
+ specificationVersion = "v2";
4574
+ defaultObjectGenerationMode = "json";
4575
+ supportsStructuredOutputs = true;
4576
+ supportsImageUrls = true;
4577
+ supportedUrls = {};
4578
+ modelId;
4579
+ provider;
4580
+ config;
4581
+ gateway;
4582
+ constructor(config, customGateways) {
4583
+ let normalizedConfig;
4584
+ if (typeof config === "string") {
4585
+ normalizedConfig = { id: config };
4586
+ } else if ("providerId" in config && "modelId" in config) {
4587
+ normalizedConfig = {
4588
+ id: `${config.providerId}/${config.modelId}`,
4589
+ url: config.url,
4590
+ apiKey: config.apiKey,
4591
+ headers: config.headers
4592
+ };
4593
+ } else {
4594
+ normalizedConfig = {
4595
+ id: config.id,
4596
+ url: config.url,
4597
+ apiKey: config.apiKey,
4598
+ headers: config.headers
4599
+ };
4600
+ }
4601
+ const parsedConfig = {
4602
+ ...normalizedConfig,
4603
+ routerId: normalizedConfig.id
4604
+ };
4605
+ this.gateway = findGatewayForModel(normalizedConfig.id, [...customGateways || [], ...defaultGateways]);
4606
+ const gatewayPrefix = this.gateway.id === "models.dev" ? void 0 : this.gateway.id;
4607
+ const parsed = parseModelRouterId(normalizedConfig.id, gatewayPrefix);
4608
+ this.provider = parsed.providerId || "openai-compatible";
4609
+ if (parsed.providerId && parsed.modelId !== normalizedConfig.id) {
4610
+ parsedConfig.id = parsed.modelId;
4611
+ }
4612
+ this.modelId = parsedConfig.id;
4613
+ this.config = parsedConfig;
4614
+ }
4615
+ async doGenerate(options) {
4616
+ let apiKey;
4617
+ try {
4618
+ if (this.config.url) {
4619
+ apiKey = this.config.apiKey || "";
4620
+ } else {
4621
+ apiKey = this.config.apiKey || await this.gateway.getApiKey(this.config.routerId);
4622
+ }
4623
+ } catch (error) {
4624
+ return {
4625
+ stream: new ReadableStream({
4626
+ start(controller) {
4627
+ controller.enqueue({
4628
+ type: "error",
4629
+ error
4630
+ });
4631
+ controller.close();
4632
+ }
4633
+ })
4634
+ };
4635
+ }
4636
+ const gatewayPrefix = this.gateway.id === "models.dev" ? void 0 : this.gateway.id;
4637
+ const model = await this.resolveLanguageModel({
4638
+ apiKey,
4639
+ headers: this.config.headers,
4640
+ ...parseModelRouterId(this.config.routerId, gatewayPrefix)
4641
+ });
4642
+ const aiSDKV5Model = new AISDKV5LanguageModel(model);
4643
+ return aiSDKV5Model.doGenerate(options);
4644
+ }
4645
+ async doStream(options) {
4646
+ let apiKey;
4647
+ try {
4648
+ if (this.config.url) {
4649
+ apiKey = this.config.apiKey || "";
4650
+ } else {
4651
+ apiKey = this.config.apiKey || await this.gateway.getApiKey(this.config.routerId);
4652
+ }
4653
+ } catch (error) {
4654
+ return {
4655
+ stream: new ReadableStream({
4656
+ start(controller) {
4657
+ controller.enqueue({
4658
+ type: "error",
4659
+ error
4660
+ });
4661
+ controller.close();
4662
+ }
4663
+ })
4664
+ };
4665
+ }
4666
+ const gatewayPrefix = this.gateway.id === "models.dev" ? void 0 : this.gateway.id;
4667
+ const model = await this.resolveLanguageModel({
4668
+ apiKey,
4669
+ headers: this.config.headers,
4670
+ ...parseModelRouterId(this.config.routerId, gatewayPrefix)
4671
+ });
4672
+ const aiSDKV5Model = new AISDKV5LanguageModel(model);
4673
+ return aiSDKV5Model.doStream(options);
4674
+ }
4675
+ async resolveLanguageModel({
4676
+ modelId,
4677
+ providerId,
4678
+ apiKey,
4679
+ headers
4680
+ }) {
4681
+ const key = createHash("sha256").update(
4682
+ this.gateway.id + modelId + providerId + apiKey + (this.config.url || "") + (headers ? JSON.stringify(headers) : "")
4683
+ ).digest("hex");
4684
+ if (_ModelRouterLanguageModel.modelInstances.has(key)) return _ModelRouterLanguageModel.modelInstances.get(key);
4685
+ if (this.config.url) {
4686
+ const modelInstance2 = createOpenAICompatible({
4687
+ name: providerId,
4688
+ apiKey,
4689
+ baseURL: this.config.url,
4690
+ headers: this.config.headers,
4691
+ supportsStructuredOutputs: true
4692
+ }).chatModel(modelId);
4693
+ _ModelRouterLanguageModel.modelInstances.set(key, modelInstance2);
4694
+ return modelInstance2;
4695
+ }
4696
+ const modelInstance = await this.gateway.resolveLanguageModel({ modelId, providerId, apiKey, headers });
4697
+ _ModelRouterLanguageModel.modelInstances.set(key, modelInstance);
4698
+ return modelInstance;
4699
+ }
4700
+ static modelInstances = /* @__PURE__ */ new Map();
4701
+ };
4702
+
4703
+ // src/llm/model/resolve-model.ts
4704
+ function isOpenAICompatibleObjectConfig(modelConfig) {
4705
+ if (typeof modelConfig === "object" && "specificationVersion" in modelConfig) return false;
4706
+ if (typeof modelConfig === "object" && !("model" in modelConfig)) {
4707
+ if ("id" in modelConfig) return true;
4708
+ if ("providerId" in modelConfig && "modelId" in modelConfig) return true;
4709
+ }
4710
+ return false;
4711
+ }
4712
+ async function resolveModelConfig(modelConfig, requestContext = new RequestContext(), mastra) {
4713
+ if (typeof modelConfig === "function") {
4714
+ modelConfig = await modelConfig({ requestContext, mastra });
4715
+ }
4716
+ if (modelConfig instanceof ModelRouterLanguageModel || modelConfig instanceof AISDKV5LanguageModel) {
4717
+ return modelConfig;
4718
+ }
4719
+ if (typeof modelConfig === "object" && "specificationVersion" in modelConfig) {
4720
+ if (modelConfig.specificationVersion === "v2") {
4721
+ return new AISDKV5LanguageModel(modelConfig);
4722
+ }
4723
+ return modelConfig;
4724
+ }
4725
+ const gatewayRecord = mastra?.listGateways();
4726
+ const customGateways = gatewayRecord ? Object.values(gatewayRecord) : void 0;
4727
+ if (typeof modelConfig === "string" || isOpenAICompatibleObjectConfig(modelConfig)) {
4728
+ return new ModelRouterLanguageModel(modelConfig, customGateways);
4729
+ }
4730
+ throw new Error("Invalid model configuration provided");
4731
+ }
4732
+
4733
+ // src/llm/model/embedding-router.ts
4734
+ var ModelRouterEmbeddingModel = class {
4735
+ specificationVersion = "v2";
4736
+ modelId;
4737
+ provider;
4738
+ maxEmbeddingsPerCall = 2048;
4739
+ supportsParallelCalls = true;
4740
+ providerModel;
4741
+ constructor(config) {
4742
+ let normalizedConfig;
4743
+ if (typeof config === "string") {
4744
+ const parts = config.split("/");
4745
+ if (parts.length !== 2) {
4746
+ throw new Error(`Invalid model string format: "${config}". Expected format: "provider/model"`);
4747
+ }
4748
+ const [providerId, modelId] = parts;
4749
+ normalizedConfig = { providerId, modelId };
4750
+ } else if ("providerId" in config && "modelId" in config) {
4751
+ normalizedConfig = {
4752
+ providerId: config.providerId,
4753
+ modelId: config.modelId,
4754
+ url: config.url,
4755
+ apiKey: config.apiKey,
4756
+ headers: config.headers
4757
+ };
4758
+ } else {
4759
+ const parts = config.id.split("/");
4760
+ if (parts.length !== 2) {
4761
+ throw new Error(`Invalid model string format: "${config.id}". Expected format: "provider/model"`);
4762
+ }
4763
+ const [providerId, modelId] = parts;
4764
+ normalizedConfig = {
4765
+ providerId,
4766
+ modelId,
4767
+ url: config.url,
4768
+ apiKey: config.apiKey,
4769
+ headers: config.headers
4770
+ };
4771
+ }
4772
+ this.provider = normalizedConfig.providerId;
4773
+ this.modelId = normalizedConfig.modelId;
4774
+ if (normalizedConfig.url) {
4775
+ const apiKey = normalizedConfig.apiKey || "";
4776
+ this.providerModel = createOpenAICompatible({
4777
+ name: normalizedConfig.providerId,
4778
+ apiKey,
4779
+ baseURL: normalizedConfig.url,
4780
+ headers: normalizedConfig.headers
4781
+ }).textEmbeddingModel(normalizedConfig.modelId);
4782
+ } else {
4783
+ const registry = GatewayRegistry.getInstance();
4784
+ const providerConfig = registry.getProviderConfig(normalizedConfig.providerId);
4785
+ if (!providerConfig) {
4786
+ throw new Error(`Unknown provider: ${normalizedConfig.providerId}`);
4787
+ }
4788
+ let apiKey = normalizedConfig.apiKey;
4789
+ if (!apiKey) {
4790
+ const apiKeyEnvVar = providerConfig.apiKeyEnvVar;
4791
+ if (Array.isArray(apiKeyEnvVar)) {
4792
+ for (const envVar of apiKeyEnvVar) {
4793
+ apiKey = process.env[envVar];
4794
+ if (apiKey) break;
4795
+ }
4796
+ } else {
4797
+ apiKey = process.env[apiKeyEnvVar];
4798
+ }
4799
+ }
4800
+ if (!apiKey) {
4801
+ const envVarDisplay = Array.isArray(providerConfig.apiKeyEnvVar) ? providerConfig.apiKeyEnvVar.join(" or ") : providerConfig.apiKeyEnvVar;
4802
+ throw new Error(`API key not found for provider ${normalizedConfig.providerId}. Set ${envVarDisplay}`);
4803
+ }
4804
+ if (normalizedConfig.providerId === "openai") {
4805
+ this.providerModel = createOpenAI({ apiKey }).textEmbeddingModel(
4806
+ normalizedConfig.modelId
4807
+ );
4808
+ } else if (normalizedConfig.providerId === "google") {
4809
+ this.providerModel = createGoogleGenerativeAI({ apiKey }).textEmbedding(
4810
+ normalizedConfig.modelId
4811
+ );
4812
+ } else {
4813
+ if (!providerConfig.url) {
4814
+ throw new Error(`Provider ${normalizedConfig.providerId} does not have a URL configured`);
4815
+ }
4816
+ this.providerModel = createOpenAICompatible({
4817
+ name: normalizedConfig.providerId,
4818
+ apiKey,
4819
+ baseURL: providerConfig.url
4820
+ }).textEmbeddingModel(normalizedConfig.modelId);
4821
+ }
4822
+ }
4823
+ if (this.providerModel.maxEmbeddingsPerCall !== void 0) {
4824
+ this.maxEmbeddingsPerCall = this.providerModel.maxEmbeddingsPerCall;
4825
+ }
4826
+ if (this.providerModel.supportsParallelCalls !== void 0) {
4827
+ this.supportsParallelCalls = this.providerModel.supportsParallelCalls;
4828
+ }
4829
+ }
4830
+ async doEmbed(args) {
4831
+ return this.providerModel.doEmbed(args);
4832
+ }
4833
+ };
4834
+
4835
+ export { AzureOpenAIGateway, ModelRouterEmbeddingModel, ModelRouterLanguageModel, resolveModelConfig };
4836
+ //# sourceMappingURL=chunk-5VZGJTPR.js.map
4837
+ //# sourceMappingURL=chunk-5VZGJTPR.js.map